0
0
NextJSframework~5 mins

Middleware for API routes in NextJS

Choose your learning style9 modes available
Introduction

Middleware lets you run code before your API route handles a request. It helps you check or change requests easily.

Check if a user is logged in before giving access to data.
Log details about each API request for debugging.
Add security headers to API responses.
Limit how many times a user can call an API in a short time.
Modify request data before it reaches the main API handler.
Syntax
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Your code here
  return NextResponse.next();
}

export const config = {
  matcher: '/api/:path*',
};

The middleware function runs before your API route.

Use NextResponse.next() to continue to the API handler.

Examples
This logs every API call URL before continuing.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  console.log('API called:', request.url);
  return NextResponse.next();
}
This checks for an authorization token and blocks requests without it.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.headers.get('authorization');
  if (!token) {
    return new NextResponse('Unauthorized', { status: 401 });
  }
  return NextResponse.next();
}
Sample Program

This middleware blocks requests from user agents that include the word 'bot'. Others continue to the API route.

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const userAgent = request.headers.get('user-agent') || '';
  if (userAgent.toLowerCase().includes('bot')) {
    return new NextResponse('Bots are not allowed', { status: 403 });
  }
  return NextResponse.next();
}

export const config = {
  matcher: '/api/:path*',
};
OutputSuccess
Important Notes

Middleware runs on the edge, so keep it fast and simple.

Use matcher to limit middleware to API routes only.

You can modify requests or responses inside middleware before they reach your API.

Summary

Middleware runs code before your API route handles a request.

Use it to check, block, or modify requests easily.

Remember to use NextResponse.next() to continue to the API handler.