0
0
NextJSframework~5 mins

Why middleware intercepts requests in NextJS

Choose your learning style9 modes available
Introduction

Middleware intercepts requests to check or change them before they reach your app. It helps control who can see what and how your app responds.

To check if a user is logged in before showing a page
To redirect users to a different page based on their location
To add security headers to every request
To log or track requests for analytics
To rewrite URLs for cleaner links
Syntax
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Your code here
  return NextResponse.next();
}
Middleware is a special function that runs before your page or API code.
You must return a response, like NextResponse.next() to continue or NextResponse.redirect() to change the path.
Examples
This middleware lets every request pass through without changes.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Let all requests continue
  return NextResponse.next();
}
This middleware checks if a user cookie exists. If not, it sends the user to the login page.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  if (!request.cookies.get('user')) {
    // Redirect if no user cookie
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
Sample Program

This middleware checks if the user has a 'loggedIn' cookie. If missing, it redirects them to '/login'. Otherwise, it lets the request continue.

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (!request.cookies.get('loggedIn')) {
    url.pathname = '/login';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
OutputSuccess
Important Notes

Middleware runs on the server before your page or API code.

Use middleware to protect pages or add common logic for many routes.

Summary

Middleware lets you check or change requests before your app handles them.

It is useful for security, redirects, and modifying requests.

Always return a NextResponse to control the flow.