Skip to content

Instantly share code, notes, and snippets.

@RuliLG
Created March 11, 2026 09:59
Show Gist options
  • Select an option

  • Save RuliLG/d7707a516f84f00052667b2223c4239c to your computer and use it in GitHub Desktop.

Select an option

Save RuliLG/d7707a516f84f00052667b2223c4239c to your computer and use it in GitHub Desktop.
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET || "dev-secret";
export interface AuthRequest extends Request {
userId?: string;
}
export function requireAuth(req: AuthRequest, res: Response, next: NextFunction) {
const token = req.headers.authorization?.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "No token provided" });
}
try {
const decoded = jwt.verify(token, JWT_SECRET) as { userId: string };
req.userId = decoded.userId;
next();
} catch {
return res.status(401).json({ error: "Invalid token" });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment