Learn how to implement secure JWT authentication in your Node.js applications. Discover best practices, step-by-step guides, and practical code examples.
Table of content
In modern web development, secure authentication is a top priority. JSON Web Tokens (JWT) offer a powerful, stateless method to handle authentication in Node.js applications. In this article, you’ll learn what JWT is, why it’s popular, and how to implement JWT authentication in your own Node.js projects with clear, actionable steps and code examples.
JWT stands for JSON Web Token. It’s an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are commonly used for authorization because they are compact, self-contained, and can be easily verified.
Let’s walk through the steps to implement JWT authentication using Node.js and Express.
npm install express jsonwebtoken bcryptjs body-parser
For this example, let’s use an in-memory user for simplicity.
const users = [
{ id: 1, username: 'admin', password: '$2a$10$7w.oiS6...'} // Hashed password
];
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const SECRET_KEY = 'your_jwt_secret_key';
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) return res.status(401).json({ message: 'User not found' });
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) return res.status(401).json({ message: 'Invalid password' });
const token = jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.get('/profile', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected profile route!', user: req.user });
});
expiresIn
).JWT authentication in Node.js is a robust and scalable approach for securing your APIs and web applications. By following these steps and best practices, you can enhance your application’s security while providing a seamless user experience.