To handle JWT token generation in a Next.js and Express.js setup, you can follow these steps:
Step 1: Install Required Packages
Install the `jsonwebtoken` package using npm:
bash
npm install jsonwebtoken
Step 2: Create an `auth.js` File
Create a new file called `auth.js` in your project directory. This file will contain the functions for generating and verifying JWT tokens.
javascript
import jwt from 'jsonwebtoken';
const secretKey = 'your_secret_key';
export function generateToken(payload) {
return jwt.sign(payload, secretKey, {
expiresIn: '1d',
});
}
export function verifyToken(token) {
try {
return jwt.verify(token, secretKey);
} catch (err) {
return null;
}
}
Step 3: Generate JWT Token
In your Next.js application, you can use the `generateToken` function to generate a JWT token when a user logs in. For example, you can generate a token when a user logs in and store it in a cookie or local storage.
javascript
import { generateToken } from '../auth';
// Login route
export default async function handler(req, res) {
const { username, password } = req.body;
// Authenticate the user and retrieve user data
const user = await authenticateUser(username, password);
if (user) {
const token = generateToken({ username, isAdmin: true });
res.cookie('token', token, { httpOnly: true });
res.status(200).json({ message: 'Logged in successfully.' });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
}
Step 4: Verify JWT Token
In your Express.js API, you can use the `verifyToken` function to verify the JWT token sent in the request headers. For example, you can protect a route by verifying the JWT token and ensuring it is valid.
javascript
import { verifyToken } from '../auth';
// Protected route
export default async function handler(req, res) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
const payload = verifyToken(token);
if (!payload || !payload.isAdmin) {
return res.status(401).json({ message: 'Unauthorized' });
}
// Retrieve protected data and return response
const userData = await getUserData(payload.username);
res.json(userData);
}
Step 5: Implement JWT Middleware
In your Express.js API, you can implement JWT middleware to validate JWT tokens sent to protected API routes. If a token is invalid, an error is thrown, which causes the global error handler to return a 401 Unauthorized response.
javascript
import jwt from 'jsonwebtoken';
import expressJwt from 'express-jwt';
const secretKey = 'your_secret_key';
export function jwtMiddleware(req, res) {
const middleware = expressJwt({ secret: secretKey, algorithms: ['HS256'] }).unless({
path: ['/api/public'],
});
return util.promisify(middleware)(req, res);
}
Step 6: Configure JWT Middleware
In your Express.js API, you can configure the JWT middleware to protect specific routes. For example, you can protect all routes starting with `/api/secure` by adding the middleware to the route handler.
javascript
import express from 'express';
import jwtMiddleware from '../middleware/jwt';
const app = express();
app.use('/api/secure', jwtMiddleware);
app.get('/api/secure/data', async (req, res) => {
// Retrieve protected data and return response
const userData = await getUserData(req.user.username);
res.json(userData);
});
By following these steps, you can effectively handle JWT token generation and verification in a Next.js and Express.js setup, ensuring secure and stateless authentication for your web application.
Citations:[1] https://mandeepsingh.hashnode.dev/building-a-secure-nextjs-app-with-jwt-tokens
[2] https://jasonwatmore.com/post/2021/08/04/next-js-11-jwt-authentication-tutorial-with-example-app
[3] https://clouddevs.com/next/jwt-and-token-based-authentication/
[4] https://github.com/definitelynotchirag/auth-nextjs
[5] https://benjamin-chavez.com/blog/integrating-next.js-with-express.js-using-auth0-for-authentication