0
0
NextJSframework~8 mins

Middleware for API routes in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Middleware for API routes
MEDIUM IMPACT
Middleware affects the time to process API requests and the responsiveness of the server, impacting interaction speed and server load.
Adding authentication checks to API routes
NextJS
import { NextResponse } from 'next/server';
import { verifyToken } from './auth';

export default function middleware(req) {
  const token = req.cookies.get('token')?.value;
  if (!verifyToken(token)) return new Response('Unauthorized', { status: 401 });
  return NextResponse.next();
}
Uses local token verification without external calls, reducing latency and server dependency.
📈 Performance GainNon-blocking, reduces request delay by 50-200ms
Adding authentication checks to API routes
NextJS
import { NextResponse } from 'next/server';

export default async function middleware(req) {
  const user = await fetch('https://auth.example.com/validate', { headers: { cookie: req.headers.get('cookie') } });
  if (!user.ok) return new Response('Unauthorized', { status: 401 });
  return NextResponse.next();
}
Middleware makes a blocking external API call on every request, delaying response and increasing server load.
📉 Performance CostBlocks rendering for 50-200ms per request depending on network latency
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Middleware with blocking external API calls0 (server-side)00[X] Bad
Middleware with local synchronous checks0 (server-side)00[OK] Good
Rendering Pipeline
Middleware runs before the API route handler, affecting the server response time and thus the interaction to next paint (INP) metric.
Server Processing
Network Response
⚠️ BottleneckBlocking asynchronous operations inside middleware
Core Web Vital Affected
INP
Middleware affects the time to process API requests and the responsiveness of the server, impacting interaction speed and server load.
Optimization Tips
1Avoid blocking asynchronous calls in middleware to keep API responses fast.
2Use local synchronous checks or caching to reduce middleware latency.
3Monitor server response times in DevTools to detect middleware bottlenecks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using middleware that calls external APIs on every request?
AIt reduces the bundle size of the frontend code.
BIt increases server response time and delays user interaction.
CIt improves the Largest Contentful Paint (LCP) metric.
DIt decreases the number of DOM nodes rendered.
DevTools: Network and Performance panels
How to check: Open DevTools, go to Network panel, filter API requests, check response times; use Performance panel to record and analyze server response delays.
What to look for: Look for long server response times before the API response arrives; high blocking time indicates slow middleware.