diff --git a/packages/fastify/src/web.ts b/packages/fastify/src/web.ts index 46116ab4754a..8814ee604fff 100644 --- a/packages/fastify/src/web.ts +++ b/packages/fastify/src/web.ts @@ -6,6 +6,7 @@ import fg from 'fast-glob' import type { FastifyInstance, FastifyReply, + FastifyRequest, HookHandlerDoneFunction, } from 'fastify' @@ -47,10 +48,21 @@ export async function redwoodFastifyWeb( const indexPath = getFallbackIndexPath() // For SPA routing, fallback on unmatched routes and let client-side 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) + } + ) done() }