0
0
NextJSframework~8 mins

Protected routes with middleware in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Protected routes with middleware
MEDIUM IMPACT
This affects the initial page load speed and interaction responsiveness by adding server-side checks before rendering protected pages.
Protecting pages by checking user authentication
NextJS
import { NextResponse } from 'next/server';
export function middleware(request) {
  const token = request.cookies.get('token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/protected/:path*'] };
Middleware runs before rendering, redirecting unauthenticated users early and avoiding client-side flicker.
📈 Performance GainReduces LCP by 200-300ms by preventing protected page render on unauthenticated access
Protecting pages by checking user authentication
NextJS
export default function Page() {
  useEffect(() => {
    if (!userIsLoggedIn()) {
      router.push('/login');
    }
  }, []);
  return <div>Protected Content</div>;
}
Client-side redirect causes the protected page to load first, increasing LCP and causing flicker.
📉 Performance CostBlocks rendering until redirect triggers, increasing LCP by 200-300ms on slow networks
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Client-side redirect after page loadFull DOM created then discardedMultiple reflows due to redirectHigh paint cost due to flicker[X] Bad
Middleware redirect before page loadNo DOM created for protected pageZero reflows on redirectLow paint cost, no flicker[OK] Good
Rendering Pipeline
Middleware intercepts requests before rendering, allowing redirects or rewrites before HTML is generated.
Server Request Handling
HTML Generation
Client Rendering
⚠️ BottleneckServer Request Handling due to synchronous auth checks
Core Web Vital Affected
LCP
This affects the initial page load speed and interaction responsiveness by adding server-side checks before rendering protected pages.
Optimization Tips
1Use middleware to redirect unauthenticated users before page rendering.
2Avoid client-side redirects for protected routes to reduce flicker and LCP.
3Keep middleware logic simple and cache tokens to optimize server response time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using middleware for protected routes in Next.js?
ALoads the entire page before checking authentication
BIncreases client-side JavaScript bundle size
CRedirects users before page rendering, reducing LCP
DTriggers multiple reflows during redirect
DevTools: Performance
How to check: Record page load with and without middleware; look for time to first contentful paint and network redirects.
What to look for: Shorter LCP and absence of client-side redirect in waterfall indicate good middleware performance.