Skip to content
codmaker

Next.js Middleware: Auth, Redirects and A/B Tests

How Next.js middleware works, when to use it for auth, redirects, geolocation and A/B testing, and the mistakes that make it slow or insecure. With examples.

CodmakerUpdated 10 min read
Share

What is Next.js middleware?

Middleware is code that runs before a request reaches your routes. It sits between the user and your React application. It can read the incoming request, then let it through, redirect it, rewrite it to a different route, or change headers and cookies on the way in and out.

That makes it the right place for routing decisions based on cookies or headers: is this user signed in, which language should they see, which experiment bucket are they in. All of that gets decided before a single layout or page renders.

A quick note on naming, since this changes between versions. In the classic setup you create a middleware.ts file in the project root, or inside src if you use one. Recent Next.js versions have renamed this file convention to proxy, with the same job and a very similar API. If you're on a newer version, check the docs for your release and use whichever name it expects. The patterns in this guide apply to both.

How middleware works: the request lifecycle

The file exports a single function that receives a NextRequest. You return a NextResponse. Calling NextResponse.next() lets the request continue. NextResponse.redirect(url) sends the browser to a new URL. NextResponse.rewrite(url) serves a different route while the address bar keeps the original URL.

You control where it runs with a matcher in the exported config object. Keep this tight. Without a matcher, middleware runs on every request, including static assets and images, and that's wasted work on every hit.

Middleware has traditionally run on the Edge runtime. It runs close to the user, and in my experience cold starts were under 10ms, which is why it works as a gate in front of every page. The trade-off is that the Edge runtime only supports a subset of Node.js APIs. Recent Next.js versions also let middleware run on the Node.js runtime, and in some versions that's the default. Check which runtime your version uses before you import a database driver or a Node-only library into it.

How to handle authentication in Next.js middleware

The basic pattern: read the session cookie, and if it's missing on a protected path, redirect to the login page with the original path in a query param so you can send the user back after sign-in.

Don't just check for a token. Refresh it. If an access token is expired, middleware can run the refresh rotation with your auth provider and set the new cookie on the response, all without the client knowing. This removes the flicker of client-side auth checks, where a page renders a logged-out state for a split second before JavaScript figures out who you are.

Here's the part a lot of tutorials skip: middleware should not be your only auth check. Treat it as a fast first filter for redirects and UX. Then verify the session again where the data actually lives, in your Server Components, route handlers and Server Actions. In 2025 Next.js patched a vulnerability where a crafted request header could skip middleware entirely on some self-hosted setups. Apps that also checked auth in the data layer were fine. Apps that trusted middleware alone were exposed. Keep Next.js updated, and keep auth checks close to your data.

A/B testing with middleware rewrites

Instead of conditional logic in your components, use middleware to rewrite the URL. Assign each visitor a bucket and store it in a cookie, for example X-Experiment-Bucket. Then rewrite /pricing to /pricing-b for 50% of traffic.

The user sees the same URL, but gets a completely different page file. Each variant is a normal route you can build, test and delete on its own. Your components stay free of if-experiment branches, and the losing variant is one folder to remove when the test ends.

Two details make this work well. Set the cookie on the first response so the same visitor stays in the same bucket on every visit. And make sure your analytics records the bucket, otherwise you'll have two pages and no way to tell which one won.

Geolocation and localization

Middleware is also the natural place for country or language routing. Read the Accept-Language header or a saved locale cookie, then redirect / to /en or /de. Once the user picks a language manually, store it in a cookie and respect it over the header.

For country-level data, rely on what your hosting platform gives you. Older Next.js versions exposed a geo property on the request. Recent versions removed it, and platforms now provide location through request headers or their own helper packages. Don't hard-code one provider's header name without a fallback, or your logic will break the day you move hosts.

Keep geo-based rules light. Use them to pick a sensible default, like currency or language, and always let the user change it. Blocking content by country based on IP alone is easy to get wrong.

Common Next.js middleware mistakes

Middleware runs on the hot path of every matched request, so small mistakes get multiplied. These are the ones to avoid:

  • No matcher, so middleware runs on images, fonts and static files
  • Heavy work like database queries or slow third-party API calls on every request
  • Redirect loops, where the login page itself is protected and redirects to itself
  • Using middleware as the only authorization layer instead of checking again near the data
  • Importing Node-only libraries when middleware runs on the Edge runtime
  • Forgetting to copy cookies set during a token refresh onto the final response

When not to use middleware

Middleware is for fast decisions about where a request goes. It's not a place for business logic. If you need to fetch data for a page, do it in a Server Component. If you need to handle a form submission, use a Server Action or a route handler. If you need to enforce permissions on a record, do it where you load or write that record.

A good test: can this decision be made from the URL, headers and cookies alone? If yes, middleware is a good fit. If it needs a database round trip, it probably belongs somewhere else. That keeps middleware small, fast and easy to reason about, the same way you'd keep a reverse proxy config small.

Frequently Asked Questions

Where do I put the middleware file in Next.js?

In the project root, next to the app folder, or inside src if you use a src directory. Recent Next.js versions renamed the convention from middleware to proxy, so check the docs for your version to get the file name right.

Does Next.js middleware run on the Edge or Node.js runtime?

Historically it ran only on the Edge runtime. Recent Next.js versions also support the Node.js runtime for middleware, and some make it the default. The runtime decides which libraries and APIs you can use, so confirm it before importing server-only packages.

Is middleware enough to protect routes in Next.js?

No. Use it for fast redirects, but always verify the session again in Server Components, route handlers and Server Actions that touch protected data. That way a bypass or misconfigured matcher doesn't expose anything.

What is the difference between redirect and rewrite in middleware?

A redirect tells the browser to go to a new URL, so the address bar changes. A rewrite serves a different route on the server while the browser keeps the original URL. Rewrites are what make invisible A/B tests possible.

How do I stop middleware from running on static files?

Export a config object with a matcher. List only the paths that need middleware, or use a negative pattern that excludes _next/static, _next/image, favicon and other public assets.

Written by Codmaker

An independent product lab. We build and run our own React Native and Next.js apps, and write up what we learn along the way.

See our apps
All guides →
Next.js10 min read

Next.js Server Actions: A Practical Guide

What Next.js Server Actions are, how to use them with forms, how to validate and secure them, and when an API route is still the better choice for the job.

React8 min read

React Compiler: Do You Still Need useMemo?

What the React Compiler does, how to turn it on in Next.js, when useMemo and useCallback still matter, and the mistakes that stop it from optimizing your code.