0
0
NextJSframework~8 mins

Redirect and rewrite in middleware in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Redirect and rewrite in middleware
MEDIUM IMPACT
This concept affects page load speed by controlling navigation early in the request lifecycle, impacting how fast users see the correct content.
Handling URL changes to redirect or rewrite paths before rendering
NextJS
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname === '/old-path') {
    return NextResponse.rewrite(new URL('/new-path', request.url));
  }
  return NextResponse.next();
}
Rewriting the URL in middleware avoids a client redirect and serves the new content immediately, reducing load time.
📈 Performance GainSaves one network round trip, improving LCP by 100-200ms
Handling URL changes to redirect or rewrite paths before rendering
NextJS
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname === '/old-path') {
    return NextResponse.redirect(new URL('/new-path', request.url));
  }
  return NextResponse.next();
}
Using Response.redirect triggers a full client-side redirect causing an extra round trip and delays page load.
📉 Performance CostBlocks rendering for 100-200ms due to extra network request
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Middleware RedirectMinimal0Extra delay due to new request[!] OK
Middleware RewriteMinimal0No extra delay, direct content serving[OK] Good
Rendering Pipeline
Middleware runs before the rendering pipeline starts, intercepting requests to redirect or rewrite URLs. Redirects cause a new request cycle, while rewrites serve content directly without extra navigation.
Request Handling
Network
Rendering
⚠️ BottleneckRedirects cause additional network requests delaying the Rendering stage
Core Web Vital Affected
LCP
This concept affects page load speed by controlling navigation early in the request lifecycle, impacting how fast users see the correct content.
Optimization Tips
1Avoid redirects in middleware to prevent extra network requests.
2Use rewrites in middleware to serve content immediately and improve LCP.
3Check Network panel for redirects to identify performance bottlenecks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance drawback of using a redirect in Next.js middleware?
AIt blocks JavaScript execution on the client
BIt causes an extra network request delaying page load
CIt increases DOM nodes causing reflows
DIt increases CSS selector complexity
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page and watch for 3xx redirect status codes and extra requests
What to look for: Presence of redirect requests indicates slower load; absence means rewrites are used improving performance