### Cache the featured fetch with "use cache" Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/instant-navigation.mdx Add a "use cache" directive to the fetching function to cache the featured fetch at the fetch level. The featured list then ships with the App Shell. In serverless deployments, in-memory caching with "use cache" will not persist across instances; consider "use cache: remote" for persistent caching. ```tsx async function getFeatured() { 'use cache' const res = await fetch('https://next-recipe-api.vercel.dev/products?limit=3') return res.json() } ``` -------------------------------- ### Cache random value with 'use cache' directive Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Use the 'use cache' directive to cache the result so all users see the same value until revalidation. This is an alternative to generating a unique value per request. ```tsx export default async function Page() { 'use cache' const buildId = crypto.randomUUID() return

Build ID: {buildId}

} ``` -------------------------------- ### Caching a component's output with use cache Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Use 'use cache' at the component level to cache any fetches or computations performed within that component. The cache entry is reused as long as the serialized props produce the same value in each instance. ```tsx export async function Bookings({ type = 'haircut' }: BookingsProps) { 'use cache' async function getBookingsData() { const response = await fetch( `https://api.example.com/bookings?type=${encodeURIComponent(type)}` ) const data = await response.json() return data } return //... } interface BookingsProps { type: string } ``` ```jsx export async function Bookings({ type = 'haircut' }) { 'use cache' async function getBookingsData() { const response = await fetch( `https://api.example.com/bookings?type=${encodeURIComponent(type)}` ) const data = await response.json() return data } return //... } ``` -------------------------------- ### After: cache lookup behind session value with 'use cache' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/adopting-partial-prefetching.mdx After refactoring, the session value is read outside the cached function and passed in, and the lookup is cached with 'use cache'. Use this to cache session-dependent content while keeping it fresh per session. ```tsx // After - the lookup is cached behind the session value import { Suspense } from 'react' import { cookies } from 'next/headers' async function getTopics(team: string | undefined) { 'use cache' return db.topics.forTeam(team) } async function TeamTopics() { const team = (await cookies()).get('team')?.value return } export default function Page() { return ( }> ) } ``` ```jsx // After - the lookup is cached behind the session value import { Suspense } from 'react' import { cookies } from 'next/headers' async function getTopics(team) { 'use cache' return db.topics.forTeam(team) } async function TeamTopics() { const team = (await cookies()).get('team')?.value return } export default function Page() { return ( }> ) } ``` -------------------------------- ### Setting cache lifetime with next.revalidate Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/fetch.mdx Specifies the cache lifetime of a resource in seconds. Pass false to cache indefinitely, 0 to prevent caching, or a number for the maximum cache lifetime in seconds. ```ts fetch(`https://...`, { next: { revalidate: false | 0 | number } }) ``` -------------------------------- ### Cache an entire page component with use cache and cacheLife Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Add the 'use cache' directive at the top of a component or page body to cache the entire UI. Pair with cacheLife to set the cache lifetime; without it, the default profile applies. ```tsx import { cacheLife } from 'next/cache' export default async function Page() { 'use cache' cacheLife('hours') const users = await db.query('SELECT * FROM users') return ( ) } ``` -------------------------------- ### Cache an async data function with use cache and cacheLife Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Add the 'use cache' directive at the top of an async function to cache its return value. Pair with cacheLife to set the cache lifetime; without it, the default profile applies. ```tsx import { cacheLife } from 'next/cache' export async function getUsers() { 'use cache' cacheLife('hours') return db.query('SELECT * FROM users') } ``` -------------------------------- ### Cache all fetch requests with fetchCache = 'default-cache' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-15.mdx Use the fetchCache segment config option to cache all fetch requests in a layout or page. Individual requests that specify their own cache option, such as cache: 'no-store', override this default. ```js // Since this is the root layout, all fetch requests in the app // that don't set their own cache option will be cached. export const fetchCache = 'default-cache' export default async function RootLayout() { const a = await fetch('https://...') // Cached const b = await fetch('https://...', { cache: 'no-store' }) // Not cached // ... } ``` -------------------------------- ### Opt individual fetch requests into caching with cache: 'force-cache' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/upgrading/version-15.mdx fetch requests are no longer cached by default in Next.js 15. Pass cache: 'force-cache' on a specific request to cache it, while requests without the option remain uncached. ```js export default async function RootLayout() { const a = await fetch('https://...') // Not Cached const b = await fetch('https://...', { cache: 'force-cache' }) // Cached // ... } ``` -------------------------------- ### Search page with cached results using 'use cache' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/adopting-partial-prefetching.mdx Search page that caches results with 'use cache' so they can be prefetched behind the resolved searchParams. Use to make URL-dependent content resolvable at prefetch time. ```tsx // After - the results are cached and prefetched behind the resolved searchParams import { Suspense } from 'react' async function getResults(query: string) { 'use cache' const res = await fetch(`https://api.example.com/search?q=${query}`) return res.json() } async function Results({ searchParams, }: Pick, 'searchParams'>) { const { q } = await searchParams return } export default function Page({ searchParams }: PageProps<'/search'>) { return ( }> ) } ``` ```jsx // After - the results are cached and prefetched behind the resolved searchParams import { Suspense } from 'react' async function getResults(query) { 'use cache' const res = await fetch(`https://api.example.com/search?q=${query}`) return res.json() } async function Results({ searchParams }) { const { q } = await searchParams return } export default function Page({ searchParams }) { return ( }> ) } ``` -------------------------------- ### Cache uncached content with use cache and remove prefetch={true} Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/adopting-partial-prefetching.mdx For uncached content, cache it with use cache so it gets included in the App Shell, then remove prefetch={true} from the links. The App Shell carries cached content whose stale time is at least 5 minutes, which holds for the default profile and every preset except seconds. ```tsx // Before export default async function Page() { const res = await fetch('https://api.example.com/products') return } ``` ```jsx // Before export default async function Page() { const res = await fetch('https://api.example.com/products') return } ``` ```tsx // After - cached, so the App Shell carries it async function getProducts() { 'use cache' const res = await fetch('https://api.example.com/products') return res.json() } export default async function Page() { return } ``` ```jsx // After - cached, so the App Shell carries it async function getProducts() { 'use cache' const res = await fetch('https://api.example.com/products') return res.json() } export default async function Page() { return } ``` -------------------------------- ### Caching function output with use cache Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Add 'use cache' to any asynchronous function to cache its output, such as a network request, database query, or slow computation. The directive must be placed at the top of the function body. ```tsx export async function getData() { 'use cache' const res = await fetch('https://api.example.com/data') const data = await res.json() return data } ``` ```jsx export async function getData() { 'use cache' const res = await fetch('https://api.example.com/data') const data = await res.json() return data } ``` -------------------------------- ### Cache output with cacheLife and nested caching Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Demonstrates cache output storage with cacheLife('hours') and nested caching. getOrderTotals is not cached and is exported for fresh reads; getOrders has its own entry keyed by accountId. ```tsx import { cacheLife } from 'next/cache' export async function getOrderSummary(accountId: string) { 'use cache' cacheLife('hours') const orders = await getOrders(accountId) const totals = await getOrderTotals(accountId) return { orders, totals } } export async function getOrders(accountId: string) { 'use cache' cacheLife('hours') return db.orders.findMany({ where: { accountId } }) } export async function getOrderTotals(accountId: string) { return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } }) } ``` -------------------------------- ### Cache a route segment's layout with `use cache` Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Add `use cache` to a layout file to cache the route segment's output. The layout must be async. ```tsx 'use cache' export default async function Layout({ children }: { children: ReactNode }) { return
{children}
} ``` ```jsx 'use cache' export default async function Layout({ children }) { return
{children}
} ``` -------------------------------- ### Cache a route segment's page with `use cache` Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Add `use cache` to a page file to cache the route segment's output. The page must be async. ```tsx 'use cache' async function Users() { const res = await fetch('https://api.example.com/users') const users = await res.json() // loop through users } export default async function Page() { return (
) } ``` ```jsx 'use cache' async function Users() { const res = await fetch('https://api.example.com/users') const users = await res.json() // loop through users } export default async function Page() { return (
) } ``` -------------------------------- ### Optimize remote cache keys with category caching in app/products/[category]/page.tsx Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache-remote.mdx Cache remotely based on low-cardinality dimensions like category rather than high-cardinality search filters. Filter additional parameters such as minPrice in memory to maximize cache hit rates. ```tsx import { Suspense } from 'react' export default async function ProductsPage({ params, searchParams, }: { params: Promise<{ category: string }> searchParams: Promise<{ minPrice?: string }> }) { return ( Loading...}> ) } async function ProductList({ params, searchParams, }: { params: Promise<{ category: string }> searchParams: Promise<{ minPrice?: string }> }) { const { category } = await params const { minPrice } = await searchParams // Cache only on category (few unique values) // Don't include price filter (many unique values) const products = await getProductsByCategory(category) // Filter price in memory instead of creating cache entries // for every price value const filtered = minPrice ? products.filter((p) => p.price >= parseFloat(minPrice)) : products return
{/* render filtered products */}
} async function getProductsByCategory(category: string) { 'use cache: remote' // Only category is part of the cache key // Much better utilization than caching every price filter value return db.products.findByCategory(category) } ``` -------------------------------- ### Configuring cache option in fetch Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/fetch.mdx Configures how a server-side fetch request interacts with the persistent cache. Caching is opt-in; use 'force-cache' to cache the response or 'no-store' to fetch fresh on every request. ```ts fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) ``` -------------------------------- ### Cache API responses in streaming contexts with 'use cache: remote' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache-remote.mdx Cache external API responses fetched during streaming or after dynamic operations to minimize outbound network requests. Combine with Suspense fallbacks for progressive rendering. ```tsx import { Suspense } from 'react' import { connection } from 'next/server' import { cacheLife, cacheTag } from 'next/cache' export default async function FeedPage() { return (
}>
) } async function FeedItems() { // Defer to request time await connection() const items = await getFeedItems() return items.map((item) => ) } async function getFeedItems() { 'use cache: remote' cacheTag('feed-items') cacheLife({ expire: 120 }) // 2 minutes // This API call is cached, reducing requests to your external service const response = await fetch('https://api.example.com/feed') return response.json() } ``` -------------------------------- ### Cache a component with the 'use cache' directive Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/public-static-pages.mdx Use the 'use cache' directive inside an async component to cache its returned output. The first render caches the result, and if inputs are available before the request, the component can be prerendered as static. ```tsx import db from '@/db' import { List } from '@/app/products/ui' function Header() {} // Cache component async function ProductList() { 'use cache' const products = await db.product.findMany() return } export default async function Page() { return ( <>
) } ``` -------------------------------- ### Cache a module's exports with `use cache` Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Place `use cache` at the top of a module to cache all exported functions. Every exported function must be async. ```tsx 'use cache' export async function getMonthlyTotals(accountId: string) { return db.orders.aggregate({ where: { accountId }, _sum: { amount: true } }) } export async function getTopProducts() { return db.products.findMany({ orderBy: { sales: 'desc' }, take: 10 }) } ``` -------------------------------- ### Cache the component or data with "use cache" Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/instant-navigation.mdx Fix card snippet for caching a component or data to avoid blocking navigation. The "use cache" directive is highlighted. ```tsx async function Posts() { "use cache" return } ``` -------------------------------- ### Cache database queries with 'use cache' in lib/guides.ts Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/keeping-pages-static.mdx Add the 'use cache' directive to data-fetching functions to allow Next.js to reuse query results across visitors and keep the route static. ```ts import { db } from '@/lib/db' export async function getGuideIds() { const guides = await db.guide.findMany({ select: { id: true } }) return guides.map(({ id }) => id) } export async function getGuide(id: string) { 'use cache' return db.guide.findUniqueOrThrow({ where: { id } }) } ``` -------------------------------- ### Read cookies inside a cached function with 'use cache: private' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/optimizing-prefetching.mdx Use this pattern when the lookup is tied to a single session. `"use cache: private"` assigns a cache lifetime to a function that reads cookies directly, and results are cached in the browser only, scoped to that session. ```tsx import { cookies } from 'next/headers' async function UserNav() { const user = await getUser() return } async function getUser() { 'use cache: private' const session = (await cookies()).get('session')?.value return db.users.findBySession(session) } ``` -------------------------------- ### Cache pricing per user currency preference with 'use cache: remote' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache-remote.mdx Caches product prices by product ID and currency preference read from cookies at request time. Using remote caching allows all users with the same currency to share cache entries across serverless instances. ```tsx import { Suspense } from 'react' import { cookies } from 'next/headers' import { cacheTag, cacheLife } from 'next/cache' export async function generateStaticParams() { return [{ id: '1' }, { id: '2' }, { id: '3' }] } export default async function ProductPage({ params, }: { params: Promise<{ id: string }> }) { const { id } = await params return (
Loading price...
}> ) } function ProductDetails({ id }: { id: string }) { return
Product: {id}
} async function ProductPrice({ productId }: { productId: string }) { // Reading cookies defers this component to request time const currency = (await cookies()).get('currency')?.value ?? 'USD' // Cache the price per product and currency combination // All users with the same currency share this cache entry const price = await getProductPrice(productId, currency) return (
Price: {price} {currency}
) } async function getProductPrice(productId: string, currency: string) { 'use cache: remote' cacheTag(`product-price-${productId}`) cacheLife({ expire: 3600 }) // 1 hour // Cached per (productId, currency) - few currencies means high cache utilization return db.products.getPrice(productId, currency) } ``` ```jsx import { Suspense } from 'react' import { cookies } from 'next/headers' import { cacheTag, cacheLife } from 'next/cache' export async function generateStaticParams() { return [{ id: '1' }, { id: '2' }, { id: '3' }] } export default async function ProductPage({ params }) { const { id } = await params return (
Loading price...
}> ) } function ProductDetails({ id }) { return
Product: {id}
} async function ProductPrice({ productId }) { // Reading cookies defers this component to request time const currency = (await cookies()).get('currency')?.value ?? 'USD' // Cache the price per product and currency combination // All users with the same currency share this cache entry const price = await getProductPrice(productId, currency) return (
Price: {price} {currency}
) } async function getProductPrice(productId, currency) { 'use cache: remote' cacheTag(`product-price-${productId}`) cacheLife({ expire: 3600 }) // 1 hour // Cached per (productId, currency) - few currencies means high cache utilization return db.products.getPrice(productId, currency) } ``` -------------------------------- ### Cache a component with 'use cache' and cacheLife Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/optimizing-the-static-shell.mdx Before/after comparison of caching a component with 'use cache' and cacheLife('hours') so its result can render in the static shell. Use when a result can be reused across requests; connect cached reads to writes with on-demand revalidation if the data can change. ```tsx // Before: the query runs for every request export async function ProductList() { const products = await db.products.findMany() return } ``` ```tsx // After: the reusable result can render in the shell import { cacheLife } from 'next/cache' export async function ProductList() { 'use cache' cacheLife('hours') const products = await db.products.findMany() return } ``` -------------------------------- ### Cache data helpers with 'use cache' in app/lib/data.ts Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/incremental-static-regeneration-cache-components.mdx Data helpers use 'use cache' at the module level so all exported functions are cached, allowing their results to be included in the static shell. ```ts 'use cache' const API = 'https://next-recipe-api.vercel.dev' export async function getCategory(slug: string) { const res = await fetch(`${API}/categories/${slug}`) if (!res.ok) return null return res.json() } export async function getProduct(category: string, slug: string) { const res = await fetch(`${API}/products/${category}/${slug}`) if (!res.ok) return null return res.json() } export async function getTopCategories() { const res = await fetch(`${API}/categories`) const categories = await res.json() return categories.slice(0, 2) } export async function getPopularProducts(category: string) { const res = await fetch(`${API}/products?category=${category}`) const products = await res.json() return products.slice(0, 1) } ``` -------------------------------- ### Pass runtime values to cached functions Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Extract values from runtime APIs and pass them as arguments to cached functions. The extracted value becomes part of the cache key. ```tsx import { cookies } from 'next/headers' import { Suspense } from 'react' export default function Page() { return ( Loading...}> ) } // Component (not cached) reads runtime data async function ProfileContent() { const session = (await cookies()).get('session')?.value return } // Cached component receives extracted value as a prop async function CachedContent({ sessionId }: { sessionId: string }) { 'use cache' // sessionId becomes part of the cache key const data = await fetchUserData(sessionId) return
{data}
} ``` -------------------------------- ### Cache uncached data in a GET Route Handler with use cache and cacheLife Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/15-route-handlers.mdx With Cache Components enabled, cache uncached data such as a database query using `use cache` in a helper function so it can be included in the prerendered response. `use cache` cannot be used directly inside a Route Handler body; cached responses revalidate according to `cacheLife` when a new request arrives. ```tsx import { cacheLife } from 'next/cache' export async function GET() { const products = await getProducts() return Response.json(products) } async function getProducts() { 'use cache' cacheLife('hours') return await db.query('SELECT * FROM products') } ``` -------------------------------- ### Combine static, cached, and streaming dynamic content in a blog page Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Shows a single page mixing static header, cached blog posts via 'use cache' with cacheLife and cacheTag, and streaming user preferences from cookies wrapped in Suspense. During prerendering, the header and cached posts become part of the static shell, while cookie-dependent UI streams at request time. ```tsx import { Suspense } from 'react' import { cookies } from 'next/headers' import { cacheLife, cacheTag } from 'next/cache' import Link from 'next/link' export default function BlogPage() { return ( <> {/* Static content - prerendered automatically */}

Our Blog

{/* Cached dynamic content - included in the static shell */} {/* Runtime dynamic content - streams at request time */} Loading your preferences...

}>
) } type Post = { id: string; title: string; author: string; date: string } // Everyone sees the same blog posts (revalidated every hour) async function BlogPosts() { 'use cache' cacheLife('hours') cacheTag('posts') const res = await fetch('https://api.vercel.app/blog') const posts: Post[] = await res.json() return (

