0 day streak
javascript / expert
Snippet

Granular Cache Invalidation with Tagged Data Fetching

Leverage Next.js unstable_cache to wrap expensive asynchronous operations (like DB queries) with a unique key and revalidation tags. This allows for surgical invalidation of specific cache entries using revalidateTag without clearing the entire cache.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { unstable_cache } from 'next/cache';
export const getCachedData = (userId) =>
unstable_cache(
async () => fetchUserStats(userId),
['user-stats', userId],
{
tags: [`user-${userId}`, 'global-stats'],
revalidate: 3600
}
)();
nextjs
Breakdown
1
unstable_cache(...)
Wraps the data-fetching function in a memoized layer.
2
['user-stats', userId]
The unique key used to identify this specific cache entry.
3
tags: [...]
Custom identifiers used for on-demand invalidation via revalidateTag.