Skip to main content

Nextjs Middleware

Middleware allows you to run code before a request is completed.

Based on the incoming request you can choose to modify the response. Examples of which are:

  • rewriting
  • redirecting
  • adding headers
  • setting cookies

Context

  • Security — Auth checks that middleware enforces
  • App Router — Routing layer that middleware intercepts
  • Services — Service boundaries middleware guards

Questions

Where does middleware end and application logic begin?

  • What belongs in middleware versus a server action?
  • How do you keep middleware fast when it runs on every request?
  • When does adding one more middleware check become the performance bottleneck?