Server Side Rendering with Netlify Functions

The guys from Zeit call it serverless pre-rendering although we’ve already been doing this for years for our clients with KeyCDN. Most CDN’s support the state-while-revalidate directive as far as I know.

The mechanism is simple:

  • The first time a URL is visited, the CDN requests the static HTML to the serverless function, serves the file and saves it in disk/memory for later use. This is the normal behaviour of any CDN, of course.
  • The second time a URL is visited, CDN serves the static file. Still normal.
  • The change is here: once the file is stale (controlled by the s-maxage directive), if the state-while-revalidate directive is used, the CDN returns the stale static HTML file to the user. After that, it requests a fresh one in the background to the serverless function. It then overwrites the stale one in its disk/memory.
  • The next user who visits the site gets the fresh static file from the CDN.

The time-to-stale is controlled by s-maxage directive and it can be 1 second (always check for a fresh file in the background) or any other time, for example 15 minutes. That obviously depends on the site needs. It can be further optimized setting s-maxage to the max and using manual cache invalidation, usually with a soft-purge hook of the CDN API that marks all the files as stale.

As you can see, the approach is similar to the static-generated site, but it has some benefits for medium/large publisher sites with thousands/tens of thousands posts: the static HTML files are generated on demand and over time. The static HTML files most used are generated first and served instantly, while the rest of the static HTML files are generated over time, if ever. And the final user always gets static files from the CDN (but the very first time).

It’d be amazing to be able to use this approach with Netlify :slight_smile:

4 Likes