protect()
The protect() function returns Express middleware that blocks unauthenticated requests.
Signature
protect(
onUnauthenticated?: (res: express.Response) => void,
): (req: express.Request, res: express.Response, next: express.NextFunction) => Promise<void>
Import
const {protect} = require('@thunderid/express');
Prerequisites
- Mount
thunderID()before this middleware - Mount
cookie-parserbefore this middleware so the SDK can readreq.cookies
Usage
Default 401 response
index.js
const {protect} = require('@thunderid/express');
app.get('/protected', protect(), (_req, res) => {
res.send('Protected content');
});
Custom unauthenticated behavior
index.js
const {protect} = require('@thunderid/express');
app.get(
'/protected',
protect((res) => res.redirect('/login')),
(_req, res) => {
res.send('Protected content');
},
);
Runtime Behavior
For each request, the middleware:
- reads
req.thunderIDAuth - reads the session ID from
req.cookies[SESSION_COOKIE_NAME] - calls
client.isSignedIn(sessionId) - either continues to the next handler or rejects the request
Default Behavior
If no onUnauthenticated callback is provided, the middleware returns 401 with an empty response body.
Failure Behavior
- If the SDK client is missing or the session cookie is missing, the middleware rejects the request
- If the session ID is invalid, the middleware rejects the request
- In both cases, it uses your
onUnauthenticatedcallback when provided, or the default401response otherwise
Notes
protect()checks authentication state for the session cookie value, not for the presence of user data on the request- A common pattern is to redirect to
/loginfor browser routes and use the default401response for API routes