TL;DR
This guide shows you how to create authentication middleware in Node.js using Express. This middleware checks if a user is logged in before allowing access to protected routes.
Prerequisites
- Node.js and npm installed
- An Express application set up (basic routing working)
- A basic understanding of HTTP requests and responses
Step 1: Install Required Packages
If you haven’t already, install the necessary packages. We’ll use jsonwebtoken for creating and verifying tokens.
npm install jsonwebtoken express
Step 2: Create a Secret Key
You need a secret key to sign your JSON Web Tokens (JWTs). Important: Keep this key secure! Don’t hardcode it directly into your code in production. Use environment variables instead.
const jwtSecret = 'your-super-secret-key'; // Replace with a strong, random string
Step 3: Implement the Authentication Middleware
This middleware function will verify the user’s token. It checks for a token in the Authorization header.
function authenticate(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('No token provided');
}
const token = authHeader.split(' ')[1]; // Bearer
jwt.verify(token, jwtSecret, (err, user) => {
if (err) {
return res.status(403).send('Invalid token');
}
req.user = user;
next(); // Pass control to the next middleware/route handler
});
}
Explanation:
authHeaderretrieves theAuthorizationheader from the request.- If no header is present, it returns a 401 (Unauthorized) error.
- The token is extracted from the header (assuming ‘Bearer
‘ format). jwt.verify()attempts to verify the token using your secret key.- If verification fails (e.g., invalid signature, expired token), it returns a 403 (Forbidden) error.
- If verification succeeds, the decoded user object is attached to the request object (
req.user). - Finally,
next()passes control to the next middleware function or route handler in the chain.
Step 4: Apply Middleware to Protected Routes
Now you can use your authentication middleware to protect specific routes.
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
// ... (your other route definitions)
app.get('/protected', authenticate, (req, res) => {
res.send(`Welcome to the protected route, ${req.user.username}!`);
});
Explanation:
- The
authenticatemiddleware function is placed before the route handler for/protected. - Before the route handler executes, Express will run the
authenticatemiddleware. - Only if the authentication succeeds (token is valid) will the route handler be called. Otherwise, a 401 or 403 error will be sent.
Step 5: Example Token Creation (for testing)
This shows how you might create a token after successful login.
app.post('/login', (req, res) => {
// ... (your authentication logic)
const user = { username: 'testuser' }; // Replace with actual user data
jwt.sign(user, jwtSecret, { expiresIn: '1h' }, (err, token) => {
if (err) {
return res.status(500).send('Token creation failed');
}
res.send({ token });
});
});
Explanation:
- This example assumes you have a
/loginroute that handles user authentication. - After successful login, it creates a JWT using
jwt.sign(). - The token is signed with your secret key and includes the user object as payload.
- The
expiresIn: '1h'option sets the token to expire after one hour.

