13. Auth - Sessions
In this part, you will add session-based authentication to the Snippets API and compare it to your JWT-based approach.
We will:
Configure
express-session.Implement login and logout using sessions.
Protect at least one Snippets API route with session-based middleware.
1. Configure express-session
Install
express-sessionin your project if it is not already installed.In your main application file (e.g.
app.js), add the session middleware with:A
secretvalue (for local development you can keep it simple).Reasonable
resaveandsaveUninitializedsettings.
2. Implement login with sessions
Create a route (for example in routes/auth-session.js) that:
Reads
usernameandpasswordfrom the request body.Looks up the user and verifies the password using bcrypt (re-using your secure users table).
Sets
req.session.userIdwhen the login is successful.Returns a small success payload (e.g.
{ "message": "Logged in with session" }).
3. Protect routes with session middleware
Create a middleware function (for example requireSessionAuth) that:
Checks if
req.session.userIdis set.Calls
next()if it is.Sends a
401response with a short JSON error if it is not.
Use this middleware to protect at least one Snippets API route (for example, a route that creates or deletes a snippet).
4. Implement logout
Add a /logout-session route that:
Destroys the current session (e.g. via
req.session.destroy).Returns a simple JSON response to confirm logout.
5. Suggested exercises
Compare your session-based solution with your JWT-based solution:
What changes in the client’s behaviour?
How does each solution handle revocation?
What would you need to consider when scaling beyond a single server instance?
Last updated