Advertisement
Advanced Next.js, Middleware

What performance considerations should you keep in mind when writing middleware, since it runs on every matched request?

Short answer

Since middleware runs on the Edge Runtime and executes before every matched request, you should keep its logic fast and lightweight, avoid making slow external API calls or database queries directly inside it, and use the matcher configuration carefully to prevent it from…

Save Next.js mock interview
Advertisement
AModel answer
Since middleware runs on the Edge Runtime and executes before every matched request, you should keep its logic fast and lightweight, avoid making slow external API calls or database queries directly inside it, and use the matcher configuration carefully to prevent it from running on routes where it adds no value.
// Avoid slow operations directly in middleware
export function middleware(request) {
  // Fast check using cookies, not a slow database call
  const hasSession = request.cookies.has('session');
  if (!hasSession) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
Real-world example
A team notices their site feels slightly slower after adding middleware that made a database call on every request, so they refactor it to only check for a session cookie instead, dramatically improving response times.
Likely follow-ups
  • What operations are safe to perform inside middleware given its runtime limitations?
  • How do you measure the performance impact of your middleware?
Related topics