πŸš€ Learn Middleware in Next.js

πŸ“˜ What is Middleware?

Middleware is used to process requests between the client and the server before they reach the final destination.

Middleware runs between a user’s request and the final response.

Middleware is a powerful tool in Next.js used to run logic between a request and the response. It's ideal for:

  • πŸ” Authentication checks
  • 🚦 Redirects
  • πŸ“Š Logging or analytics
  • 🌍 Locale detection

πŸ›  How to Create Middleware

  • Create a file named middleware.js at the root level of your project.
  • The file must export a function called middleware.
  • Inside this file, define the function:
  • This function receives a request object and can optionally return a Response.
export function middleware(request) {
  console.log('Middleware triggered');
  return NextResponse.next(); // Allow request to continue
}

πŸ” Example Use Case: Authentication

Middleware can check if a user is logged in using cookies or headers. If not logged in, redirect to `/login` or `/` page.

import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken');

  if (!token) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  return NextResponse.next();
}

βœ… req.nextUrl.pathname != "/" condition is important to avoid **infinite redirects**.

import { NextResponse } from "next/server";

// Simulated user login status (replace with real logic later)
let login = true;

export function middleware(req) {
  if (!login && req.nextUrl.pathname !== "/") {
    return NextResponse.redirect(new URL('/', req.url));
  }
  return NextResponse.next();
}

// ⚠️ Without this pathname check (req.nextUrl.pathname !== "/"), it will keep redirecting to '/' infinitely

πŸ“ Target Middleware to Specific Routes

You can apply middleware only to a specific route like a payment or dashboard page.

import { NextResponse } from "next/server";

export function middleware(req) {
  return NextResponse.redirect(new URL('/', req.url));
}

export const config = {
  matcher: ["/pay/:path*"], 
  // βœ… Apply middleware to pay route /:path* all subroutes
  // βœ… Only run on /pay or subroutes like /pay/confirm
};

πŸ“š Learn More: