#Return 500 page in middleware
4 messages · Page 1 of 1 (latest)
Hi @drowsy lantern. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro’s docs don’t describe a direct “render the 500 page from middleware” API (like a helper you can call), so the options are indirect.
What is documented:
- If an error is thrown during rendering (including from middleware), Astro will serve a 500 error page for on‑demand rendered pages. If you create
src/pages/500.astro, that page is used as the custom 500 error page. [Custom 500] - Middleware runs before serving a 500 page, unless the server error occurred in the middleware itself. If middleware fails, you won’t have access to
Astro.localsin the 500 page. [Middleware error pages]
From the middleware side, the only documented requirement is that onRequest() must return a Response (or call next()), otherwise you get middleware errors like MiddlewareNoDataOrNextCalled or MiddlewareNotAResponse. [Middleware exports; NoDataOrNext; NotAResponse]
Because there is no documented helper to “invoke the 500.astro page” from middleware, the supported ways to end up on the 500 page are:
- Let an error bubble up from middleware
Throw an error in middleware; Astro will treat it as a server error and, for on‑demand rendered pages, rendersrc/pages/500.astroif it exists. [Custom 500; Middleware error pages]
- Return your own 500
Response
You can always construct and return anew Response(...)withstatus: 500from middleware. This will not automatically render500.astro; it just sends a 500 response. The docs only state that middleware must return aResponse, not that Astro will wire that to the 500 page. [MiddlewareHandler]
There is no explicit documentation showing middleware calling something like context.rewrite('/500') to render the 500 page, and the routing docs only show rewrites to arbitrary routes (including /404), not /500. [Rewrites]
So, based on the available docs:
- To “trigger” the 500 error page from middleware, the documented path is to throw an error and let Astro handle it.
- To just send a 500 status from middleware, return a
Responsewithstatus: 500.