Performance: Middleware for API routes
Middleware affects the time to process API requests and the responsiveness of the server, impacting interaction speed and server load.
Jump into concepts and practice - no test required
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(); }
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(); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Middleware with blocking external API calls | 0 (server-side) | 0 | 0 | [X] Bad |
| Middleware with local synchronous checks | 0 (server-side) | 0 | 0 | [OK] Good |
x-auth: secret is sent?
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.headers.get('x-auth') !== 'secret') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
}import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.headers.get('authorization')) {
NextResponse.redirect('/login');
}
return NextResponse.next();
}token is missing or empty. Which code correctly implements this behavior?