javascript / intermediate
Snippet
Fine-grained Caching with unstable_cache
The 'unstable_cache' utility in Next.js App Router allows you to cache the results of expensive operations (like database queries) manually. It provides tag-based invalidation and time-based revalidation outside of the standard 'fetch' API.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { unstable_cache } from 'next/cache';export const getCachedUserData = unstable_cache(async (userId: string) => {const user = await db.user.findUnique({ where: { id: userId } });return user;},['user-profile'],{ tags: ['users'], revalidate: 3600 });
nextjs
Breakdown
1
unstable_cache(async (...) => { ... })
Wraps an asynchronous function to enable caching of its return value.
2
['user-profile']
The cache key used to identify this specific cached result.
3
{ tags: ['users'], revalidate: 3600 }
Configures tags for manual purging and a TTL of one hour.