Setting static asset cache TTL in SvelteKit

Viewed 1379

I am serving font and CSS files from /static using the default SvelteKit application template. I am using SvelteKit Node.js adapter.

The default cache time-to-live (TTL) seems to be 4 hours for /static files. I am not sure if this is set by SvelteKit/Vite itself or does any of the middleboxes like CloudFlare make this assumption.

How can I override this in SvelteKit? I assume this needs to be configured in Vite somehow, so that the /static files are server with correct HTTP caching headers. As the font files do not change, I would like to set them to be immutable and avoid the user web browser redownloading the files again.

enter image description here

2 Answers

The header settings are hardcoded in @sveltejs/adapter-node.

However, the latest @sveltejs/adapter-node@next version contains cache immutability header with cache-control.

/tmp # wget -S "http://localhost:3000/fonts.css"

--2021-12-31 00:35:00--  http://localhost:3000/fonts.css
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Vary: Accept-Encoding
  Content-Length: 2249
  Content-Type: text/css
  Last-Modified: Thu, 30 Dec 2021 23:34:41 GMT
  ETag: W/"2249-1640907281407"
  Cache-Control: public,max-age=31536000,immutable
  Date: Thu, 30 Dec 2021 23:35:00 GMT
  Connection: keep-alive
  Keep-Alive: timeout=5
Length: 2249 (2.2K) [text/css]

for those who also came here looking for this you can set the maxage:

<script context="module">
    export async function load({ params, fetch }) {
    //...
        return {
            maxage: 60 // 1 minute
        };
    }
</script>

https://kit.svelte.dev/docs#loading-output-maxage

i am not sure if this works for prerendered pages, probably not.

Related