In Next.js, managing cached pages is an essential aspect of ensuring that users receive the most up-to-date content. Caching can occur at various levels, including server-side, client-side, and even at the CDN level. Understanding how to clear cached pages effectively can help maintain the integrity of your application and improve user experience.
Next.js provides several strategies to handle caching, especially when it comes to static generation and server-side rendering. Here, we will explore practical examples, best practices, and common mistakes associated with clearing cached pages in Next.js.
Next.js employs different caching mechanisms depending on how pages are generated:
For static pages, the most common approach to clear the cache is to trigger a rebuild of your application. This can be done by:
revalidate option in getStaticProps to specify a revalidation time.
export async function getStaticProps() {
const data = await fetchData();
return {
props: { data },
revalidate: 10, // Revalidate every 10 seconds
};
}
For server-side rendered pages, you can control caching using HTTP headers. To prevent caching, you can set the following headers in your API responses:
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
When using libraries like SWR or React Query, you can invalidate the cache programmatically. For example, in SWR, you can use the mutate function:
import useSWR, { mutate } from 'swr';
function fetcher(url) {
return fetch(url).then(res => res.json());
}
const { data } = useSWR('/api/data', fetcher);
// To clear the cache
mutate('/api/data');
By understanding these caching mechanisms and employing best practices, you can effectively manage cached pages in Next.js and ensure a smooth user experience.