Skip to content

Commit 616b4d6

Browse files
committed
fix(api-server): copy fallback fix from #9272 (#9369)
This PR copies the fix in #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.
1 parent 4bb8b33 commit 616b4d6

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

packages/api-server/src/plugins/withWebServer.ts

+16-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import fs from 'fs'
22
import path from 'path'
33

44
import fastifyStatic from '@fastify/static'
5-
import type { FastifyInstance, FastifyReply } from 'fastify'
5+
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
66

77
import { getPaths } from '@redwoodjs/project-config'
88

@@ -54,10 +54,21 @@ const withWebServer = async (
5454

5555
// For SPA routing fallback on unmatched routes
5656
// And let JS routing take over
57-
fastify.setNotFoundHandler({}, function (_, reply: FastifyReply) {
58-
reply.header('Content-Type', 'text/html; charset=UTF-8')
59-
reply.sendFile(indexPath)
60-
})
57+
fastify.setNotFoundHandler(
58+
{},
59+
function (req: FastifyRequest, reply: FastifyReply) {
60+
const requestedExtension = path.extname(req.url)
61+
// If it's requesting some sort of asset, e.g. .js or .jpg files
62+
// Html files should fallback to the index.html
63+
if (requestedExtension !== '' && requestedExtension !== '.html') {
64+
reply.code(404)
65+
return reply.send('Not Found')
66+
}
67+
68+
reply.header('Content-Type', 'text/html; charset=UTF-8')
69+
return reply.sendFile(indexPath)
70+
}
71+
)
6172

6273
return fastify
6374
}

0 commit comments

Comments
 (0)