0
0
NextJSframework~5 mins

Request modification in NextJS

Choose your learning style9 modes available
Introduction

Sometimes you need to change a web request before sending it. This helps add extra info or fix details.

Adding authentication tokens to API calls
Changing request headers for special needs
Modifying request body data before sending
Redirecting requests to different URLs
Logging or debugging requests by changing them
Syntax
NextJS
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  // Modify request here
  const modifiedRequest = request.clone();
  // Example: add header
  modifiedRequest.headers.set('X-Custom-Header', 'value');
  return NextResponse.next();
}

Use middleware in Next.js to intercept and modify requests.

You can clone the request to safely change it without affecting the original.

Examples
This example changes the request path to '/new-path' before continuing.
NextJS
export function middleware(request) {
  const url = request.nextUrl.clone();
  url.pathname = '/new-path';
  return NextResponse.rewrite(url);
}
This adds a custom header to the response, showing how to modify headers.
NextJS
export function middleware(request) {
  const response = NextResponse.next();
  response.headers.set('X-Added-Header', 'hello');
  return response;
}
This redirects users to login if they have no authorization header.
NextJS
export function middleware(request) {
  if (!request.headers.get('authorization')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
Sample Program

This middleware checks if the request comes from a bot by looking at the user-agent header. If it finds 'bot', it redirects the request to a special '/bots' page. Otherwise, it lets the request continue as normal.

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

export function middleware(request) {
  // Check if user-agent contains 'bot'
  const userAgent = request.headers.get('user-agent') || '';
  if (userAgent.toLowerCase().includes('bot')) {
    // Redirect bots to a special page
    return NextResponse.redirect(new URL('/bots', request.url));
  }
  // Otherwise, continue normally
  return NextResponse.next();
}
OutputSuccess
Important Notes

Middleware runs before your page or API code, so it can change requests early.

Be careful not to create infinite redirects when modifying requests.

Use NextResponse.next() to continue without changes.

Summary

Request modification lets you change or redirect requests before they reach your app.

Use Next.js middleware to inspect and change headers, paths, or redirect users.

This helps with authentication, routing, and customizing user experience.