Securing API Routes in Next.js

Next.js allows us to create API routes that can handle server-side logic. We need to protect these routes by ensuring that only authenticated users can access them.

Step 1: Protecting API Routes

We can create a middleware function to check for authentication before allowing access to certain routes:

// middleware/auth.js

import { verify } from ‘jsonwebtoken’;

export const isAuthenticated = (handler) => async (req, res) => {

 const { token } = req.cookies;

 if (!token) {

  return res.status(401).json({ message: ‘Not authenticated’ });

 }

 try {

  const user = verify(token, process.env.JWT_SECRET);

  req.user = user;

  return handler(req, res);

 } catch (error) {

  return res.status(401).json({ message: ‘Invalid token’ });

 }

};

Step 2: Applying the Middleware

Use this middleware in your API routes to secure them:

// pages/api/protected-route.js

import { isAuthenticated } from ‘../../middleware/auth’;

const protectedRoute = async (req, res) => {

 // Your protected logic here

 res.status(200).json({ message: ‘This is a protected route’, user: req.user });

};

export default isAuthenticated(protectedRoute);

Step 3: Handling Tokens and Sessions

Depending on your authentication strategy, ensure tokens or session cookies are securely handled:

  • Use HttpOnly and Secure flags on cookies.
  • Set appropriate expiration times for tokens.
  • Refresh tokens if necessary to maintain user sessions securely.

Leave a comment

Your email address will not be published. Required fields are marked *