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.
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*'] };
export default function Page() { useEffect(() => { if (!userIsLoggedIn()) { router.push('/login'); } }, []); return <div>Protected Content</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side redirect after page load | Full DOM created then discarded | Multiple reflows due to redirect | High paint cost due to flicker | [X] Bad |
| Middleware redirect before page load | No DOM created for protected page | Zero reflows on redirect | Low paint cost, no flicker | [OK] Good |