Skip to content

Commit

Permalink
fix(fastify): Dont fallback to index html if requesting static assets (
Browse files Browse the repository at this point in the history
…#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.
  • Loading branch information
dac09 authored and jtoar committed Oct 28, 2023
1 parent de4139c commit e5f5ddd
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions packages/fastify/src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fg from 'fast-glob'
import type {
FastifyInstance,
FastifyReply,
FastifyRequest,
HookHandlerDoneFunction,
} from 'fastify'

Expand Down Expand Up @@ -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()
}
Expand Down

0 comments on commit e5f5ddd

Please sign in to comment.