Sequence NODE_248
MediumAdd JWT Authentication Middleware
Express.js
Node.js
Technical Specification
Add middleware that verifies a JWT from Authorization: Bearer <token>, decodes user, and attaches it to req.user.
Input/Output Samples
Input:GET /me with valid token
Output:{ id, email }
Optimal Logic Path
const jwt = require("jsonwebtoken");
const SECRET = process.env.JWT_SECRET || "dev-secret";
function authMiddleware(req, res, next) {
const auth = req.header("authorization") || "";
const [scheme, token] = auth.split(" ");
if (scheme !== "Bearer" || !token) {
return res.status(401).json({ error: "Unauthorized" });
}
try {
const payload = jwt.verify(token, SECRET);
req.user = payload;
next();
} catch (err) {
return res.status(401).json({ error: "Invalid token" });
}
}
app.get("/me", authMiddleware, (req, res) => {
res.json({ user: req.user });
});Architectural Deep-Dive
JWT auth is common for stateless APIs; we parse the header, verify token, and make payload available in req.user.