
August 26, 2025
How to Implement JWT Authentication in a Node.js App
How to Implement JWT Authentication in a Node.js App
A key part of almost all modern web applications is authentication. Hackers could get access to private user data without a strong security system. At the moment, JWT (JSON Web Token) security is one of the most popular ways for authentication. It manages user sessions reliably and flexiblely. This article explains how to utilise Express for Node.js JWT authentication.
What is JWT and How Does It Work?
A JSON Web Token, a URL-based string, lets two parties exchange claims. Most of the time, it has three parts:
- Header: This part tells the hashing method and the type of token.
- Payload: This part has user info or unique claims in it.
- Signature: This makes sure that the token has not been changed.
A typical JWT looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOjEsIm5hbWUiOiJKb2huIERvZSJ9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The server makes a JWT and sends it to the client when a user logs in. The client keeps the token somewhere safe, like in memory or secure cookies, and sends it with every request to get to protected routes. The computer then uses a hidden key to check the token.
Setting Up Your Node.js App
Start by making a new Node.js project and installing the tools you need:
mkdir jwt-auth-app
cd jwt-auth-app
npm init -y
npm install express jsonwebtoken bcryptjs body-parser
Set up a basic project structure:
jwt-auth-app/
âââ index.js
âââ users.js
âââ middleware/
âââ auth.js
Creating a Simple User Login System
We will use a static array to simulate a user database for this example:
// users.js
const users = [
{
id: 1,
username: 'john',
password: '$2a$10$abcdef...' // hashed password
}
];
module.exports = users;
In your index.js, set up Express and the login route:
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const users = require('./users');
const app = express();
app.use(bodyParser.json());
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: 'Invalid credentials' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ id: user.id }, 'your_jwt_secret', { expiresIn: '1h' });
res.json({ token });
});
This code checks the user's credentials, matches the hashed password, and gives back a JWT if it works.
Creating Middleware to Protect Routes
As users may log in and get passwords, you will need middleware to secure certain routes.
// middleware/auth.js
const jwt = require('jsonwebtoken');
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, 'your_jwt_secret', (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
module.exports = authenticateToken;
To keep routes in index.js safe, use this middleware:
const authenticateToken = require('./middleware/auth');
app.get('/dashboard', authenticateToken, (req, res) => {
res.json({ message: `Welcome user ${req.user.id} to your dashboard.` });
});
The /dashboard route is only accessible to valid token holders.
Best Practices for JWT Authentication
JWT is a strong tool, but it needs to be used properly to keep things secure:
- To avoid token interception, always use HTTPS.
- Use environment variables instead of code to store secrets.
- Limit the use of tokens by setting expiry dates.
- If you are using a private app, do not store tokens in localStorage. HttpOnly cookies are better.
- Revoke tokens when you need to (for example, when you log out or change your password).
Conclusion
A simple, unbiased way to protect your APIs is to use JWT authentication in a Node.js app. You now know how to use middleware to protect routes, set up a login system, and make JWTs. Even though this example utilises a static user list, connecting to MongoDB or PostgreSQL is the same. JWT lets you create secure, flexible, and authorisation-friendly services.
You must understand JWT to understand modern web development, whether you are developing APIs or single-page applications.
65 views