Sessions, JWTs, and Token Authentication
🎯 Introduction
By the end of this article, you will be able to create and verify session credentials and JWTs and assess their tradeoffs.
🎫 A token is a credential; JWT is a format
A token is any value a client uses to demonstrate an identity or entitlement. A random session ID is a token, and a JWT can also serve as a token. These are not three mutually exclusive choices.
Session-based authentication typically stores a random value on the client and looks up a server-side login record with it. JWTs typically carry signed claims: the server verifies the signature and constraints before using the user identifier. A signature verifies that an untrusted party has not altered the content; it does not encrypt it.
🗃 Store login state with express-session
Express applications can use express-session to manage sessions. It reads the session cookie, finds the server-side record, and exposes the current session through req.session.
Install the dependency for this section:
npm install express-session@1.19.0
Create session-app.mjs and prepare the app and session secret:
import express from 'express';
import session from 'express-session';
export const app = express();
const secret = process.env.SESSION_SECRET;
if (!secret || Buffer.byteLength(secret) < 32) throw new Error('Configure a session secret');
SESSION_SECRET should be a randomly generated server-side secret that protects the session cookie's signature. Generate it once with the built-in crypto module, save the output as SESSION_SECRET in your local .env, and exclude it from the repository:
import { randomBytes } from 'node:crypto';
console.log(randomBytes(32).toString('hex'));
Running node session-secret.mjs produces a random string. Multiple service instances must share the same secret. Do not regenerate it for every request.
🍪 Configure session middleware before routes
Add this to session-app.mjs:
app.use(session({
name: 'sid',
secret,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', secure: false, maxAge: 30 * 60_000 }
}));
name specifies the cookie name. resave: false avoids saving unchanged sessions again; saveUninitialized: false avoids creating records for visitors who have not used a session. The cookie lasts 30 minutes. HttpOnly restricts page script access, and SameSite restricts cross-site transmission.
secure: false is only for local HTTP practice. Set it to true for production HTTPS. Behind a reverse proxy, also configure Express's trusted proxy settings for the actual deployment.
The default store is for local development only; restarting loses its records. In production, configure a shared store so multiple processes read the same login state and the store removes expired sessions.
✅ Save the user ID after password verification
After verifying the username and password, regenerate the session ID before storing the trusted user ID. This prevents the pre-login session from being reused for the authenticated identity.
This function handles successful login. res.locals.user is a user record, such as { id: 1 }, that an earlier password verification step retrieved and verified. Never assign the request body directly to it:
export function loginSuccess(req, res, next) {
req.session.regenerate(error => {
if (error) return next(error);
req.session.userId = res.locals.user.id;
req.session.save(error => {
if (error) return next(error);
res.json({ data: { loggedIn: true } });
});
});
}
Run this handler after password verification in the login route. regenerate replaces the session; save confirms persistence before returning success. Errors go to error middleware. The browser stores sid after receiving Set-Cookie and automatically includes it in subsequent eligible requests.
🔎 Read the authenticated identity in an endpoint
Add /me after the session middleware:
app.get('/me', (req, res) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Sign in first' });
}
res.json({ data: { userId: req.session.userId } });
});
Without a valid login record, the endpoint returns 401. After login as user 1, a request from the same browser returns {"data":{"userId":1}}. The ID comes from the server-side session rather than the client's own claim.
🚪 Delete the server-side session on logout
Continue by adding a logout endpoint:
app.post('/logout', (req, res, next) => {
req.session.destroy(error => {
if (error) return next(error);
res.clearCookie('sid', { path: '/' });
res.status(204).end();
});
});
destroy deletes the session record; clearCookie tells the browser to delete its cookie. Success returns 204, and the next /me request returns 401. State-changing cookie-authenticated endpoints also need CSRF protection before modifying data; see the security section.
✍️ Issue JWTs with a library
Install the JWT library in the example directory:
npm install jose@6.2.13
Create tokens.mjs and prepare a signing key:
import { SignJWT, jwtVerify } from 'jose';
import { randomBytes } from 'node:crypto';
const key = randomBytes(32);
This demonstration key changes on restart. Production services should read stable keys from secure configuration and plan key rotation. Never put the key in frontend code or the source repository.
Add the issuing function:
export function issueAccess(userId) {
return new SignJWT({})
.setProtectedHeader({ alg: 'HS256' })
.setSubject(String(userId))
.setIssuer('backend-demo')
.setAudience('web-demo')
.setExpirationTime('15m')
.sign(key);
}
sub identifies the user, iss constrains the issuer, aud constrains the audience, and exp sets expiration. This example uses HS256: parties holding the same secret can sign and verify tokens. Anyone who obtains the secret can forge them.
JWT contents are readable. Do not include secrets such as passwords or identity documents.
✅ Verify claims before using them
Add this in the same file:
export async function verifyAccess(token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'], issuer: 'backend-demo', audience: 'web-demo'
});
if (typeof payload.sub !== 'string') throw new Error('Missing user identifier');
return payload.sub;
}
Verification fails if the signature, algorithm, issuer, audience, or expiration does not meet the constraints. Decoding the payload only reads its content; it does not establish trust.
Create token-demo.mjs:
import { issueAccess, verifyAccess } from './tokens.mjs';
const token = await issueAccess(1);
console.log(await verifyAccess(token));
Running it produces the string 1. After receiving a Bearer credential, an endpoint calls verifyAccess. Convert verification failures to 401 and check permissions after success.
⚖️ Choose based on revocation and deployment needs
Sessions can be revoked immediately by deleting records, but require server-side state lookup on each request. JWTs expose claims after signature verification, but logout does not automatically invalidate issued JWTs. Immediate revocation still requires server-side state checks, or you can use a shorter lifetime.
Roles stored in JWTs can become stale. Sensitive permissions should account for current user state. A valid signature does not make old permissions trustworthy forever.
❓ Questions and Answers
Q1: Are JWTs always more secure than sessions?
No. Both depend on protecting secrets or credentials, expiration, revocation, and request authorization. The format alone does not guarantee overall security.
Q2: Can tokens go in URLs?
Do not transmit login credentials this way: URLs easily enter history and logs. Use an appropriate authentication header or protected cookie.
Q3: Is verifying the signature enough?
No. Also check expiration, issuer, audience, allowed algorithms, and required claims, then perform actual authorization.
🧪 Practice
Integrate session persistence and logout into the login flow and confirm that /me returns 401 after logout. Change the JWT verifier's audience and confirm that the same token fails verification.
// Write your code or record your verification results here
