Introduction
Authentication is an important part of modern web applications. It helps verify the identity of users before allowing them to access protected resources. For example, an application may require users to log in before viewing their profile, updating account details, or accessing a dashboard.
JSON Web Token (JWT) is a commonly used approach for transferring authentication information between a client and a server. In Node.js applications, JWTs are often used with Express to authenticate API requests without maintaining traditional server-side session state.
In this tutorial, you will learn what JWT is, how it works, and how to implement JWT authentication in Node.js using Express.
What Is JWT?
JWT stands for JSON Web Token. It is a compact, URL-safe format for representing claims that can be transferred between two parties. A JWT is commonly used to carry information about an authenticated user.
A signed JWT usually consists of three parts separated by dots:
header.payload.signature
- Header: Contains information about the token type and signing algorithm.
- Payload: Contains claims, such as a user ID or token expiration time.
- Signature: Helps the server verify that the token has not been modified and was signed using the expected key.
A JWT payload is typically encoded, not encrypted. Do not store passwords, secret keys, or other sensitive information in it.
How JWT Authentication Works
A typical JWT authentication flow works as follows:
- The user submits login credentials to the server.
- The server verifies the credentials against the stored user record.
- If the credentials are valid, the server creates and signs a JWT.
- The client receives the token and sends it with requests to protected endpoints.
- The server verifies the token before returning protected data.
This approach can be useful for REST APIs, single-page applications, and mobile applications.
Prerequisites
Before implementing JWT authentication, make sure Node.js and npm are installed on your system. Basic knowledge of JavaScript and Express is also helpful.
Create a new project directory and initialize it:
mkdir jwt-node-app
cd jwt-node-app
npm init -y
Install the required packages:
npm install express jsonwebtoken dotenv
The packages serve the following purposes:
- express: Creates the web server and API routes.
- jsonwebtoken: Signs and verifies JWTs.
- dotenv: Loads environment variables from a .env file.
1. Create the Node.js Server
Create a file named server.js and add the following code:
const express = require('express');
require('dotenv').config();
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.send('JWT Authentication API');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This code creates a basic Express server and enables JSON request-body parsing. The root route provides a simple response to confirm that the server is running.
2. Configure the JWT Secret
JWTs must be signed using a secret or private key. For this introductory example, use a secret stored in an environment variable.
Create a .env file in your project directory:
PORT=3000
JWT_SECRET=replace_with_a_long_random_secret
Replace the example secret with a securely generated, high-entropy value before running the application.
Important: Do not commit .env to source control or expose the secret in frontend code. In production, use a secrets manager or your hosting platform’s secure environment-variable settings.
3. Generate a JWT After Login
For demonstration purposes, the following example uses a fixed user record. A real application must retrieve the user from a database and verify a securely hashed password, for example using Argon2 or bcrypt.
Add this route to server.js:
const jwt = require('jsonwebtoken');
const demoUser = {
id: 101,
username: 'rahul',
password: 'demo-password'
};
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (
username !== demoUser.username ||
password !== demoUser.password
) {
return res.status(401).json({
message: 'Invalid username or password'
});
}
if (!process.env.JWT_SECRET) {
return res.status(500).json({
message: 'Server configuration error'
});
}
const token = jwt.sign(
{ userId: demoUser.id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
});
The jwt.sign() method creates a signed token containing the user’s ID. The expiresIn: ‘1h’ option sets a one-hour expiration.
This route is only a learning example: it uses a hard-coded password and must not be used as a production login system.
4. Verify the JWT Using Middleware
After login, the client needs to send the token when accessing a protected endpoint. Express middleware can check the token before allowing the request to continue.
Add the following middleware to server.js:
function authenticateToken(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader &&
authHeader.startsWith('Bearer ')
? authHeader.slice(7)
: null;
if (!token) {
return res.status(401).json({
message: 'Authentication token required'
});
}
if (!process.env.JWT_SECRET) {
return res.status(500).json({
message: 'Server configuration error'
});
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({
message: 'Invalid or expired token'
});
}
req.user = user;
next();
});
}
This middleware reads the token from the Authorization header and expects the Bearer scheme. It uses jwt.verify() to validate the token’s signature and expiration before allowing the request to continue.
A missing token results in HTTP 401 Unauthorized, while an invalid or expired token results in HTTP 403 Forbidden in this example.
5. Create a Protected Route
Once the middleware is defined, you can protect routes by placing it before the route handler.
app.get('/profile', authenticateToken, (req, res) => {
res.json({
message: 'Profile accessed successfully',
userId: req.user.userId
});
});
When a valid token is supplied, the middleware attaches the verified token claims to req.user and calls next(). Otherwise, the request is rejected.
In a real application, use the verified user ID to retrieve the user’s current profile and permissions from your database. A valid token alone does not automatically grant permission to access every resource.
6. Test JWT Authentication
Start the server:
node server.js
Send a POST request to http://localhost:3000/login with this JSON body:
{
"username": "rahul",
"password": "demo-password"
}
The response contains a JWT:
{
"token": "your_generated_jwt"
}
Copy the returned token and send a GET request to http://localhost:3000/profile with this header:
Authorization: Bearer your_generated_jwt
If the token is valid, the server returns the profile response. If it is missing, invalid, or expired, the request is rejected.
JWT Authentication Best Practices
Keep these security practices in mind when implementing JWT authentication:
- Use strong secrets: Generate high-entropy secrets and store them outside your source code.
- Hash passwords: Never store or compare plaintext passwords in a real application.
- Set token expiration: Use a suitable expiry time and plan how users will obtain new tokens.
- Validate algorithms: Configure token verification to accept only the intended signing algorithm.
- Protect tokens in transit: Use HTTPS in production.
- Choose storage carefully: JavaScript-accessible browser storage can expose tokens to cross-site scripting (XSS). Secure, HttpOnly, Secure, appropriately configured cookies can reduce that exposure but require protection against cross-site request forgery (CSRF).
- Check authorization: Verify that authenticated users are allowed to access the specific resource or perform the requested action.
- Plan revocation: Signed tokens generally remain valid until expiration unless your application implements revocation or another server-side check.
Conclusion
JWT authentication is a useful way to protect APIs built with Node.js and Express. The jsonwebtoken package provides methods for creating and verifying tokens, while Express middleware can check authentication before protected routes are executed.
The example in this tutorial demonstrates the basic flow, from login to token verification and protected-route access. Before using this approach in production, add database-backed users, secure password hashing, robust input validation, rate limiting, carefully managed secrets, and an appropriate token-storage and revocation strategy.