5 questions found
What is middleware in Next.js, and when does it run?
Beginner
Middleware is a special function defined in a middleware.js file at the root of your project that runs before a request completes, letting you inspect, modify, redirect, or block requests before they reach your actual pages or API routes.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
console.log('Request received:', request.nextUrl.pathname);
return NextResponse.next();
}
Real-world example
An application logs every incoming request's path using middleware, giving the team visibility into traffic patterns before any page even starts rendering.
Common follow-ups: Does middleware run on every single request by default?;What is the difference between middleware and a route handler?
Edge Runtime vs Node.js Runtime;Routing (App/Pages Router)
How do you limit which routes your middleware actually applies to?
Beginner
You export a config object with a matcher array from your middleware file, specifying the exact paths or patterns where the middleware should run, preventing it from executing unnecessarily on routes where it is not needed, such as static assets.
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*']
};
Real-world example
A team configures their authentication middleware to only run on dashboard and admin routes, avoiding unnecessary overhead on public marketing pages that do not need any authentication checks.
Common follow-ups: Can you use a regular expression in the matcher configuration?;What happens to routes not included in the matcher?
Authentication & Authorization in Next.js;Routing (App/Pages Router)
How would you use middleware to redirect users based on their location or device type?
Intermediate
You read information available on the request object, such as geolocation data or the user agent header, inside your middleware function, and then return a redirect response pointing to a different path if the condition matches, such as sending mobile visitors to a mobile optimized version of a page.
import { NextResponse } from 'next/server';
export function middleware(request) {
const country = request.geo?.country;
if (country === 'FR') {
return NextResponse.redirect(new URL('/fr', request.url));
}
}
Real-world example
An online store redirects visitors from France to a dedicated French language storefront automatically, based on geolocation information read inside its middleware function.
Common follow-ups: Is geolocation data always accurate and available in every deployment environment?;How do you avoid an infinite redirect loop in middleware?
Internationalization (i18n) in Next.js;Redirects & Rewrites Configuration
How do you rewrite a request to a different path using middleware without changing the URL the user sees?
Intermediate
You return a rewrite response from your middleware function pointing to the internal path you actually want to serve, and Next.js will render that different page while keeping the original URL visible in the user's browser address bar, which is useful for A/B testing or serving different content based on conditions.
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.cookies.get('experiment') === 'variant-b') {
return NextResponse.rewrite(new URL('/variant-b', request.url));
}
}
Real-world example
A company runs an A/B test on its homepage, silently serving a different page layout to half of its visitors using middleware rewrites, without their URL ever changing.
Common follow-ups: What is the difference between a redirect and a rewrite in middleware?;How do you assign users consistently to the same A/B test variant?
Redirects & Rewrites Configuration;Testing Next.js Applications
What performance considerations should you keep in mind when writing middleware, since it runs on every matched request?
Advanced
Since middleware runs on the Edge Runtime and executes before every matched request, you should keep its logic fast and lightweight, avoid making slow external API calls or database queries directly inside it, and use the matcher configuration carefully to prevent it from running on routes where it adds no value.
// Avoid slow operations directly in middleware
export function middleware(request) {
// Fast check using cookies, not a slow database call
const hasSession = request.cookies.has('session');
if (!hasSession) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
Real-world example
A team notices their site feels slightly slower after adding middleware that made a database call on every request, so they refactor it to only check for a session cookie instead, dramatically improving response times.
Common follow-ups: What operations are safe to perform inside middleware given its runtime limitations?;How do you measure the performance impact of your middleware?
Edge Runtime vs Node.js Runtime;Web Vitals & Performance Monitoring