0
0
NextJSframework~8 mins

Middleware.ts file convention in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Middleware.ts file convention
MEDIUM IMPACT
Middleware.ts affects the initial request handling and routing speed, impacting how fast the server responds and the page starts loading.
Handling authentication and redirects in middleware
NextJS
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  if (!request.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
Removes heavy computation, allowing middleware to run quickly and pass control to next handler faster.
📈 Performance GainReduces server blocking to under 5 ms, improving LCP significantly
Handling authentication and redirects in middleware
NextJS
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  // Heavy synchronous computation
  for (let i = 0; i < 1000000000; i++) {}
  if (!request.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
Blocking synchronous code delays middleware completion, increasing server response time and delaying page load.
📉 Performance CostBlocks server response for 200+ ms depending on CPU, increasing LCP
Performance Comparison
PatternServer Blocking TimeMiddleware ComplexityImpact on LCPVerdict
Heavy synchronous logic in middleware200+ msHighDelays LCP significantly[X] Bad
Minimal logic with quick checksUnder 5 msLowImproves LCP[OK] Good
Rendering Pipeline
Middleware.ts runs before the page renders, intercepting requests to modify or redirect them. It affects the server response time, which impacts the browser's ability to start rendering the page.
Server Request Handling
Routing
Initial Response
⚠️ BottleneckServer Request Handling when middleware is slow or does heavy work
Core Web Vital Affected
LCP
Middleware.ts affects the initial request handling and routing speed, impacting how fast the server responds and the page starts loading.
Optimization Tips
1Avoid heavy synchronous computations in middleware.ts.
2Keep middleware logic minimal and fast to reduce server blocking.
3Use middleware only for essential routing or authentication checks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of adding heavy synchronous code in middleware.ts?
AIt increases CSS paint time
BIt blocks the server response, delaying page load
CIt causes layout shifts on the page
DIt reduces JavaScript bundle size
DevTools: Performance
How to check: Record a server-side profile or use Next.js telemetry to measure middleware execution time during request handling.
What to look for: Look for long blocking times in middleware functions that delay server response and increase LCP.