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:
- Install the jsonwebtoken and express-jwt packages:
$ npm install jsonwebtoken express-jwt
- Create a JWT secret key:
const jwtSecret = 'your_secret_key';
- Create a middleware to check the JWT:
const jwtCheck = expressJwt({
secret: jwtSecret
});
- Use the middleware to protect routes:
app.get('/protected', jwtCheck, (req, res) => {
res.send('Protected route');
});
- Generate a JWT token:
const token = jwt.sign({ userId: 123 }, jwtSecret);
- Pass the token to the client:
res.send({
token: token
});
- On subsequent requests, the client should include the token in the Authorization header:
Authorization: Bearer <token>
Helpful links
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I implement CSRF protection in an Express.js application?
- How do I manage user roles in Express.js?
- How can I use express-zip js to zip and download files?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I create and use models in Express.js?
- How can I use Express.js with TypeScript?
- How do I download a zip file using Express.js?
- How can I use Express.js to generate a zip response?
- How do I use Zod with Express.js?
See more codes...