#How to handle 404 not found error with node adapter in "middleware" mode?

2 messages · Page 1 of 1 (latest)

fluid hedge
#

I use fastify for my server and here is my basic setup

import { fileURLToPath } from "node:url";
import fastifyMiddie from "@fastify/middie";
import fastifyStatic from "@fastify/static";
import Fastify from "fastify";
import { handler as ssrHandler } from "./dist/server/entry.mjs";

const app = Fastify({ logger: true });

await app
    .register(fastifyStatic, {
        root: fileURLToPath(new URL("./dist/client", import.meta.url)),
    })
    .register(fastifyMiddie);
app.use(ssrHandler);

await app.listen({ port: 3000, host: "0.0.0.0" });

When I go to some non-existent page, I just get a 404 json response from fastify.

{
  "message": "Route GET:/532 not found",
  "error": "Not Found",
  "statusCode": 404
}

But I want to show my 404.astro page instead. Even when I try to access /404 path, I get the same default response from fastify.

I couldn't find any info on how to do this in the docs or other issues, so I would appreciate any help.

gray crater
#

If you have a static 404 page (prerender set to true for server mode), you could use https://fastify.dev/docs/latest/Reference/Server/#setnotfoundhandler e.g.

await app
    .register(fastifyStatic, {
        root: fileURLToPath(new URL("./dist/client", import.meta.url)),
    })
    .setNotFoundHandler((_, reply) => {
        return reply.code(404).type('text/html').sendFile('404.html');
    })
    .register(fastifyMiddie);
app.use(ssrHandler);