0
0
NextJSframework~5 mins

Middleware.ts file convention in NextJS

Choose your learning style9 modes available
Introduction

Middleware.ts helps you run code before a page or API responds. It controls requests easily.

To check if a user is logged in before showing a page
To redirect users based on their location or device
To add headers or cookies to requests
To block or allow access to certain pages
To log or track requests for analytics
Syntax
NextJS
import { NextRequest, NextResponse } from 'next/server';

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

export const config = {
  matcher: ['/path1/:path*', '/path2'],
};

The middleware function runs on every matching request.

The config.matcher controls which paths use this middleware.

Examples
This example redirects all requests to the login page.
NextJS
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/login', request.url));
}
This example rewrites requests from mobile devices to a mobile page.
NextJS
export function middleware(request: NextRequest) {
  const userAgent = request.headers.get('user-agent') || '';
  if (userAgent.includes('Mobile')) {
    return NextResponse.rewrite(new URL('/mobile', request.url));
  }
  return NextResponse.next();
}
This config runs middleware only on dashboard and settings pages.
NextJS
export const config = {
  matcher: ['/dashboard/:path*', '/settings'],
};
Sample Program

This middleware checks if a user has a 'token' cookie. If not, it redirects to the login page. It only runs on URLs starting with '/protected'.

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

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

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

Middleware runs before the page or API code.

Use NextResponse.next() to continue the request normally.

Be careful with redirects to avoid loops.

Summary

Middleware.ts runs code before pages or APIs respond.

Use it to check, redirect, or modify requests.

Configure paths with config.matcher.