When fetching data from external sources like a database or CMS, it can be beneficial to prevent re-fetching the same data if it has not changed by utilizing caching. This guide will explain how to use the Next.js App Router and the Vercel Data Cache to persist cached data across deployments.
To cache data and share responses across deployments, you must currently use the Next.js App Router (latest version recommended). You cannot share the cache between different projects.
The Next.js App Router (app/) provides more fine-grained control over fetching, caching, and revalidating your data. For example, you can fetch and cache data (using fetch or your favorite library) and revalidate the data by cache tag or path by defining a stale time or programmatically purging the cache.
The Vercel Data Cache is a specialized, granular cache for storing responses from fetches while using modern frontend frameworks like Next.js. It's a shared cache, meaning users of the same project share the same cache.
Frameworks that integrate with the Data Cache (currently Next.js) can cache data per fetch instead of per route. This means you can have static, dynamic, and revalidated data together in the same route.
Inside your Next.js application, fetch and tag your data with a cache key:
async function Blog() { const res = await fetch('https://api.vercel.app/blog', { next: { tags: ['blogs'] } }); const blogs = await res.json(); return '...';}The response from fetch will be cached and not re-fetched on the next deployment. Instead, to revalidate the data and purge the cache, you can use revalidateTag:
'use server' import { revalidateTag } from 'next/cache' export default async function action() { revalidateTag('blogs')}