jwt auth middelware in javascript

Here's an example of how to create a JWT authentication middleware in Javascript using the jsonwebtoken library:

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

function authMiddleware(req, res, next) {
  try {
    const token = req.headers.authorization.split(' ')[1]; // Extract the JWT token from the Authorization header
    const decodedToken = jwt.verify(token, process.env.JWT_SECRET_KEY); // Verify the JWT token
    req.userData = { userId: decodedToken.userId };
    next();
  } catch (error) {
    res.status(401).json({ message: 'Unauthorized' });
  }
}
443 chars
13 lines

In this example, the middleware function authMiddleware extracts the JWT token from the Authorization header and verifies it using the secret key stored in the environment variable JWT_SECRET_KEY. If the verification is successful, the req.userData object is set with the decoded token's userId property and the middleware calls the next() function to pass control to the next middleware or route handler. If the verification fails, the middleware sends a 401 (Unauthorized) error response to the client.

To use this middleware in a route handler, simply add it as a parameter before the route handler function:

index.tsx
app.get('/protected', authMiddleware, (req, res) => {
  res.json({ message: 'Protected resource' });
});
105 chars
4 lines

In this example, the authMiddleware function is invoked before the route handler function for the /protected route.

gistlibby LogSnag