Next.js Middleware Explained In A Way Nobody Told You
Nitesh Babu
13 November 2025Understanding Next.js Middleware, can be painful sometimes, that’s why I’m here.
Here we will discuss, How? It Works and Why? It Matters.
If you have been building with Next.js for a while, you already know how powerful the framework is for creating fast, scalable, and modern web apps. But there is one feature that quietly unlocks a whole new level of control over requests and routing. Middleware.
Middleware sits between the incoming request and your application’s response. It runs before your routes render, allowing you to intercept, transform, or redirect traffic. Think of it as a tiny gatekeeper that decides what should happen with every incoming request.
If you want to see the official reference, the original docs do a great job explaining the basics.
What Exactly Is Next.js Middleware
Middleware is a special file named middleware.js or middleware.ts placed in the root of your project or inside specific route segments. It runs automatically when a request hits your app. Because it executes at the edge close to the user, it allows extremely fast checks and transformations.
It is perfect for tasks such as authentication, redirection, rewriting URLs, personalization, bot detection, or analytics.
Simple Example
Here is a quick example of a middleware that redirects unauthenticated users away from a protected route.
import { NextResponse } from 'next/server'
export function middleware(request) {
const isLoggedIn = request.cookies.get('auth')?.value === 'true'
if (!isLoggedIn && request.nextUrl.pathname.startsWith('/dashboard')) {
const loginUrl = new URL('/login', request.url)
return NextResponse.redirect(loginUrl)
}
return NextResponse.next()
}
Matching Routes with Config
You can specify which routes your middleware should apply to using a config matcher.
export const config = {
matcher: ['/dashboard', '/settings/:path*'],
}
More about matcher patterns here
What You Can Do With Middleware
Middleware unlocks a lot of practical use cases.
1. Personalization and A/B Testing
When deployed on Vercel, middleware can access geolocation and headers. You can show personalized content or run A/B tests by assigning random cookies. Since it runs at the edge, users get instant changes with no flicker.
2. Authentication and Access Control
You can check cookies, headers, tokens, or session states before a route loads. This prevents partially loaded pages and ensures instant redirection for restricted paths.
3. URL Rewrites and Cleaner Routing
Middleware lets you rewrite URLs before rendering. Developers often use this to support legacy routes or create cleaner dynamic slugs.
For example:
- Rewrite /u/123 to /profile/123
- Rewrite /product?id=88 to /product/88
More details on rewrites.
4. Bot Protection
You can inspect user agents or define custom logic to block suspicious or automated traffic.
5. Lightweight Analytics
Middleware can collect information like path, device type, or referrer early in the request cycle. Just keep it fast.
6. Middleware Runs on the Edge Runtime
Middleware uses the Edge Runtime, not Node.js. This means some Node features do not exist. No fs module, no complex Node libraries, no heavy crypto. Instead, you use Web Standard APIs such as
fetchRequestResponseURLReadableStream
These limitations ensure middleware stays lightweight and globally distributed for speed.
More about the runtime.
Middleware vs Route Handlers vs Server Actions
To avoid confusion, here is how they differ.
- Middleware executes before the request reaches your route.
- Route Handlers respond to API style requests inside the app router.
- Server Actions handle data mutations triggered from components.
Middleware is strictly for intercepting and shaping requests, not rendering UI or returning large data payloads.
Performance Considerations
Middleware is extremely fast, but only if you keep it simple. Avoid heavy imports, large dependencies, or slow network calls. Anything slow inside middleware slows down every matched request.
If you want to explore more examples, here is a helpful reference.
Middleware might look small at first glance, but it adds tremendous power to modern Next.js apps. Whether you are building SaaS dashboards, content platforms, or full scale products, mastering middleware gives you fine control over routing, access, and personalization.


