Vojtěch Struhár

Posted on February 14, 2024 | #web

Force Next.js page render dynamically

Next.js has a somewhat confusing notion of caching requests. They say you can supply a caching interval to fetch function like so:

fetch('https://...', { next: { revalidate: 3600 } })

But I don’t use the fetch function directly. I use Sanity CMS which provides a client for interacting with their service. I’m sure it calls fetch somewhere inside, but I can’t really get to it.

Also from version 13 you can mysteriously export some variables…

export const revalidate = 3600 // revalidate at most every hour

But that didn’t work for me either. I’m starting to think it’s me 😂

Solution

I found the solution to my problem in Next’s learning materials.

import { unstable_noStore as noStore } from 'next/cache'; 

// Add noStore() here to prevent the response from being cached.
export async function fetchGallery() { 
 noStore();
 // ...
}

I put this in my gallery component - I want it to shuffle on every render and show different pictures each time. This did it. Every page where this component appears is now a dynamic page.

Client component pitfall

Declaring the component as "use client"; and shuffling the photos when it appeared broke everything. It causes the hydration to fail, because the page is obviously not the same as on server. Sigh.

Read next → Don't break words along hyphens