Skip to content

Commit 4bb8b33

Browse files
dac09jtoar
authored andcommitted
fix(fastify): Dont fallback to index html if requesting static assets (#9272)
Attempts to fix an issue we found on teamstream with @KrisCoulson **The summary:** if you are requesting an asset (e.g. .js, jpeg, ico) file - we should _not_ respond with the index html. The response is meant to be for any routes that haven't been prerendered, and is an SPA fallback (so client side routing takes over). Because the 200 response here can get cached (intheory 200 means, all ok, so cloudflare or CDN would be correct to cache it), it can lead to problems where trying to load dynamically loaded chunks causes fatal errors. The change in this PR just throws a 404, when a .js file is being requested and it doesn't exist - mainly to prevent caching.
1 parent 359f4bc commit 4bb8b33

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

packages/fastify/src/web.ts

+16-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import fg from 'fast-glob'
66
import type {
77
FastifyInstance,
88
FastifyReply,
9+
FastifyRequest,
910
HookHandlerDoneFunction,
1011
} from 'fastify'
1112

@@ -47,10 +48,21 @@ export async function redwoodFastifyWeb(
4748
const indexPath = getFallbackIndexPath()
4849

4950
// For SPA routing, fallback on unmatched routes and let client-side routing take over.
50-
fastify.setNotFoundHandler({}, function (_, reply: FastifyReply) {
51-
reply.header('Content-Type', 'text/html; charset=UTF-8')
52-
reply.sendFile(indexPath)
53-
})
51+
fastify.setNotFoundHandler(
52+
{},
53+
function (req: FastifyRequest, reply: FastifyReply) {
54+
const requestedExtension = path.extname(req.url)
55+
// If it's requesting some sort of asset, e.g. .js or .jpg files
56+
// Html files should fallback to the index.html
57+
if (requestedExtension !== '' && requestedExtension !== '.html') {
58+
reply.code(404)
59+
return reply.send('Not Found')
60+
}
61+
62+
reply.header('Content-Type', 'text/html; charset=UTF-8')
63+
return reply.sendFile(indexPath)
64+
}
65+
)
5466

5567
done()
5668
}

0 commit comments

Comments
 (0)