using `not_found_handling = "single-page-application"` and a worker script together?

I'm trying to deploy an SPA using workers assets (https://developers.cloudflare.com/workers/static-assets/get-started/#deploy-a-full-stack-application) but I'd also like to be able to 'fall back' to the worker script if the SPA's routing logic rejects the request. Currently if I have something like
main = "src/index.ts"
[assets]
binding = "ASSETS"
directory = "./public"
not_found_handling = "single-page-application"
main = "src/index.ts"
[assets]
binding = "ASSETS"
directory = "./public"
not_found_handling = "single-page-application"
in my wrangler.toml file, and if I make a request to http://localhost:8787/foo/bar it gets routed to the worker at src/index.ts I would expect this request be handled by public/index.html instead, where I could then decide if I want to route the request to the worker or render content based on the URL Is this possible? Thanks!
4 Replies
texan
texan11h ago
not_found_handling will only be evaluated if there’s no worker script (see point 2): https://developers.cloudflare.com/workers/static-assets/routing/#default-behavior
Cloudflare Docs
Routing · Cloudflare Workers docs
How Workers assets' routing and its configuration works.
Hello, I’m Allie!
For clarity, imagine how this would work. I, a new visitor, browse to http://localhost:8787/foo/bar. I am served your SPA, as it runs on the clientside. The SPA code somehow decides to fall back to the Worker. What signal could it send to the Worker that it actually wants your code to handle the request? Any path that isn't occupied by static assets would return your SPA. You might be able to handle this by having a single endpoint(/worker, for example) that actually does handle the request, but at that is more an implementation detail on your end. The SPA setting within your Wrangler config is for the simple case, where you don't need a Worker at all
johnrees
johnreesOP5h ago
oops.. my bad! thanks for pointing it out makes sense thanks for explaining! I love the idea of having all my frontend and backend (worker+DO+D1+queues) in a single worker repo for ease of development and e2e testing. My naive idea was to have some way of forwarding all fetch() requests to the worker script and everything else to be handled by an SPA router. I'll mess around with some other approaches, cheers
texan
texan5h ago
You could check out ‘experimental_serve_directly’ and see if you have a solution there. You’d basically invoke your user worker for every request and then use the assets binding to attempt to fetch your static assets. Downside to this is a user invocation for every request, but you’d have full control

Did you find this page helpful?