Introduction
404 can be handled at the bottom of the middleware pipeline when none of them could handle the request.
here more details on how to implement it in an express js project
https://expressjs.com/en/starter/faq.html#:~:text=How%20do%20I%20handle%20404%20responses%3F
Astro middleware
here working fine, implemented in an Astro as node middleware with node project.
const app = express();
app.use(express.static('dist/client/'))
app.use(express.static('dist/client/raw'))
app.use(authRouter)
app.use(ssrHandler);
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!")
})
here a link to a full working project
https://github.com/MicroWebStacks/astro-big-doc/blob/a2049e286424c256e9d406f7df84dfedf65527ad/server/server.js#L17
Astro Standalone
in standalone mode it is possible to add a collector page such as [...any].astro
that collects all requests not hit by other pages and then pick the required content to be returned and place it in its body as follows
---
import Page_404 from './404.astro'
const {any} = Astro.params;
console.log(`${any} does not exist`)
---
<Page_404/>
Examples
here are examples where this can be tested
Github repo : https://github.com/MicroWebStacks/astro-examples#08_404-error-handling
StackBliz : https://stackblitz.com/github/MicroWebStacks/astro-examples/tree/main/08_404-error-handling
CodeSandbox : https://codesandbox.io/s/github/MicroWebStacks/astro-examples/tree/main/08_404-error-handling
Gitpod (test in prod) : https://gitpod.io/?on=gitpod#https://github.com/MicroWebStacks/astro-examples/tree/main/08_404-error-handling