What Is Express Authentication Middleware? Verify Identity Before Protected Routes
Authentication middleware validates a request's credentials and, on success, makes verified user information available to later handlers. This article uses a Bearer-token API in Express 5 to explain the middleware boundary, placement, and error handling; token cryptography is delegated to a trusted authentication library. Authorization decisions about roles or resources and login-session management are separate concerns.
Authentication middleware validates a request's credentials and, on success, makes verified user information available to later handlers. This article uses a Bearer-token API in Express 5 to explain the middleware boundary, placement, and error handling; token cryptography is delegated to a trusted authentication library. Authorization decisions about roles or resources and login-session management are separate concerns.
What does authentication middleware do in the request flow?
Express middleware can access the request (req), response (res), and next, which passes control to the next step. Authentication middleware reads credentials from a header and calls a verifier. If the credential is valid, it attaches minimal verified principal information to the request and calls next(). If credentials are missing or invalid, it must not continue to a protected handler. Failures in the verifier or its configuration should be distinguished from rejected credentials and passed to error handling. In Express 5, a rejected Promise or thrown error enters the next(error) flow. (Express: Writing middleware)
Ordinary middleware must either end the response or call next(); doing neither can leave a request hanging. Authentication middleware should call next() only on success and end the response or pass an error on failure. (Express: Using middleware)
How do you structure Bearer-token authentication?
The example shows the shape of Express 5 TypeScript middleware that receives an external verifier. It does not implement tokenVerifier.verify(). A real implementation should use a trusted JWT or opaque-token library configured for the expected issuer and API audience, with appropriate key management. Do not trust decoded token data without verifying its integrity, issuer, audience, and expiry. OWASP recommends verifying JWT integrity and validating iss, aud, and exp for API access tokens. (OWASP: REST Security Cheat Sheet)
import type { RequestHandler } from 'express';
export type Principal = {
subject: string;
};
export class InvalidCredentialError extends Error {}
export interface TokenVerifier {
verify(token: string): Promise<Principal>;
}
declare global {
namespace Express {
interface Request {
principal?: Principal;
}
}
}
export function requireAuthentication(
verifier: TokenVerifier,
): RequestHandler {
return async (req, res, next) => {
const match = /^Bearer\s+([^\s]+)$/i.exec(req.get('authorization') ?? '');
if (!match) {
res.set('WWW-Authenticate', 'Bearer');
res.sendStatus(401);
return;
}
try {
req.principal = await verifier.verify(match[1]);
next();
} catch (error) {
if (error instanceof InvalidCredentialError) {
res.set('WWW-Authenticate', 'Bearer error="invalid_token"');
res.sendStatus(401);
return;
}
next(error);
}
};
}This is an illustrative example; it was not compiled or run. InvalidCredentialError is an application contract used here when the verifier rejects a credential. If a key lookup or issuer-service outage is misclassified as this error, an operational problem will incorrectly become a 401; keep these error types distinct in the verifier. Principal contains only the user identifier needed downstream and does not store the raw token. The custom Express request property is typed with declaration merging. (Express: Writing middleware)
Where should you mount the middleware?
Attach authentication to a router or individual route so it runs before protected handlers. Deliberately separate public and protected routes instead of applying authentication indiscriminately to every endpoint. In this example, every method under /api/private passes through the middleware, while the public health endpoint does not.
import express from 'express';
import { requireAuthentication } from './require-authentication.js';
import { tokenVerifier } from './token-verifier.js';
const app = express();
const privateRouter = express.Router();
app.get('/health', (_req, res) => res.sendStatus(200));
privateRouter.use(requireAuthentication(tokenVerifier));
privateRouter.get('/profile', (req, res) => {
res.json({ subject: req.principal!.subject });
});
app.use('/api/private', privateRouter);This router setup is also illustrative and has not been run. A request to /api/private/profile passes through privateRouter.use() before reaching GET /profile. If authentication middleware is registered after a route handler that already ends the response, it will not protect that handler. Express runs middleware in registration order. (Express: Using middleware)
How are authentication and authorization different?
Authentication establishes which principal a request represents. Authorization decides whether that verified principal may perform an action on a resource. A valid token must not grant every action. Non-public APIs need access control at each endpoint, with permission checks matched to the action and resource. (OWASP: REST Security Cheat Sheet)
Missing or invalid credentials generally call for 401. Use 403 when authentication succeeded but the principal lacks permission for the resource. Follow the API's response contract and include the appropriate WWW-Authenticate challenge when required. (OWASP: REST Security Cheat Sheet)
Which security conditions are easy to miss in production?
Send credentials only over HTTPS. Do not put tokens in URL query strings, where they may be recorded in server logs. ([OWASP: REST Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html))
For JWTs, configure allowed signature algorithms and trusted keys on the server; do not let the token header select the verification algorithm. Validate issuer (`iss`), audience (`aud`), expiry (`exp`), and any additional claims required by the token profile. Decoding alone does not verify a token. ([OWASP: REST Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html))
Do not include tokens, signature details, or internal exception messages in authentication-failure responses. Send operational errors through suitable internal logging and error handling without logging credentials.
Keep middleware focused on identifying the principal; check authorization against each resource and action. Passing authentication is not passing authorization.
A token may remain valid until expiry after logout or account suspension. If early revocation is required, design a revocation strategy supported by the chosen session or token architecture; middleware alone does not solve it.
What should you check when authentication middleware behaves unexpectedly?
Separate public and protected routes and confirm the middleware is mounted on the protected router.
Confirm the request contains an `Authorization: Bearer <token>` header and that browsers, proxies, and gateways forward it. Do not move the token into the URL.
Distinguish a valid token, missing token, expired/tampered/wrong-audience token, and verifier-service outage. Check whether each maps to the API's expected 401, 403, or server-error response. These checks require an integration environment with the real verifier; they were not performed for this example.
Confirm that `req.principal` is available to later handlers and that per-user data is not left in shared state.
Confirm every branch calls `next()` or ends the response, and that unexpected failures reach Express error handling.