The hidden magic of Incremental Static Regeneration with Next.js
This week I launched whatcdkisit.com – a little website I’ve built to learn Next.js. There are multiple flavors of the AWS CDK and it’s sometimes hard to keep track of them all. What CDK is it? always tells you the current versions of the most popular CDK projects. You can find the source code on GitHub.
In this post, I want to highlight a particular feature of Next.js that I found tremendously helpful. I would go so far as to call it one of the most developer-friendly applications of AWS Lambda I know.
At its core, whatcdkisit.com is a static website that gets updated periodically using information from GitHub’s REST API. It’s static because static means fast. It also means not having to worry about API rate limits as the data is only queried when building the site, not every time someone opens it in a browser (or worse, uses a command-line tool that couldn’t care less about caching).
So far, so good. But how would you implement the regeneration process? One low-tech way to do it is to set up a CI job that builds and deploys the site once a day or so. You could do that pretty easily with GitHub Actions pushing to GitHub Pages, for example. In fact, it’s precisely how whatrustisit.com tracks new releases of the Rust programming language, which undoubtedly served as an inspiration to me. However, I knew there must be a better way with Next.js.
Enter Incremental Static Regeneration, or ISR for short:
Next.js allows you to create or update static pages after you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, without needing to rebuild the entire site. With ISR, you can retain the benefits of static while scaling to millions of pages.
The documentation goes into more detail, but here’s the gist of it:
-
If you export an async function called
getStaticProps
from a page, Next.js will pre-render this page at build time using the data returned bygetStaticProps
. What CDK is it? uses this function to gather release information like tag name and publish date from a couple of GitHub repositories. -
By specifying the optional
revalidate
interval – I set it to 600 seconds – Next.js will callgetStaticProps
periodically at run time to regenerate the page in the background. This all happens “on a serverless function”, which very likely means Lambda if you happen to deploy to Vercel as I do.
So that’s the short but somewhat magical story of how whatcdkisit.com is updated every 10 minutes while still being a static website. The major benefits are the things I didn’t have to do. I didn’t have to create a CI/cron job. I didn’t have to touch a single server – or Lambda, for that matter. To me, ISR is as close to our serverless ideal of “only write business logic” as it gets.