express jwt middleware in javascript

Here's how to write a JWT middleware function in ExpressJS using the jsonwebtoken library:

index.tsx
const jwt = require('jsonwebtoken');

function authMiddleware(req, res, next) {
  // Get the token from the header
  const token = req.header('Authorization');
  if (!token) {
    return res.status(401).json({ msg: 'Authorization denied' });
  }

  try {
    // Verify the token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Invalid token' });
  }
};

module.exports = authMiddleware;
494 chars
21 lines

This middleware checks if a JWT is present in the Authorization header. If it is, the token is verified using the secret key stored in the environment variable JWT_SECRET. If the token is valid, the decoded user information is attached to the request object and the request is passed on to the next middleware. If the token is invalid, a 401 unauthorized error is returned.

gistlibby LogSnag