Authentication & Security
Node.js JWT Authentication
A JSON Web Token is a signed, base64-encoded string containing claims about a user. The server signs it at login and verifies the signature on later requests, so no session needs to be stored.
What is JWT Authentication in Node.js?
A JSON Web Token is a signed, base64-encoded string containing claims about a user. The server signs it at login and verifies the signature on later requests, so no session needs to be stored.
Why JWT Authentication matters
JWTs let an API stay stateless and scale horizontally without shared session storage — which is why they dominate mobile and single-page-application backends.
JWT Authentication example
import jwt from 'jsonwebtoken';
// login — sign
const token = jwt.sign(
{ sub: user._id.toString(), role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
);
res.cookie('token', token, {
httpOnly: true, // not readable by JavaScript — blocks XSS theft
secure: true, // HTTPS only
sameSite: 'strict', // mitigates CSRF
maxAge: 15 * 60 * 1000,
});
// middleware — verify
export function requireAuth(req, res, next) {
const token = req.cookies.token ?? req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Not authenticated' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
const expired = err.name === 'TokenExpiredError';
res.status(401).json({ error: expired ? 'Session expired' : 'Invalid token' });
}
}Key points to remember
- A JWT is signed, not encrypted — anyone can read the payload, so never put secrets in it.
- Keep access tokens short-lived and pair them with a revocable refresh token.
- httpOnly cookies are safer than localStorage, which any XSS can read.
- Use a long random secret from the environment, never a hardcoded string.
Common mistakes with JWT Authentication
- Storing personal data or roles you cannot revoke inside a long-lived token.
- A default secret such as "secret" left in production.
- Accepting the alg header from the token itself, enabling the alg=none attack — always pin the algorithm.
Node.js JWT Authentication— Interview Questions & FAQs
Is it safe to store a JWT in localStorage?+
It is convenient but vulnerable — any cross-site scripting flaw can read localStorage and steal the token. An httpOnly cookie with sameSite is safer because JavaScript cannot read it.
How do I log a user out with JWT?+
You cannot invalidate a signed token directly. Keep access tokens short-lived and store refresh tokens server-side so they can be deleted, or maintain a denylist of revoked token ids.
