0
0
NextJSframework~8 mins

Request modification in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Request modification
MEDIUM IMPACT
This affects the server response time and client perceived load speed by modifying requests before they reach the server or client.
Modifying HTTP requests in Next.js middleware
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = new URL(request.url);
  if (url.pathname === '/old-path') {
    url.pathname = '/new-path';
    return NextResponse.rewrite(url);
  }
  return NextResponse.next();
}
Only rewrites requests when necessary, reducing server processing and avoiding redundant rewrites.
📈 Performance Gainreduces average middleware processing time by 30-50%
Modifying HTTP requests in Next.js middleware
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = new URL(request.url);
  url.pathname = '/old-path';
  return NextResponse.rewrite(url);
}
Rewriting requests without caching or conditional checks causes unnecessary rewrites on every request, increasing server processing time.
📉 Performance Costblocks rendering for 20-50ms per request depending on server load
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Unconditional rewrite in middleware0 (server-side)00[X] Bad
Conditional rewrite with minimal logic0 (server-side)00[OK] Good
Rendering Pipeline
Request modification happens before the server generates the response, affecting the critical rendering path by changing the resource requested or headers sent.
Request Handling
Server Response
Critical Rendering Path
⚠️ BottleneckServer Response time increases if request modification is inefficient or excessive.
Core Web Vital Affected
LCP
This affects the server response time and client perceived load speed by modifying requests before they reach the server or client.
Optimization Tips
1Avoid unconditional rewrites in middleware to reduce server processing time.
2Use conditional logic to modify requests only when necessary.
3Cache or memoize results when possible to speed up repeated requests.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a key performance risk when modifying requests unconditionally in Next.js middleware?
AIncreased server processing time due to unnecessary rewrites
BIncreased DOM nodes causing layout shifts
CHigher client-side JavaScript bundle size
DSlower CSS parsing on the client
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and inspect the request URL and response headers to verify if rewrites or redirects occur.
What to look for: Look for extra redirects or rewrites causing delays; check timing waterfall for server response time.