Skip to content

Missing detail for node adapter middleware examples #13864

In review
sharadvc/docs
#3

Description

@ashleigh-yeoman

📚 Subject area/topic

Examples

📋 Page(s) affected (or suggested, for new content)

https://docs.astro.build/en/guides/integrations-guide/node/#middleware

📋 Description of content that is out-of-date or incorrect

The fastify example doesn't take into account error pages.

As-is, the example will hit https://github.com/withastro/astro/blob/d365c975ba2d88fc1dbdfe698df2bf9e2eafadce/packages/integrations/node/src/serve-app.ts#L119 and result in a blank error response, rather than rendering e.g. 404.astro

I feel like there should at least be an additional example, in order to have both the rendering of error pages e.g. 404.astro, and serving of client assets (which is helpful when deploying to e.g. aws lambda using @fastify/aws-lambda).

import type { NextHandleFunction } from "@fastify/middie";

import { readdirSync } from "node:fs";

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

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

const root = fileURLToPath(new URL('./dist/client', import.meta.url));

await app
  .register(fastifyStatic, { root })
  .register(fastifyMiddie);

const assetFilenames = readdirSync(root).map(({ name }) => `/${name}`);

const fn: NextHandleFunction = async (req, res, next) => {
    if (req.url) {
        const isAsset = assetFilenames.includes(req.url);
        if (isAsset || req.url.startsWith("/_astro")) {
            next();
            return;
        }
    }

    // Not a client asset, let astro take over
    await ssrHandler(req, res);
};

app.use(fn);

🖥️ Reproduction in StackBlitz (if reporting incorrect content or code samples)

No response

Activity

  1. added
    improve or update documentation
    on May 11, 2026
  2. spa77k commented on Oct 22, 2026

    @spa77k

    I was able to reproduce this with the current versions, and it looks like it affects the Express example as well, not just Fastify.

    Versions: astro 7.4.2, @astrojs/node 11.1.9 (mode: 'middleware'), fastify 5.12.7, @fastify/middie 9.3.6, @fastify/static 10.1.7, express 5.3.0, Node 24.

    Steps: a project with src/pages/index.astro and src/pages/404.astro, built, then started with the run-server.mjs examples from the docs as-is.

    Result for GET /does-not-exist:

    • Fastify example: Fastify's JSON 404 ({"message":"Route GET:/does-not-exist not found",...})
    • Express example: Express's default Cannot GET /does-not-exist page

    404.astro is not rendered in either case. It is the same whether 404.astro is prerendered or on-demand.

    This seems to be expected adapter behavior: when no route matches and a next function is passed, serve-app.ts calls next() so the host server can handle the request. Without next, Astro renders the 404 page. So the examples work as written, but users who expect their custom 404 page won't get it.

    Passing the request back to the handler without next at the end of the chain renders 404.astro (I tested both prerendered and on-demand 404 pages, and normal pages and static files still work):

    // Fastify
    app.use(ssrHandler);
    app.setNotFoundHandler((request, reply) => {
      reply.hijack();
      ssrHandler(request.raw, reply.raw);
    });
    // Express
    app.use(ssrHandler);
    app.use((req, res) => ssrHandler(req, res));

    Would you like the docs to cover this? I could open a PR for whichever you prefer:

    1. Add the fallback to both examples
    2. Keep the examples as they are and add a short note (with the snippet) explaining that unmatched routes are passed to next(), and how to render the Astro 404 page instead
  3. ashleigh-yeoman commented on Oct 29, 2026

    @ashleigh-yeoman
    Author

    I've since tried Koa, and by using koa-static for static assets, just doing this works fine

    // ...
    const app = new Koa();
    app.use(serve(root));
    app.use(({ req, res }) => ssrHandler(req, res));

    so I don't know if Fastify or Express are similarly fine now by just passing req and res to the astro handler, or if they still need clarification in the docs.

  4. ArmandPhilippot commented on Nov 23, 2026

    @ArmandPhilippot
    Member

    Sorry @ashleigh-yeoman , I totally missed there was more interactions on that issue! I was first waiting to see if people considered that to be a docs issue or not. This is some old contents, and no one complained in 4 years AFAIK...

    FYI, it works with Koa because you don't pass next():

    app.use(({ req, res }) => ssrHandler(req, res));

    With it, your server handles the requests. Without it, Astro can renders the custom 404.

    You can do the same with Express. This also works with Fastify, but you need to use their own API (app.setNotFoundHandler(), IIUC how it works, I'm not a Fastify user).

    We usually aim to provide minimal examples. This is not Astro role to explain how third-party tools work (e.g. the Fastify API that could change in the next version...). That's why we do not show how to serve assets but instead we say:

    Note that middleware mode does not do file serving. You'll need to configure your HTTP framework to do that for you. By default the client assets are written to ./dist/client/.

    And that's also why (in addition to not following our contribution guidelines), I didn't like all the AI-generated PRs we received for that...

    Now, I do think this section could be clearer! But, I don't think adding a new example is the right call. I'm also not sure adding more lines to the existing examples is the right fix. We still want something sufficiently minimal and generic to be applied to other frameworks here.

    I tried a different approach by documenting more precisely the handler() export. Would something like https://armand-node-middleware-handler.previews.docs.astro.build/en/guides/integrations-guide/node/#middleware (and its subsection) have helped you understand how it works?

  5. ashleigh-yeoman commented on Nov 24, 2026

    @ashleigh-yeoman
    Author

    From the handler section

    You can optionally provide a next() function as the third argument. This allows your server to handle requests that do not match any route in your Astro project. Without it, the handler renders your custom 404 page instead.

    I think this would have helped avoid some of the diving through the astro codebase I did before creating this issue. Also I think the if (req.url) block in my original code example was because I wasn't aware of the setNotFoundHandler method for fastify.

    This is not Astro role to explain how third-party tools work

    You're right, it's not Astro's job to explain how other people's code works. But still, you have examples for configuring express and fastify to serve static assets, without allowing the astro server to SSR the custom 404 page.

    From the middleware section

    The following example serves the client files, and passes all other requests to the handler

    that feels like a bit of a misnomer imo if the handler doesn't serve any configured 404 pages.

    But yeah, all in all, I think the docs about the handler export help a lot

  6. ArmandPhilippot commented on Nov 24, 2026

    @ArmandPhilippot
    Member

    Thank you, your feedback is helpful! 🙌🏽 I tried to reword a bit the Middleware section. I hope it's clearer now.

    You're right, it's not Astro's job to explain how other people's code works. But still, you have examples for configuring express and fastify to serve static assets, without allowing the astro server to SSR the custom 404 page.

    I hear you... My concern is that overloading an example might make it harder for some people to grasp. And providing multiple examples for third-party tools is a bit annoying too maintenance-wise. It's always tricky to find the right balance.

    So, if you think the new description is clearer, I would like to start with that. If we receive further feedback later on, we can then consider adding more examples!

  7. ashleigh-yeoman commented on Nov 24, 2026

    @ashleigh-yeoman
    Author

    Yeah, it's definitely clearer imo. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    improve or update documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions