Node.js · Chapter 27 of 43

Authentication & JWT

Authentication verifies who a user is. A common stateless approach in APIs is JSON Web Tokens (JWT) — signed tokens that encode user information and can be verified without a database lookup.

After login, the server issues a JWT; the client sends it back on future requests (usually in an Authorization header) to prove identity.

Issuing a token

Use a library like `jsonwebtoken` to sign a payload (like a user ID) with a secret key, producing a token string.

Verifying a token

Middleware can verify the token on protected routes, rejecting requests with missing or invalid tokens.

Example 1 (javascript)
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secretKey', { expiresIn: '1h' });
console.log(token);
Output
eyJhbGciOiJIUzI1NiIs...

sign() creates a token containing the payload, expiring after 1 hour.

Example 2 (javascript)
function auth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    req.user = jwt.verify(token, 'secretKey');
    next();
  } catch {
    res.status(401).json({ error: 'Unauthorized' });
  }
}
Output
401 if token invalid, otherwise proceeds

Middleware verifies the token and attaches decoded data to req.user.

Key points

  • JWTs are signed tokens proving a user's identity.
  • jwt.sign() creates a token; jwt.verify() checks it.
  • Tokens are usually sent in the Authorization header.
  • JWT-based auth is stateless — no server-side session storage needed.
💡 Note: Never store sensitive data in a JWT payload — it's encoded, not encrypted, and can be read by anyone.

📝 Quick Quiz

1. What does JWT stand for?

2. Which method creates a signed token?

3. Where is a JWT usually sent on subsequent requests?