JWT Authentication (Node.js)
JWT (JSON Web Token) authentication issues a signed token at login that the client sends on each request (usually in an Authorization: Bearer header). The server verifies the signature instead of keeping session state.
Node.js
JWTs let a Node API authenticate requests without server-side sessions. After verifying credentials, you sign a token containing the user's id and an expiry with a secret (using the jsonwebtoken package). The client stores it and sends it on each request; middleware verifies it and attaches the decoded user to req.user.
A JWT has three parts — header, payload, signature — joined by dots. The signature, computed with your secret, is what makes it trustworthy: anyone can read the payload (it is only base64-encoded, not encrypted), but they cannot forge a valid token without the secret. So never put passwords or secrets in the payload.
Best practices: keep access tokens short-lived and use refresh tokens to renew them, store the signing secret in an environment variable, always send tokens over HTTPS, and verify on every protected route. Pair JWT auth with bcrypt for password hashing at login.
Syntax
jwt.sign(payload, secret); jwt.verify(token, secret)Examples
JavaScript
const jwt = require("jsonwebtoken");
const SECRET = process.env.JWT_SECRET;
// at login
const token = jwt.sign({ id: user.id }, SECRET, { expiresIn: "1h" });
// in auth middleware
function auth(req, res, next) {
const t = req.headers.authorization?.split(" ")[1];
try { req.user = jwt.verify(t, SECRET); next(); }
catch { res.status(401).json({ error: "invalid token" }); }
}