Revalidation and ISR gotcha on Vercel
FULL-STACK WEB DEVELOPMENT BOOTCAMP
2024 COHORT SIGNUPS END TOMORROW
I was kind of surprised by something, so I’m writing a post on it.
First time testing ISR, which is a very cool functionality offered by Next.js.
Basically we can have a site the is statically generated at build time, so we have all the data fetched initially and then Next.js serves the cached version.
But can also tell a Next.js page that it should revalidate every n seconds.
So we can set (Next.js 13 app folder):
export const revalidate = 30
and the page is revalidated every 30 seconds.
The page is served as-is super fast to the first person that hits the URL later than 30 seconds after the last revalidation (someone needs to hit the URL before revalidation happens, it’s not a cron job), but in the background it’s built again, with any data fetching that needs to happen.
It’s pretty cool.
One gotcha is that on Vercel the revalidation process runs in a serverless function.
This made me spend several hours on what I believed was a bug (the new app folder is still beta, so it could happen), but either I didn’t read the right docs or it’s not documented well.
The revalidation serverless function runs in a different environment than the first build.
The first build can write to the filesystem. The revalidation serverless function can’t. It can write to the system tmp folder which you get using
import os from 'os' first) but there’s no “communication” with the other build.
I was downloading some images to make them part of the site, but that workflow was not possible.
Also, we can’t access the previous files downloaded in the original build, because we can’t see them, we’re in a brand new environment.
Something that might be common knowledge in a serverless function environment but got me by surprise.
Anyway, once you know that, you know the limitations and can find workarounds.
For example I could host assets on S3, or as I eventually did for a quick workaround, encode small images as data URIs.
Oh, a tip: to debug revalidation I used on-demand revalidation, which is super cool.
So I was able to hit an API endpoint to revalidate a specific page route without having to wait for the revalidation time.
One gotcha using on-demand revalidation was that I enabled revalidation on a route that didn’t fetch data, was static (because I was stripping away all the data fetching I was doing to “get to the problem”), and when I tried using ODR I hit this issue, which apparently says that revalidation could not be done because there’s no data to revalidate. Basically it’s marked as server error but it’s not. Could be something that gets fixed in later updated, keep in mind the date of this post.