'unstable_cache' in Next.js for Efficient Data Fetching
Hafiz Muhammad Ahmed
AI Engineer | Build AI Agents and Workflow Automations using (n8n | LangGraph | Crew AI) | Pursuing MSc in AI | Develop AI Applications using (Next.js | FastAPI)
unstable_cache is perfect for scenarios where the data doesn’t change frequently but is still essential for user experience, like a user's profile information, user credits, or specific settings. With unstable_cache, you can cache the result of a function that fetches such data and only revalidate or refresh it based on a specified time period or custom conditions.
I recently worked on my side SaaS project, where users are allocated a certain number of credits (or coins) when they sign up. These credits are used to access AI services, and once they run out, users need to purchase more credits. However, since this transaction doesn’t change frequently coins are only updated when a user spends or buys more fetching the data on every request would be inefficient.
Solution
Next.js’ unstable_cache fits this scenario perfectly. It allows me to cache the result of the query that fetches the user's coin balance and revalidate it only when necessary. Additionally, it gives the flexibility to set a revalidation time or use custom tags to control when the cache should refresh.
Here’s how I implemented it:
领英推è
import { unstable_cache } from "next/cache";
import prisma from "@/lib/db.config";
// Fetch user coin balance and cache the result
export const getUserCoins = unstable_cache(
async (userId: string) => {
return await prisma.user.findUnique({
select: {
coins: true,
},
where: {
id: userId,
},
});
},
["userCoins"], // Custom tags to trigger cache invalidation
{ revalidate: 60 * 60, tags: ["userCoins"] } // Cache expires after 1 hour
);
- The Database Query: The query fetches the current coin balance of the user from the user table using Prisma ORM.
- unstable_cache: Wraps the query inside the unstable_cache function. This caches the result and reuses it across multiple requests.
- Custom Tags: I've added a custom tag ["userCoins"] which allows the cache to revalidate or refresh only when necessary.
- Revalidation Time: I set the revalidation time to one hour (60 * 60 seconds). After this time, the function will refetch the user's coin balance to ensure up-to-date information.
For my project, the coin balance is something that only changes when the user interacts with the system by purchasing or spending coins, so it’s a perfect candidate for caching with unstable_cache.
My Thoughts
Next.js unstable_cache is a powerful feature that can drastically improve the performance of your application when used appropriately. In cases like mine, where data doesn’t change often, caching can reduce the number of database queries and significantly speed up the user experience. The flexibility to set custom revalidation times and use tags for invalidation makes it a highly effective tool for optimizing server-side data fetching.
Next time you're working on a project with data that doesn't need to be fetched frequently, give unstable_cache a try it might just save you some server time!