9951 explained code solutions for 126 technologies


expressjsHow do I use Express.js and JWT to authenticate users?


To use Express.js and JWT to authenticate users, you will need to do the following steps:

  1. Install the jsonwebtoken and express-jwt packages:
$ npm install jsonwebtoken express-jwt
  1. Create a JWT secret key:
const jwtSecret = 'your_secret_key';
  1. Create a middleware to check the JWT:
const jwtCheck = expressJwt({
    secret: jwtSecret
});
  1. Use the middleware to protect routes:
app.get('/protected', jwtCheck, (req, res) => {
    res.send('Protected route');
});
  1. Generate a JWT token:
const token = jwt.sign({ userId: 123 }, jwtSecret);
  1. Pass the token to the client:
res.send({
    token: token
});
  1. On subsequent requests, the client should include the token in the Authorization header:
Authorization: Bearer <token>

Helpful links

Edit this code on GitHub