Latest Posts

    {posts.map((post) => (
  • {post.title}

    By {post.author} on {post.date}

  • ))}
) } // UI that depends on a value stored in cookies async function UserPreferences() { const theme = (await cookies()).get('theme')?.value || 'light' const favoriteCategory = (await cookies()).get('category')?.value return ( ) } ``` -------------------------------- ### cacheTag Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/09-revalidating.mdx Tags cached data so it can be invalidated on-demand. Use it inside a `use cache` scope to associate a tag with cached data, then invalidate the cache using `revalidateTag` or `updateTag`. ```APIDOC ## cacheTag ### Description `cacheTag` lets you tag cached data so it can be invalidated on-demand. Use it inside a `use cache` scope. ### Method Function ### Endpoint `cacheTag` ### Parameters - **tag** (string) - Required - The tag to associate with the cached data. ### Request Example ```tsx filename="app/lib/data.ts" switcher import { cacheTag } from 'next/cache' export async function getProducts() { 'use cache' cacheTag('products') return db.query('SELECT * FROM products') } ``` ```jsx filename="app/lib/data.js" switcher import { cacheTag } from 'next/cache' export async function getProducts() { 'use cache' cacheTag('products') return db.query('SELECT * FROM products') } ``` ``` ```APIDOC ## revalidateTag ### Description `revalidateTag` with the recommended `'max'` profile invalidates cache entries by tag using stale-while-revalidate semantics. Stale content is served immediately while fresh content loads in the background. This is ideal for content where a slight delay in updates is acceptable, like blog posts or product catalogs. ### Method Function ### Endpoint `revalidateTag` ### Parameters - **tag** (string) - Required - The tag to invalidate. - **profile** (string) - Optional - The profile to use. Recommended: `'max'` for stale-while-revalidate. ### Request Example ```tsx filename="app/lib/actions.ts" highlight={1,5} switcher import { revalidateTag } from 'next/cache' export async function updateUser(id: string) { // Mutate data revalidateTag('user', 'max') // Recommended: stale-while-revalidate } ``` ```jsx filename="app/lib/actions.js" highlight={1,5} switcher import { revalidateTag } from 'next/cache' export async function updateUser(id) { // Mutate data revalidateTag('user', 'max') // Recommended: stale-while-revalidate } ``` ``` -------------------------------- ### Cache computed data after dynamic checks with 'use cache: remote' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache-remote.mdx Cache expensive computations performed after runtime checks such as security validation or feature flags. The cached calculation is shared across authorized requests according to the configured expiration time. ```tsx import { connection } from 'next/server' import { cacheLife } from 'next/cache' export default async function ReportsPage() { // Defer to request time (for security check) await connection() const report = await generateReport() return } async function generateReport() { 'use cache: remote' cacheLife({ expire: 3600 }) // 1 hour // This expensive computation is cached and shared across all authorized users, // avoiding repeated calculations const data = await db.transactions.findMany() return { totalRevenue: calculateRevenue(data), topProducts: analyzeProducts(data), trends: calculateTrends(data), } } ``` -------------------------------- ### Cache metadata with 'use cache' in generateMetadata Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/generate-metadata.mdx Use when metadata depends on external data but not runtime data. The 'use cache' directive caches the metadata query so it can be prerendered. ```tsx export async function generateMetadata() { 'use cache' const { title, description } = await db.query('site-metadata') return { title, description } } ``` -------------------------------- ### Cache fetch requests with force-cache Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/caching-without-cache-components.mdx Cache individual fetch requests by configuring the cache option to 'force-cache'. Use this in async server components or route handlers when fetch requests are not cached by default. ```tsx export default async function Page() { const data = await fetch('https://...', { cache: 'force-cache' }) } ``` ```jsx export default async function Page() { const data = await fetch('https://...', { cache: 'force-cache' }) } ``` -------------------------------- ### Read and cache current user with 'use cache: private' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/authentication-with-cache-components.mdx Reads session data from cookies in lib/session.ts and uses 'use cache: private' in lib/auth.ts to cache the user result in the browser. Throws redirect() calls when unauthenticated without caching the redirection. ```tsx import 'server-only' import { cookies } from 'next/headers' import { sealData, unsealData } from 'iron-session' export type SessionData = { userId?: string } const COOKIE_NAME = 'app_session' const password = process.env.SESSION_PASSWORD! export async function getSession(): Promise { const cookie = (await cookies()).get(COOKIE_NAME)?.value if (!cookie) { return {} } return unsealData(cookie, { password }) } ``` ```tsx import 'server-only' import { redirect } from 'next/navigation' import { getSession } from './session' import { findUserById } from './data' export type User = { id: string name: string } export async function getCurrentUser(): Promise { 'use cache: private' const { userId } = await getSession() if (!userId) { redirect('/login') } const user = await findUserById(userId) if (!user) { redirect('/login') } return { id: user.id, name: user.name } } ``` -------------------------------- ### Optimistically update client cache with useMutation in MarkReadButton component Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/client-side-data-fetching/tanstack-query.mdx Use onMutate to immediately update the client query cache and onError to restore previous cache data if the mutation fails. ```tsx 'use client' import { useMutation, useQueryClient } from '@tanstack/react-query' import { markActivityReadAction } from './actions' import { activityCache } from './activity-cache' export function MarkReadButton() { const queryClient = useQueryClient() const queryKey = activityCache.key const markRead = useMutation({ mutationFn: markActivityReadAction, onMutate: async () => { await queryClient.cancelQueries({ queryKey }) const previous = queryClient.getQueryData(queryKey) queryClient.setQueryData(queryKey, { count: 0 }) return { previous } }, onError: (_error, _variables, context) => { queryClient.setQueryData(queryKey, context?.previous) }, }) return } ``` ```jsx 'use client' import { useMutation, useQueryClient } from '@tanstack/react-query' import { markActivityReadAction } from './actions' import { activityCache } from './activity-cache' export function MarkReadButton() { const queryClient = useQueryClient() const queryKey = activityCache.key const markRead = useMutation({ mutationFn: markActivityReadAction, onMutate: async () => { await queryClient.cancelQueries({ queryKey }) const previous = queryClient.getQueryData(queryKey) queryClient.setQueryData(queryKey, { count: 0 }) return { previous } }, onError: (_error, _variables, context) => { queryClient.setQueryData(queryKey, context?.previous) }, }) return } ``` -------------------------------- ### Cache the component or data with "use cache" Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/migrating-to-cache-components.mdx Fix card shown in the dev overlay for blocking prerender dynamic errors. Add the "use cache" directive to the async component to cache it. ```tsx async function Posts() { "use cache" return } ``` -------------------------------- ### generateMetadata with use cache (after) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/migrating-to-cache-components.mdx Add 'use cache' to generateMetadata when metadata depends on external but not runtime data. This caches the external data so the page can remain prerenderable. ```tsx // After - cache external data export async function generateMetadata() { 'use cache' const { title, description } = await db.query('site-metadata') return { title, description } } ``` -------------------------------- ### Cache server-provided data using use cache with cacheLife and cacheTag Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/client-side-data-fetching/tanstack-query.mdx Requires cacheComponents enabled in next.config.ts. Uses the 'use cache' directive along with cacheLife('max') and cacheTag to cache database queries that can be invalidated by mutations. ```ts import { cacheLife, cacheTag } from 'next/cache' import type { Product } from './product-cache' export async function getProduct(id: string): Promise { 'use cache' cacheLife('max') cacheTag(`product:${id}`) const product = await db.product.findUnique({ where: { id } }) if (!product) throw new Error('Product not found') return product } ``` ```js import { cacheLife, cacheTag } from 'next/cache' export async function getProduct(id) { 'use cache' cacheLife('max') cacheTag(`product:${id}`) const product = await db.product.findUnique({ where: { id } }) if (!product) throw new Error('Product not found') return product } ``` -------------------------------- ### Add use cache at file level Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Add 'use cache' at the file level to cache every exported function. All exported functions must be async. ```tsx // File level 'use cache' export default async function Page() { // ... } ``` -------------------------------- ### cacheTag Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/cacheTag.mdx The `cacheTag` function allows you to tag cached data for on-demand invalidation. By associating tags with cache entries, you can selectively purge or revalidate specific cache entries without affecting other cached data. It takes one or more string values. ```APIDOC ## cacheTag ### Description The `cacheTag` function allows you to tag cached data for on-demand invalidation. By associating tags with cache entries, you can selectively purge or revalidate specific cache entries without affecting other cached data. ### Usage To use `cacheTag`, enable the `cacheComponents` flag in your `next.config.js` file: ```ts filename="next.config.ts" switcher import type { NextConfig } from 'next' const nextConfig: NextConfig = { cacheComponents: true, } export default nextConfig ``` ```js filename="next.config.js" switcher const nextConfig = { cacheComponents: true, } module.exports = nextConfig ``` The `cacheTag` function takes one or more string values. ```tsx filename="app/data.ts" switcher import { cacheTag } from 'next/cache' export async function getData() { 'use cache' cacheTag('my-data') const res = await fetch('https://api.example.com/data') const data = await res.json() return data } ``` ```jsx filename="app/data.js" switcher import { cacheTag } from 'next/cache' export async function getData() { 'use cache' cacheTag('my-data') const res = await fetch('https://api.example.com/data') const data = await res.json() return data } ``` You can then purge the cache on-demand from a Server Function or Route Handler: - Use `updateTag` for read-your-own-writes scenarios, such as forms and other user-triggered mutations, where a user makes a change and the next read should fetch fresh data immediately. `updateTag` is only available inside Server Functions. - Use `revalidateTag` when it is acceptable to serve stale data while revalidation happens in the background, or when revalidating from a Route Handler or other context. For example, this Server Function adds a post and then purges every cache entry tagged `'my-data'` so the next read reflects the change: ```tsx filename="app/action.ts" switcher 'use server' import { updateTag } from 'next/cache' export default async function submit() { await addPost() updateTag('my-data') } ``` ```jsx filename="app/action.js" switcher 'use server' import { updateTag } from 'next/cache' export default async function submit() { await addPost() updateTag('my-data') } ``` For deployments with multiple server instances, see Distributed Tag Coordination. ``` -------------------------------- ### Extract and pass cookie value to a cached function with 'use cache' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/optimizing-prefetching.mdx Use this pattern when the lookup result is shared across many sessions. Read the cookie outside the cached function and pass the value in as an argument so the cache entry is keyed on that argument and sessions sharing the value share the entry. ```tsx import { cookies } from 'next/headers' async function UserNav() { const team = (await cookies()).get('team')?.value const topics = await getTopics(team) return ( ) } async function getTopics(team: string | undefined) { 'use cache' return db.topics.forTeam(team) } ``` -------------------------------- ### Cache reusable reads with cacheLife and cacheTag Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/interactive-apps.mdx Defines a cached server read function using the 'use cache' directive, cacheLife, and cacheTag for specific resource handles and broader collection handles. ```ts import { cacheLife, cacheTag } from 'next/cache' import { getTaskById } from '@/lib/db' export async function getTask(id: string) { 'use cache' cacheLife('hours') cacheTag('tasks', `task-${id}`) return getTaskById(id) } ``` -------------------------------- ### Enable Cache Components and Partial Prefetching in next.config.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/08-caching.mdx Add the cacheComponents and partialPrefetching options to your Next.js config to enable Cache Components. Set partialPrefetching explicitly; leaving it unset logs a warning. Set it to false only while migrating an app that adopted Cache Components before Partial Prefetching. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { cacheComponents: true, partialPrefetching: true, } module.exports = nextConfig ``` -------------------------------- ### Nesting rules for 'use cache: remote' Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache-remote.mdx Remote caches can be nested inside other remote caches or regular caches, but cannot be nested inside or wrap private caches. ```tsx // VALID: Remote inside remote async function outerRemote() { 'use cache: remote' const result = await innerRemote() return result } async function innerRemote() { 'use cache: remote' return getData() } // VALID: Remote inside regular cache async function outerCache() { 'use cache' // The inner remote cache will work when deferred to request time const result = await innerRemote() return result } async function innerRemote() { 'use cache: remote' return getData() } // INVALID: Remote inside private async function outerPrivate() { 'use cache: private' const result = await innerRemote() // Error! return result } async function innerRemote() { 'use cache: remote' return getData() } // INVALID: Private inside remote async function outerRemote() { 'use cache: remote' const result = await innerPrivate() // Error! return result } async function innerPrivate() { 'use cache: private' return getData() } ``` -------------------------------- ### Add use cache at function or component level Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Add 'use cache' at the function or component level. Cached functions and components must be async. ```tsx // Function level export async function getData() { 'use cache' const res = await fetch('https://api.example.com/data') const data = await res.json() return data } // Component level export async function MyComponent() { 'use cache' return <> } ``` -------------------------------- ### Set explicit cache lifetime with cacheLife('hours') Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/01-directives/use-cache.mdx Set an explicit cache lifetime with cacheLife in every use cache scope to make cache behavior clear at the call site. Uses the built-in 'hours' profile. ```tsx import { cacheLife } from 'next/cache' async function getData() { 'use cache' cacheLife('hours') // Use built-in 'hours' profile const res = await fetch('https://api.example.com/data') return res.json() } ``` -------------------------------- ### unstable_cache(fetchData, keyParts, options) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/04-functions/unstable_cache.mdx Caches the results of an asynchronous function and returns a function that, when invoked, resolves to the cached data. If the data is not in the cache, the provided function is invoked, its result is cached, and then returned. The function passed to unstable_cache cannot depend on the incoming request; read request data before calling the cached function and pass values as arguments. ```APIDOC ## unstable_cache(fetchData, keyParts, options) ### Description Caches the results of an asynchronous function and returns a function that, when invoked, resolves to the cached data. If the data is not in the cache, the provided function is invoked, its result is cached, and then returned. The function passed to `unstable_cache` cannot depend on the incoming request; read request data before calling the cached function and pass values as arguments. ### Method Function call ### Endpoint `unstable_cache(fetchData, keyParts, options)` ### Parameters - **fetchData** (function) - Required - An asynchronous function that fetches the data you want to cache. It must return a `Promise`. - **keyParts** (array) - Optional - An extra array of keys that further adds identification to the cache. By default, `unstable_cache` already uses the arguments and the stringified version of your function as the cache key. It is optional in most cases; the only time you need to use it is when you use external variables without passing them as parameters. However, it is important to add closures used within the function if you do not pass them as parameters. - **options** (object) - Optional - An object that controls how the cache behaves. It can contain the following properties: - **tags** (array) - Optional - An array of tags that can be used to control cache invalidation. Next.js will not use this to uniquely identify the function. - **revalidate** (number | false) - Optional - The number of seconds after which the cache should be revalidated. Omit or pass `false` to cache indefinitely or until matching `revalidateTag()` or `revalidatePath()` methods are called. ### Returns A function that when invoked, returns a Promise that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned. ### Example ```jsx import { getUser } from './data'; import { unstable_cache } from 'next/cache'; const getCachedUser = unstable_cache( async (id) => getUser(id), ['my-app-user'] ); export default async function Component({ userID }) { const user = await getCachedUser(userID); ... } ``` ```