solid-start icon indicating copy to clipboard operation
solid-start copied to clipboard

Add cache control header for immutable static assets

Open patdx opened this issue 2 years ago • 1 comments

Files in the /assets dir get a content hash from Vite/Rollup by default. Because they have a content hash, the deploy adapters can give these files a Cache-Control header of public, immutable, max-age=31536000 which will allow browsers to cache the files without needing to ping the server again.

This can speed up repeating loadings of the site deployment and also cut down on HTTP requests, which could help stretch the free quota or reduce costs for various serverless site providers.

I would like to have this feature in the Cloudflare Workers adapter, which I am currently using, so I tested this feature out there first.

But I figure it would be good to have in all the adapters so I tried to adjust all them. However, I have not fully tested them yet. If you have a chance, could you please take a look and let me know if I am on the right track with this PR?

Also, if I understood correctly, the Node.js adapter is currently giving an "immutable" cache header to all files in the public folder. This is not ideal, because there may be files in this folder that do not have a content hash and may occasionally update, such as favicon.ico, Web app manifest of PWAs, apple-touch-icon.png, etc. I updated the code to only use the immutable cache header for files in the /public/assets/ folder.

Reference:

  • Next.js documentation: https://nextjs.org/docs/going-to-production#caching
  • Sveltekit adapters, eg: https://github.com/sveltejs/kit/blob/b4c268091b246befb1cb028875781285c9ff4aa5/packages/adapter-cloudflare/index.js#L98

Future considerations:

  • I think the adapters should support a customizable build.assetsDir and base url instead of hardcoding /assets/, but this is more complicated, we would need to pass these settings on to the adapters, perhaps via a generated manifest file.

patdx avatar Oct 13 '22 05:10 patdx

I tested

  • cloudflare workers
  • cloudflare pages
  • deno
  • netlify
  • netlify edge
  • node
  • vercel
  • vercel edge

They seemed to work as expected with the exception of Netlify; I could not get the deploy to work. It seemed to be uploading the wrong directories. Is the Netlify adapter known to be broken or should I try to do some debugging here?

In the meantime I will change to non draft status. It would be great if this could be merged sometime soon, so I can use of immutable header in a Cloudflare workers based project. Thanks!

patdx avatar Oct 14 '22 03:10 patdx

Interesting I haven't seen Netlify issue (we've been using netlify to deploy most recent projects)

ryansolid avatar Oct 16 '22 06:10 ryansolid

Thank you

ryansolid avatar Oct 16 '22 06:10 ryansolid