From 27bb09de396a3a8812ad67cfc8e4c0efcd7ecd1f Mon Sep 17 00:00:00 2001 From: Dominic Saadi Date: Wed, 1 Nov 2023 23:08:12 -0700 Subject: [PATCH] fix(api-server): copy fallback fix from #9272 (#9369) This PR copies the fix in https://github.com/redwoodjs/redwood/pull/9272 into `@redwoodjs/api-server`. The `@redwoodjs/api-server` can be accessed via `npx @redwooodjs/api-server rw-server api`. We won't have to do this once the code between the two entry points is deduplicated but till then, yeah. --- .../api-server/src/plugins/withWebServer.ts | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/api-server/src/plugins/withWebServer.ts b/packages/api-server/src/plugins/withWebServer.ts index f347e672c2b2..fa34797ce134 100644 --- a/packages/api-server/src/plugins/withWebServer.ts +++ b/packages/api-server/src/plugins/withWebServer.ts @@ -2,7 +2,7 @@ import fs from 'fs' import path from 'path' import fastifyStatic from '@fastify/static' -import type { FastifyInstance, FastifyReply } from 'fastify' +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify' import { getPaths } from '@redwoodjs/project-config' @@ -54,10 +54,21 @@ const withWebServer = async ( // For SPA routing fallback on unmatched routes // And let JS routing take over - fastify.setNotFoundHandler({}, function (_, reply: FastifyReply) { - reply.header('Content-Type', 'text/html; charset=UTF-8') - reply.sendFile(indexPath) - }) + fastify.setNotFoundHandler( + {}, + function (req: FastifyRequest, reply: FastifyReply) { + const requestedExtension = path.extname(req.url) + // If it's requesting some sort of asset, e.g. .js or .jpg files + // Html files should fallback to the index.html + if (requestedExtension !== '' && requestedExtension !== '.html') { + reply.code(404) + return reply.send('Not Found') + } + + reply.header('Content-Type', 'text/html; charset=UTF-8') + return reply.sendFile(indexPath) + } + ) return fastify }