QA
Intermediate LevelExpress JS

How do you implement secure JSON Web Token (JWT) authentication middleware in Express?

❓ Interview Prompt: Explain JWT structure (header, payload, signature), verifying tokens in Authorization headers, handling expiration, and attaching user payloads to req.

JSON Web Tokens (JWT) provide stateless authentication for RESTful APIs.

The Authentication Middleware Pattern:

1
Extract token from the HTTP 'Authorization' header (standard format: 'Bearer <token>').
2
Verify cryptographic signature and expiration ('exp') using 'jwt.verify()'.
3
If valid, attach the decoded user payload to the request object ('req.user = decoded') and call 'next()'.
4
If invalid or expired, return a '401 Unauthorized' or '403 Forbidden' JSON error immediately.

Code Implementation Example

javascript
import express from 'express';
import jwt from 'jsonwebtoken';

const app = express();
const JWT_SECRET = process.env.JWT_SECRET || 'secret-key';

export const authenticateJWT = (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Access denied. Bearer token missing.' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded; // Attach user payload to request
    next();
  } catch (error) {
    return res.status(403).json({ error: 'Invalid or expired token.' });
  }
};

app.get('/api/profile', authenticateJWT, (req, res) => {
  res.json({ user: req.user });
});
💡JWT authentication middleware verifying Bearer tokens and attaching decoded user payload.
🎯 Interview Key Takeaway

Verify JWT tokens from the Authorization header using jwt.verify() and attach the decoded user payload to req.user before calling next().

#JWT#Authentication#Security#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?