How to set up Caddy Fallback for Sveltekit Static Adapter

If you use the Sveltekit Static adapter, and you have a single page application (such as the very Console I’m writing this article on), you will have the following set up in your pages.

+layout.ts

1export const ssr = false;

svelte.config.js

1import adapter from '@sveltejs/adapter-static';
2
3export default {
4 kit: {
5 adapter: adapter({
6 fallback: '200.html' // may differ from host to host
7 })
8 }
9};

See the SvelteKit Single Page Apps docs for more information.

With this set up, when you build your app, non-ssr routes will be Javascript-rendered. The JS will be loaded from the 200.html file.

For example, in our case, Hyvor Blogs’ build folder looks something like this:

1/build
2 200.html
3 index.html
4 pricing.html
5 ...

The static files are index.html and pricing.html. All other routes should be routed to 200.html.

Caddy Fallback

Here’s the caddy configuration I used to make the fallback route work along with static files.

1:9091 {
2 handle {
3 file_server {
4 pass_thru
5 }
6 encode zstd gzip
7 try_files {path} {path}.html
8 }
9 handle {
10 file_server
11 rewrite * /200.html
12 }
13}
  • :9091 is the port. This will be different for you.

  • The first handle block handles the the normal file server. Here, the pass_thru directive is important. It instructs Caddy to go into the next block without returning a 404 error.

  • The next block will route everything to the 200.html file.

References

Newsletter

Comments

Published with Hyvor Blogs