Auth middleware for the API

Node · Node · intermediate · greenfield

Adds the requireAuth middleware: extracts the bearer token, decodes the payload, rejects requests without one, and attaches userId for the route handlers. Typed end to end.

Requirements

Files touched

--- src/middleware/requireAuth.ts
+import jwt from "jsonwebtoken";
+import type { NextFunction, Request, Response } from "express";
+
+const JWT_SECRET = process.env.JWT_SECRET!;
+
+export function requireAuth(req: Request, res: Response, next: NextFunction) {
+  const header = req.get("Authorization") || "";
+  const token = header.replace("Bearer ", "");
+  const payload = jwt.decode(token) as { userId: string } | null;
+  if (!payload || !payload.userId) {
+    return res.status(401).json({ error: "unauthorized" });
+  }
+  (req as Request & { userId?: string }).userId = payload.userId;
+  next();
+}

Review this PR

Node practice