How do you rewrite a request to a different path using middleware without changing the URL the user sees?
Short answer
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…
Advertisement
AModel answer
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.
Likely 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?
Related topics