Middleware in Next.js

📘 Next.js 👁 36 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Middleware in Next.js allows you to run code before a request is completed. It is mainly used for authentication, authorization, redirects, rewrites, and request handling at the edge.


1. What is Middleware?

Middleware runs before routing happens.
It executes on the Edge Runtime, which makes it fast and lightweight.

Common uses:

  • Authentication checks

  • Route protection

  • Redirects and rewrites

  • Localization (i18n)

  • Logging and headers


2. Creating Middleware

Middleware is defined in a file named middleware.js or middleware.ts at the root of the project.

Basic Example

import { NextResponse } from 'next/server'; export function middleware(request) { return NextResponse.next(); }

3. Protecting Routes (Authentication Example)

import { NextResponse } from 'next/server'; export function middleware(request) { const isLoggedIn = false; if (!isLoggedIn) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }

4. Matching Specific Routes

You can control where middleware runs using matchers.

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

This middleware will apply only to:

/dashboard /dashboard/settings /dashboard/profile

5. Reading Cookies and Headers

Cookies

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

Headers

export function middleware(request) { const userAgent = request.headers.get('user-agent'); return NextResponse.next(); }

6. Rewriting URLs

import { NextResponse } from 'next/server'; export function middleware(request) { return NextResponse.rewrite(new URL('/new-path', request.url)); }

7. Redirect vs Rewrite

FeatureRedirectRewrite
URL changeYesNo
Browser awareYesNo
Use caseAuth, SEOInternal routing

8. Middleware Limitations

  • Runs on Edge Runtime

  • No access to Node.js APIs

  • Cannot access databases directly

  • Must be fast and lightweight


Use Cases

  • Authentication & authorization

  • Role-based access

  • Geo-based routing

  • Maintenance mode

  • A/B testing


Conclusion

Middleware in Next.js is a powerful feature for controlling requests before they reach your routes. It helps improve security, performance, and user experience when used correctly.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes