expressjsHow do I set up Express.js JWT authentication?
To set up Express.js JWT authentication, you need to install the jsonwebtoken package first, then create a secret key to sign the token, and then create a middleware to verify the token.
- Install the jsonwebtoken package:
npm install jsonwebtoken
- Create a secret key to sign the token:
const secret = 'supersecret';
- Create a middleware to verify the token:
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token) {
return res.status(403).send({
auth: false,
message: 'No token provided.'
});
}
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(500).send({
auth: false,
message: 'Failed to authenticate token.'
});
}
// If everything is good, save to request for use in other routes
req.userId = decoded.id;
next();
});
};
- Use the middleware in the routes that need authentication:
app.get('/protected', verifyToken, (req, res) => {
res.send('Access granted.');
});
For more details, please refer to this guide.
Code explanation
**
- Install the jsonwebtoken package:
npm install jsonwebtoken
This command installs the jsonwebtoken package to your project.
- Create a secret key to sign the token:
const secret = 'supersecret';
This code creates a secret key to sign the token.
- Create a middleware to verify the token:
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token) {
return res.status(403).send({
auth: false,
message: 'No token provided.'
});
}
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(500).send({
auth: false,
message: 'Failed to authenticate token.'
});
}
// If everything is good, save to request for use in other routes
req.userId = decoded.id;
next();
});
};
This code creates a middleware to verify the token. It first checks if the token exists in the request header, and then verifies the token with the secret key. If the token is verified, it will save the decoded token to the request for use in other routes.
- Use the middleware in the routes that need authentication:
app.get('/protected', verifyToken, (req, res) => {
res.send('Access granted.');
});
This code uses the middleware in the routes that need authentication. When the token is verified, it will send a response of "Access granted".
More of Expressjs
- How do I build an Express.js application?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js and Vite together for software development?
- How can I use express-zip js to zip and download files?
- How do I set the time zone in Express.js?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How do I use Express.js to patch a route?
- How do I use Zod with Express.js?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js to make an XHR request?
See more codes...