When Remix went open source I was pretty excited to try it out, mostly because it labelled itself as a framework that embraces web fundamentals. I was using Nextjs at the time and was pretty happy with it.
Remix first impressions #
On the first try, I liked features like form support web way and nested routes. It felt like a better version of already good nextjs(like C++ is to C). One missing feature bugging me was SSG(Static site Generation). Nextjs has great support of SSG and I always tried to do SSG whenever possible. Remix does not support SSG and it annoyed me a bit.
What is SSG and why is it popular #
SSG stands for Static Site Generation and in this approach, data is fetched on build time and stored as HTML. So when the user requests for a page then generated HTML is returned, saving time to request data on runtime.
In the last few years, plenty of SSG frameworks like Jekyll, Hugo, Gatsby, 11ty and Nextjs have become popular. Nextjs is my favourite because it supports both SSG and SSR(Server Side Rendering) as I feel this hybrid approach works best for most of my work.
How to achieve SSG like performance with Remix #
Remix does not support SSG by default, but we can achieve almost similar performance.
How do you ask?
And the answer is (as in most cases)
We can set stale-while-revalidate
Cache-Control
header if a CDN is being used.
In remix you can do so by adding the following code to the route.
export function headers() {
return {
"cache-control": "max-age=604800, stale-while-revalidate=86400"
}
}
- First request: This is a cache miss scenario. So data fetching need to be done on request performance is similar to SSR
- Subsequent requests for 1 day(86400s): All the requests will be served from CDN cache and performance is similar to SSG
- First request after 1 day and till 7th(604800s): Till 7th-day response will be considered fresh. So a stale response from the previous day is served and parallelly cache is refreshed in the background. So here also performance is similar to SSG
- Subsequent requests for day 2: Because cache was refreshed in prev step, now updated response is served from cache. So here also performance is like SSG
Additional points #
- HTTP caching is not specific to Remix. This approach can be used in Nextjs, Nuxt or any framework which do SSR
- This approach gets around some of SSG quirks like SSG does not support query parameters. So that might be limiting in some cases. Cache-Headers respects query parameters we can still have SSG like performance while supporting query params.
Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated ! For feedback, please ping me on Twitter.
Published