Building a Secure Next.js App with JWT Tokens

To use JWT token in Next.js, you can follow these steps:

  1. Install the jsonwebtoken package by running the following command in your project directory:
npm install jsonwebtoken
  1. Create a file called auth.js in your project directory. This file will contain the functions for generating and verifying JWT tokens.
import jwt from 'jsonwebtoken';

const secret = 'your_secret_key';

export function generateToken(payload) {
  return jwt.sign(payload, secret, { expiresIn: '1d' });
}

export function verifyToken(token) {
  try {
    return jwt.verify(token, secret);
  } catch (err) {
    return null;
  }
}

The generateToken function takes a payload (an object containing data you want to include in the token) and returns a JWT token signed with your secret key. The verifyToken function takes a JWT token and returns the decoded payload if the token is valid, or null otherwise.

  1. In your Next.js application, you can use these functions to generate and verify JWT tokens as needed. For example, you can generate a token when a user logs in and store it in a cookie or local storage. Then, you can verify the token on subsequent requests to ensure that the user is authenticated.
import { generateToken, verifyToken } from './auth';

// Login route
export default async function handler(req, res) {
  const { username, password } = req.body;

  // TODO: Authenticate the user and retrieve user data

  const token = generateToken({ username, isAdmin: true });

  res.cookie('token', token, { httpOnly: true });

  res.status(200).json({ message: 'Logged in successfully.' });
}

// Protected route
export default async function handler(req, res) {
  const { token } = req.cookies;

  const payload = verifyToken(token);

  if (!payload || !payload.isAdmin) {
    return res.status(401).json({ message: 'Unauthorized.' });
  }

  // TODO: Retrieve protected data and return response
}

In this example, the generateToken function is used to generate a token when a user logs in. The token is then stored in a cookie called token with the httpOnly flag set to true to prevent client-side access.

The verifyToken function is used in a protected route to ensure that the user is authenticated and has the necessary permissions to access the resource. If the token is invalid or does not contain the required data, the route returns a 401 Unauthorized response.

Note that you may need to configure your Next.js application to use cookies and enable CORS depending on your specific requirements.

Did you find this article valuable?

Support Mandeep Singh Blog by becoming a sponsor. Any amount is appreciated!