#does middleware finish running before any app code ?

1 messages · Page 1 of 1 (latest)

slim lily
#

does middleware finish running before any app code ?

vagrant bobcatBOT
#

Hi @slim lily. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, Middleware in Next.js runs before any app code. It is invoked for every route in your project and allows you to run code before a request is completed. Based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly. Middleware also runs before cached content and routes are matched.

Here is the execution order:

  1. headers from next.config.js
  2. redirects from next.config.js
  3. Middleware (rewrites, redirects, etc.)
  4. beforeFiles (rewrites) from next.config.js
  5. Filesystem routes (public/, _next/static/, pages/, app/, etc.)
  6. afterFiles (rewrites) from next.config.js
  7. Dynamic Routes (/blog/[slug])
  8. fallback (rewrites) from next.config.js

You can define which paths Middleware will run on using a custom matcher config or conditional statements.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: