Performance: Middleware.ts file convention
Middleware.ts affects the initial request handling and routing speed, impacting how fast the server responds and the page starts loading.
Jump into concepts and practice - no test required
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(); }
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(); }
| Pattern | Server Blocking Time | Middleware Complexity | Impact on LCP | Verdict |
|---|---|---|---|---|
| Heavy synchronous logic in middleware | 200+ ms | High | Delays LCP significantly | [X] Bad |
| Minimal logic with quick checks | Under 5 ms | Low | Improves LCP | [OK] Good |
middleware.ts file in a Next.js project?middleware.ts?export const middleware = (req) => NextResponse.next(); which is valid and recommended.middleware.ts snippet, what will happen when a request to /dashboard is made?
import { NextResponse } from 'next/server';
export const config = { matcher: ['/dashboard'] };
export const middleware = (req) => {
if (!req.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
};middleware.ts code snippet:
import { NextResponse } from 'next/server';
export const middleware = (req) => {
if (req.cookies.token === undefined) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
};req.cookies.get('name'), not as object properties.req.cookies.token will be undefined or cause error; correct is req.cookies.get('token').middleware.ts to run only on API routes starting with /api/private and redirect users without a valid auth cookie to /api/auth/unauthorized. Which config and middleware code correctly implements this?/api/private/:path* correctly matches all routes under /api/private.req.cookies.get('auth') is correct. Redirect uses NextResponse.redirect(new URL(...)) with full URL.