Next.js - API MiddleWares



In this chapter, we will learn about API Middlewares in Next.js, how to create a middleware function, and use it to handle API requests.

Middleware in API Routes

Middleware in API routes are reuseable functions executed before the main request handler logic. These functions are commonly used for tasks like authentication, logging, rate limiting, input validation, or other pre-processing tasks. Middleware will help you centralize common logic and ensure consistency across multiple API routes.

Key Features of Middleware in API Routes

  • Pre-Processing Request: Middleware functions allow you to inspect, modify, or validate the incoming request before passing it to the main handler.
  • Centralized Logic: Middleware helps to reduce code duplication by defining middleware logic once and reuse it across multiple API routes.
  • Early Termination: Middleware can terminate a request early (e.g., if authentication fails) to prevent further processing.

Create a Authentication Middleware

Let's create a simple authentication middleware that checks if the request contains a valid API key. Create a file named 'authMiddleware.js' inside the 'middlewares' directory with the following code:

// File: middlewares/authMiddleware.js

export default function authMiddleware(handler) {
    return (req, res) => {
      const headerApiKey = req.headers.apikey;
      const queryApiKey = req.query.apiKey;

      // Check if API key is present in header or query
      if ( (!headerApiKey && !queryApiKey) || 
             (headerApiKey !== process.env.API_KEY && 
             queryApiKey !== process.env.API_KEY) ) {
        return res.status(401).json({ message: 'Unauthorized' });
      }
      return handler(req, res);
    };
}

Usage

Now, let's use the authentication middleware in an API route. Create a file named 'hello.js' inside the 'pages/api' directory with the following code:

// File: pages/api/hello.js

import authMiddleware from '../../middlewares/authMiddleware';

export default authMiddleware(function handler(req, res) {
    res.status(200).json({ message: 'Hello, Next.js API!' });
});

Output

We have added an API key "djcjcwj-wcdkjcnw" to '.env.local' file in root folder. Now, if we visit the URL '/api/hello', an unauthorized response will be returned. But when we visited '/api/hello?apiKey=djcjcwj-wcdkjcnw', the API key is validated and the proper response is returned.

Next.js API Middleware
Advertisements