Typed Express Middleware With Request State
Extend Express request types through declaration merging so middleware can attach authenticated user data that later handlers read with full type safety.
Code
import express, { type NextFunction, type Request, type Response } from "express";
export interface AuthUser {
id: string;
roles: string[];
}
declare module "express-serve-static-core" {
interface Request {
user?: AuthUser;
}
}
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
const token = req.header("authorization")?.replace(/^Bearer /, "");
if (!token) {
res.status(401).json({ error: "missing token" });
return;
}
try {
req.user = verifyToken(token);
next();
} catch (error) {
res.status(401).json({ error: (error as Error).message });
}
}
function verifyToken(token: string): AuthUser {
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
return { id: payload.sub, roles: payload.roles ?? [] };
}
const app = express();
app.use(requireAuth);
How the snippet works
Typed Express Middleware With Request State keeps everything in the functions requireAuth and verifyToken.
The result comes back as an object carrying sub.
Points of care
- Plan for an install step:
expressis a real dependency, resolved by the package manager.
Applying it
Signature: export function requireAuth(req: Request, res: Response, next: NextFunction)
The surface worth importing is requireAuth; the helpers around it are private to the snippet.
The call returns sub.
Statements that matter
return { id: payload.sub, roles: payload.roles ?? [] };
const token = req.header("authorization")?.replace(/^Bearer /, "");
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
FAQ
- Does `requireAuth` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Which packages must be installed first?
- Yes. The imports resolve to `express`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.