Middleware: Intercepting Requests
6 min read
Intercepting Requests with Next.js Middleware π¦
Welcome, future Next.js wizard! π§ββοΈ So, you've been building your application, and now you're wondering how to handle things that need to happen for multiple pages or API routes. Do you repeat the same logic in every getServerSideProps or API route? "Ain't nobody got time for that!" And that's where the magic of Middleware comes in.
What's the Big Deal with Middleware Anyway? π€
At its core, Next.js Middleware allows you to run code before a request is completed. Think of it as a friendly bouncer at the door of your application. Before letting a request in to see a page or hit an API endpoint, the bouncer can check their ID (authentication), give them a different menu (A/B testing), or send them to a different room entirely (redirects). This all happens on the server, so it doesn't add any extra weight to your frontend code.
The problem it solves is handling cross-cutting concerns in a centralized way. Instead of scattering your authentication checks, logging, or redirect logic across your entire application, you can manage it all in one place.
1. The middleware.ts File: Where the Magic Happens on the Edge β¨
To get started with Middleware, you simply create a middleware.ts (or middleware.js) file in the root of your project, at the same level as your pages or app directory. Next.js will automatically pick up this file and use it as the entry point for all your middleware logic.
Edge Execution: "Living on the Edge" π€
One of the coolest things about Next.js Middleware is that it runs on the Edge. Imagine you have a global network of servers (a CDN). When a user makes a request, instead of it traveling all the way to a central server, the middleware code is executed on a server that is geographically closest to them.
What does this mean for you?
- Lower Latency: Since the code runs closer to the user, responses are incredibly fast.
- No Cold Starts: Edge functions are designed for super-fast initialization, so you don't have to wait for a server to "wake up".
- Global Scalability: Your middleware can handle a massive number of requests from all over the world without breaking a sweat.
However, there's a small catch. The Edge runtime is a lightweight environment and doesn't have access to all Node.js APIs, like the file system (fs). But you can use web-standard APIs like fetch, Request, and Response.
Here's a very basic middleware.ts file:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Your middleware logic goes here
console.log('Middleware is running for:', request.nextUrl.pathname);
// Allow the request to continue
return NextResponse.next();
}By default, this middleware will run for every request to your application. But what if you only want it to run for specific paths? That's where the matcher comes in.
You can export a config object from your middleware file to specify which paths the middleware should apply to.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// This will only run for requests to /dashboard and its sub-paths
return NextResponse.next();
}
export const config = {
matcher: '/dashboard/:path*',
};You can also use an array to match multiple paths.
2. Dynamic Redirects and Rewrites on the Edge βͺοΈ
A common use case for middleware is to dynamically redirect or rewrite requests.
- Redirect: This sends the user to a completely different URL. The URL in the browser's address bar will change. This is useful for things like authentication, where you want to send unauthenticated users to a login page.
- Rewrite: This shows the content of a different URL without changing the URL in the browser's address bar. It's like a behind-the-scenes switcheroo. This is great for A/B testing or serving different content based on certain conditions.
Dynamic Redirects in Action
Imagine you want to protect a /dashboard route so that only authenticated users can access it. Your middleware could check for an authentication token (we'll cover cookies in the next section) and redirect to /login if it's not present.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const authToken = request.cookies.get('auth-token')?.value;
if (!authToken) {
const loginUrl = new URL('/login', request.url);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: '/dashboard/:path*',
};Dynamic Rewrites for A/B Testing
Let's say you're running an A/B test on your homepage. You want to show 50% of users a new version of the page located at /new-home without changing the URL.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Randomly assign users to group A or B
const bucket = Math.random() < 0.5 ? 'a' : 'b';
if (bucket === 'b' && request.nextUrl.pathname === '/') {
const newHomeUrl = new URL('/new-home', request.url);
return NextResponse.rewrite(newHomeUrl);
}
return NextResponse.next();
}3. Reading, Setting, and Deleting Cookies in Middleware πͺ
Cookies are a fundamental part of web applications, often used for sessions, personalization, and tracking. Middleware gives you the power to interact with cookies before the request reaches your application logic.
Reading Cookies
You can easily access incoming request cookies through the request.cookies object.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const theme = request.cookies.get('theme')?.value;
if (theme) {
console.log(`User's preferred theme is: ${theme}`);
}
return NextResponse.next();
}Setting and Deleting Cookies
To set or delete a cookie, you'll need to work with the response object. The general flow is to create a response (usually by calling NextResponse.next()), modify its cookies, and then return it.
Here's an example of setting a cookie:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Set a new cookie
response.cookies.set('user-preference', 'dark-mode', {
maxAge: 60 * 60 * 24 * 7, // 1 week
});
return response;
}And here's how you can delete a cookie:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Delete a cookie
response.cookies.delete('old-cookie');
return response;
}Fun Fact: The term "cookie" was coined by web pioneer Lou Montulli. It's derived from "magic cookie," a term from the Unix programming world for a packet of data a program receives and sends back unchanged.
Hands-on Industry Practices and Key Takeaways π
- Keep it Lightweight: Since middleware can run on every matching request, it's crucial to keep your logic minimal and efficient. Avoid heavy computations or long-running database queries.
- Modularize Your Logic: For larger applications, your
middleware.tsfile can get crowded. It's a good practice to organize your logic into separate functions or modules and import them into your main middleware file. - Error Handling is Your Friend: Always wrap your middleware logic in
try...catchblocks to gracefully handle any unexpected errors. - Optimize Your
matcher: Be as specific as possible with yourmatcherpatterns to ensure your middleware only runs where it's needed.
By mastering Next.js Middleware, you're adding a powerful tool to your developer toolkit that allows you to build more performant, secure, and personalized web applications.
π Extra Reading & References
Challenge
You are tasked with implementing A/B testing for a new product page design. Your goal is to create a Next.js middleware that directs users to either the original page or a new version based on a cookie.
Requirements:
- Create a middleware function that intercepts requests.
- Implement path matching: The middleware must only run on the
/productspath. Do not use a wildcard that would match/products/new. - Existing User Logic:
- Check for an incoming cookie named
ab-test-variant. - If the cookie value is
'new-feature', rewrite the request to/products/new. - If the cookie value is
'control', allow the request to proceed to/productswithout modification.
- Check for an incoming cookie named
- New User Logic:
- If the
ab-test-variantcookie does not exist, you must assign the user to a group. - Use
Math.random()to randomly assign the user to either the'new-feature'group or the'control'group (a 50/50 split). - Create a response object.
- Set the
ab-test-variantcookie on the response with the assigned group value. The cookie should expire in one week (maxAge: 604800). - If the user was assigned to the
'new-feature'group, rewrite the request to/products/newusing the created response object. - If the user was assigned to the
'control'group, return the response object without a rewrite, allowing them to proceed to/products.
- If the
Expected result
Your final code should be a complete middleware.ts file that correctly implements the specified A/B testing logic.
The submitted code must contain:
An exported
middlewarefunction that:- Correctly retrieves the
ab-test-variantcookie from therequest. - Conditionally rewrites the URL to
/products/newif the cookie value is'new-feature'. - Properly handles the absence of the cookie by:
- Generating a random assignment (
'control'or'new-feature'). - Creating a
NextResponseobject. - Setting the
ab-test-variantcookie on the response with the correct value and amaxAgeof604800. - Returning the appropriate response (a rewrite or the plain response object based on the random assignment).
- Generating a random assignment (
- Correctly retrieves the
An exported
configobject that contains:- A
matcherproperty. - The value of the
matcherproperty must be the exact string'/products'.
- A