Next.js Middleware: Your App's Edge Bouncer
Think of Next.js Middleware as a bouncer at your app's door. It runs code on the edge before a request is processed, letting you redirect, rewrite, or block it. The main footgun is forgetting it runs in a limited Edge Runtime, not a full Node.js.
WHY IT EXISTS To centralize logic that applies to many routes without repeating code. Instead of checking for an auth token in every single protected page, you can check it once in a single middleware file that guards all those routes, keeping your page logic clean.
THE MENTAL MODEL Middleware is like a bouncer or a traffic cop standing in front of your entire Next.js application. It intercepts incoming requests before they reach a page or API route. Based on the request (its headers, cookies, URL), the middleware can decide to let it pass through, rewrite it to a different destination, redirect the user elsewhere, or block it completely.
HOW IT WORKS You create a middleware.ts file in the root of your project. This file exports a function that receives the request as a NextRequest object. Inside this function, you can read cookies, headers, and the URL. You then return a NextResponse to control the flow. For performance, you use a matcher config object to specify exactly which paths the middleware should run on, avoiding unnecessary execution on static assets. This code executes in the "Edge Runtime," a lightweight V8 isolate, not a full Node.js environment.
WHEN TO USE IT Use it for cross-cutting concerns that affect multiple routes. Three common cases are: first, authentication, where you check for a session cookie and redirect to a login page if it's missing; second, A/B testing, where you bucket users by setting a cookie or rewriting the URL to a different page variant; and third, internationalization, where you detect the user's preferred language from a header and redirect them to the correct locale path.
WHEN NOT TO USE IT Avoid middleware for heavy, long-running computations, as the Edge Runtime has strict execution time limits. It's also not the place for logic that's specific to a single page; put that logic in the page itself. Finally, because it lacks access to native Node.js APIs, you cannot use it for tasks that require file system access (fs) or other Node-specific dependencies.
ONE CANONICAL EXAMPLE A common use case is protecting a dashboard. The middleware is configured to run on all paths starting with /dashboard. It inspects the incoming request's cookies for an auth_token. If the token is missing or invalid, it returns a NextResponse.redirect() to send the user to the /login page. If the token is present, it allows the request to proceed to the dashboard page.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.