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.

TypescriptAuth Jwt

Code

typescriptsnippet
35 lines
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: express is 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

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.