In Express.js, middleware functions are used to perform tasks during the request-response cycle. Implementing a custom middleware for handling JSON Web Tokens (JWT) is a common use case for securing routes in your application. Below is a step-by-step guide on how to implement a custom JWT middleware in Express.js.
Install Dependencies:
First, make sure you have the required packages installed. Install jsonwebtoken
for creating and verifying JWTs.
bashnpm install express jsonwebtoken
Create a Middleware File:
Create a new file for your JWT middleware, e.g., jwtMiddleware.js
.
javascript// jwtMiddleware.js
const jwt = require('jsonwebtoken');
const secretKey = 'yourSecretKey'; // Replace with your secret key
const authenticateJWT = (req, res, next) => {
const token = req.header('Authorization');
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
jwt.verify(token, secretKey, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Forbidden' });
}
req.user = user;
next();
});
};
module.exports = authenticateJWT;
Replace 'yourSecretKey'
with a strong and secure secret key. This key should be kept confidential and not shared publicly.
Use the Middleware in Your Express App:
In your main Express application file (e.g., app.js
), import the middleware and use it for the routes you want to protect.
javascriptconst express = require('express');
const authenticateJWT = require('./jwtMiddleware');
const app = express();
// Your other middleware and route configurations go here
// Example protected route
app.get('/protected-route', authenticateJWT, (req, res) => {
res.json({ message: 'This route is protected.' });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this example, the /protected-route
endpoint is protected by the authenticateJWT
middleware. The middleware checks for a valid JWT in the Authorization
header and verifies it using the provided secret key.
Generating JWT in Your Authentication Endpoint:
When a user logs in or is authenticated, you need to generate a JWT and send it to the client. You can use the jsonwebtoken
library for this task.
javascriptconst express = require('express');
const jwt = require('jsonwebtoken');
const secretKey = 'yourSecretKey'; // Same secret key as in jwtMiddleware.js
const app = express();
// Your other middleware and route configurations go here
// Example authentication endpoint
app.post('/login', (req, res) => {
// Replace this with your actual user authentication logic
const user = {
id: 1,
username: 'exampleUser',
};
// Generate a JWT
const token = jwt.sign(user, secretKey, { expiresIn: '1h' });
// Send the token to the client
res.json({ token });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this example, the /login
endpoint generates a JWT after authenticating the user and sends it back to the client.
Remember to handle your secret keys and sensitive information securely, and consider using environment variables for configuration in a production environment.