new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · API reference · all subjects

directives

82 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Directives in Next.js

Directives are used to modify the behavior of your Next.js application.

'use cache: remote' example with user preferences

```tsx async function getProductPrice(productId: string, currency: string) { 'use cache: remote' cacheTag(`product-price-${productId}`) cacheLife({ expire: 3600 }) // 1 hour return db.products.getPrice(productId, currency) } ``` This caches product prices per currency combination, allowing all users with the same currency to share the cache entry.

'use cache: remote' example reducing database load

```tsx async function getGlobalStats() { 'use cache: remote' cacheTag('global-stats') cacheLife({ expire: 60 }) // 1 minute const stats = await db.analytics.aggregate({ total_users: 'count', active_sessions: 'count', revenue: 'sum', }) return stats } ``` This caches expensive database queries so the upstream database sees at most one request per minute regardless of user count.

Platform support for 'use cache: remote'

'use cache: remote' is supported on Node.js server, Docker container, and Adapters. It is not supported for static export.

'use cache: remote' version history

'use cache: remote' was introduced in v16.0.0 and is enabled with the Cache Components feature.

'use cache: remote' directive syntax

The 'use cache: remote' directive is a string literal placed at the top of an async function or component to enable persistent remote caching. It must be used with the cacheComponents config flag enabled.

cacheComponents config required for 'use cache: remote'

To use 'use cache: remote', enable the cacheComponents flag in next.config.ts or next.config.js. Example: const nextConfig = { cacheComponents: true }

'use cache: remote' stores in remote cache handler instead of in-memory

'use cache: remote' stores cached output in a remote cache handler instead of in-memory, providing durable caching shared across all server instances. The handler implementation is configured via cacheHandlers config.

Remote cache limitations: cannot access cookies/headers directly

'use cache: remote' cannot access runtime values like cookies() or headers() directly. These values must be extracted and passed as function arguments to be included in the cache key.

Remote cache vs 'use cache' comparison

Comparison table: 'use cache' uses in-memory or cache handler caching shared across users with no additional costs; 'use cache: remote' uses remote cache handler shared across users with infrastructure and network latency costs; 'use cache: private' has no server-side caching and is per-client (browser).

Remote cache entries do not persist across deploys

Remote cache entries do not persist across deploys because the cache key includes the deploymentId or buildId. A new build produces new keys and previous build entries are no longer reachable.

'use cache: remote' nesting rules

Remote caches can be nested inside other remote caches and inside regular 'use cache' caches. Remote caches cannot be nested inside 'use cache: private' caches, and private caches cannot be nested inside remote caches.

Cache key design for 'use cache: remote'

Design cache keys thoughtfully by including low-cardinality dimensions (e.g., category instead of price filter, language instead of user ID). High-cardinality values create many cache entries, reducing cache utilization. Filter high-cardinality data in-memory instead.

When to use 'use cache: remote'

'use cache: remote' makes sense for rate-limited APIs, protecting slow backends, expensive operations, and flaky services. It provides most value for request-time content (accessed via cookies, headers, searchParams) inside Suspense boundaries in serverless environments where cache hit rates are low across instances.

use server example: file-level with createUser

Example showing file-level 'use server' directive: ```tsx 'use server' import { db } from '@/lib/db' import { auth } from '@/lib/auth' export async function createUser(data: { name: string; email: string }) { const session = await auth() if (!session?.user) { throw new Error('Unauthorized') } const user = await db.user.create({ data }) return { id: user.id, name: user.name } } ```

Server Functions return value security

Server Function return values are serialized and sent to the client. Only return data the UI needs, not raw database records.

Server Functions authentication best practice

Always authenticate and authorize users before performing sensitive server-side operations in Server Functions. Read authentication from cookies or headers rather than accepting tokens as function parameters.

use server example: inline in function

Example showing inline 'use server' directive within a single async function: ```tsx import { EditPost } from './edit-post' import { revalidatePath } from 'next/cache' export default async function PostPage({ params }: { params: { id: string } }) { const post = await getPost(params.id) async function updatePost(formData: FormData) { 'use server' // Verify auth before saving (e.g. inside savePost) await savePost(params.id, formData) revalidatePath(`/posts/${params.id}`) } return <EditPost updatePostAction={updatePost} post={post} /> } ```

use server example: importing Server Function in Client Component

Example showing how to import and use a Server Function in a Client Component: ```tsx 'use client' import { fetchUsers } from '../actions' export default function MyButton() { return <button onClick={() => fetchUsers()}>Fetch Users</button> } ```

use server directive purpose

The use server directive designates a function or file to be executed on the server side. It can be used at the top of a file to indicate that all functions in the file are server-side, or inline at the top of a function to mark the function as a Server Function. This is a React feature.

use server at file top - all functions server-side

When 'use server' is placed at the top of a file, all exported functions in that file are executed on the server side.

use server inline - single function

When 'use server' is placed inline at the top of a single function, only that specific function is marked as a Server Function to be executed on the server side.

Server Functions in Client Components require dedicated file

To use Server Functions in Client Components, the Server Functions must be created in a dedicated file using the 'use server' directive at the top of that file. These Server Functions can then be imported into both Client and Server Components and executed.

use server example: file-level with fetchUsers

Example showing 'use server' directive at file top with a fetchUsers Server Function: ```tsx 'use server' import { db } from '@/lib/db' import { auth } from '@/lib/auth' export async function fetchUsers() { const session = await auth() if (!session?.user) { throw new Error('Unauthorized') } const users = await db.user.findMany({ select: { id: true, name: true, email: true }, }) return users } ```

use cache build timeout error

If your build hangs with the error 'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or uncached data were used inside "use cache"', you're accessing Promises that resolve to uncached or runtime data, created outside a 'use cache' boundary. The cached function waits for data that can't resolve during the build, causing a timeout after 50 seconds.

use cache directive overview

The 'use cache' directive allows you to mark a route, React component, or a function as cacheable. It can be used at the top of a file to indicate that all exports in the file should be cached, or inline at the top of a function or component to cache the return value. Functions and components that use 'use cache' must be async.

use cache file-level example

'use cache' at file level: ```tsx // File level 'use cache' export default async function Page() { // ... } ``` When used at file level, every exported function becomes a cached function and must also be async.

use cache component-level example

'use cache' at component level: ```tsx export async function MyComponent() { 'use cache' return <></> } ```

use cache function-level example

'use cache' at function level: ```tsx export async function getData() { 'use cache' const data = await fetch('/api/data') return data } ```

use cache key generation components

A cache entry's key is generated using a serialized version of its inputs, which includes: (1) Build ID - unique per build, changing this invalidates all cache entries. If 'deploymentId' is configured, it overrides the build ID for cache key purposes. (2) Function ID - a secure hash of the function's location and signature in the codebase. (3) Serializable arguments - props (for components) or function arguments. (4) HMR refresh hash (development only) - invalidates cache on hot module replacement.

use cache serializable argument types

Arguments to cached functions must be serializable. Supported argument types: primitives (string, number, boolean, null, undefined), plain objects ({ key: value }), arrays ([1, 2, 3]), Dates, Maps, Sets, TypedArrays, ArrayBuffers, and React elements (as pass-through only). Unsupported types: class instances, functions (except as pass-through), Symbols, WeakMaps, WeakSets, and URL instances.

use cache serializable return value types

Return values from cached functions must be serializable. Supported return value types include all argument types (primitives, plain objects, arrays, Dates, Maps, Sets, TypedArrays, ArrayBuffers, React elements as pass-through) plus JSX elements. Unsupported types: class instances, functions (except as pass-through), Symbols, WeakMaps, WeakSets, and URL instances.

use cache pass-through pattern

You can accept non-serializable values in 'use cache' as long as you don't introspect them. This enables composition patterns with 'children' and Server Actions. For example, you can accept 'children' or a Server Action function as a prop and pass it through without reading or modifying it.

use cache cannot access request-time APIs

Cached functions and components cannot access runtime APIs like cookies(), headers(), or searchParams. The restriction follows the call stack: a helper that the cached function calls that reads one of these APIs fails with the 'next-request-in-use-cache' error. Read these values outside the cached scope and pass them as arguments.

use cache runtime caching behavior by environment

Runtime cache behavior with the default in-memory handler depends on hosting environment: (1) Serverless - cache entries typically don't persist across requests (each request can be a different instance), or during revalidation. Build-time caching works normally. (2) Self-hosted - cache entries persist across requests. Control cache size with 'cacheMaxMemorySize'.

use cache Draft Mode behavior

When Draft Mode is enabled, all cached functions and components re-execute on every request, and results are not saved to the cache. This ensures draft content is always fresh without requiring any changes to your caching code. You can read 'isEnabled' from draftMode() inside a 'use cache' scope, but other runtime APIs like cookies() and headers() are not allowed, even when Draft Mode is active.

use cache React.cache isolation

React.cache operates in an isolated scope inside 'use cache' boundaries. Values stored via React.cache outside a 'use cache' function are not visible inside it. This means you cannot use React.cache to pass data into a 'use cache' scope. To pass data into a 'use cache' scope, use function arguments instead.

use cache client-side stale time

On the client, content from the server cache is stored in the browser's memory for the duration defined by the 'stale' time. The client router enforces a minimum 30-second stale time, regardless of configuration. The 'x-nextjs-stale-time' response header communicates cache lifetime from server to client.

use cache default cacheLife profile

If you omit cacheLife in a 'use cache' scope, the 'default' profile applies: stale is 5 minutes (client-side), revalidate is 15 minutes (server-side), and expire is never expires by time.

use cache time-based revalidation with cacheLife

Set an explicit cache lifetime with cacheLife() in every 'use cache' scope. Example: 'use cache' followed by cacheLife('hours') makes the cache behavior clear at the call site instead of depending on the default profile or surrounding caches.

use cache on-demand revalidation with tags

Use cacheTag(), updateTag(), or revalidateTag() for on-demand cache invalidation in 'use cache' scopes. Example: call cacheTag('products') inside a cached function, then call updateTag('products') in a Server Action to invalidate all 'products' caches.

use cache entire route example

To prerender an entire route, add 'use cache' to the top of both the 'layout' and 'page' files. Each of these segments are treated as separate entry points and will be cached independently. Any components imported and nested in the 'page' file are part of the cache output associated with the 'page'.

use cache component output caching example

You can use 'use cache' at the component level to cache any fetches or computations performed within that component: ```tsx export async function Bookings({ type = 'haircut' }: BookingsProps) { 'use cache' async function getBookingsData() { const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`) return data } return //... } interface BookingsProps { type: string } ``` The cache entry will be reused as long as the serialized props produce the same value in each instance.

use cache pass-through children example

```tsx async function CachedWrapper({ children }: { children: ReactNode }) { 'use cache' // Don't read or modify children - just pass it through return ( <div className="wrapper"> <header>Cached Header</header> {children} </div> ) } // Usage: children can be dynamic export default function Page() { return ( <CachedWrapper> <DynamicComponent /> {/* Not cached, passed through */} </CachedWrapper> ) } ``` This pattern allows you to pass dynamic or non-cacheable content through a cached component without affecting its cache entry.

use cache pass-through Server Actions example

```tsx async function CachedForm({ action }: { action: () => Promise<void> }) { 'use cache' // Don't call action here - just pass it through return <form action={action}>{/* ... */}</form> } ``` You can pass Server Actions through cached components as long as you don't invoke them inside the cacheable function.

use cache draftMode reading example

```tsx import { draftMode } from 'next/headers' async function Content() { 'use cache' const { isEnabled } = await draftMode() const url = isEnabled ? 'https://draft.example.com/content' : 'https://production.example.com/content' const data = await fetch(url) return <article>{/* ... */}</article> } ``` You can read 'isEnabled' from draftMode() inside a 'use cache' scope, though other runtime APIs like cookies() and headers() are not allowed.

use cache verbose logging with NEXT_PRIVATE_DEBUG_CACHE

Set the environment variable NEXT_PRIVATE_DEBUG_CACHE=1 for verbose cache logging: 'NEXT_PRIVATE_DEBUG_CACHE=1 npm run dev' for development or 'NEXT_PRIVATE_DEBUG_CACHE=1 npm run start' for production. This environment variable also logs ISR and other caching mechanisms.

use cache captured variables

When a cached function references variables from outer scopes, those variables are automatically captured and bound as arguments, making them part of the cache key. When a cached function reads root parameters, only the ones it actually reads become part of its cache key.

use cache passing runtime data Promises pitfall

Don't pass Promises that resolve to runtime data (like cookies()) as props to cached components. For example, if you pass a Promise from cookies() as a prop to a cached component, the build will hang because the cached function waits for runtime data during the build. Instead, await the cookies store in the parent component and pass individual cookie values.

use cache shared storage pitfall

Don't store dynamic Promises in shared Maps or storage accessed by cached code. For example, if a non-cached function stores a Promise from fetch() in a Map, and a cached function retrieves and awaits that Promise from the Map, the build will hang. Use Next.js's built-in fetch() deduplication or use separate Maps for cached and uncached contexts.

use cache platform support

Platform support for 'use cache': Node.js server - Yes. Docker container - Yes. Static export - No. Adapters - Platform-specific.

use cache version history

Version history: v16.0.0 - 'use cache' is enabled with the Cache Components feature. v15.0.0 - 'use cache' is introduced as an experimental feature.

Setting explicit cacheLife in every use cache scope recommended

It is recommended to set a cacheLife in every 'use cache' scope so its behavior is clear at the call site. Omitting it leaves the lifetime implicit with the default profile applied, which makes it harder to reason about, especially in nested cached scopes.

Dynamic cache lifetimes from data example

import { cacheLife, cacheTag } from 'next/cache' async function getPostContent(slug: string) { 'use cache' const post = await fetchPost(slug) cacheTag(`post-${slug}`) if (!post) { cacheLife('minutes') return null } cacheLife({ revalidate: post.revalidateSeconds ?? 3600, }) return post.data }

Omitted properties in inline profile inherit from default

When using an inline cache profile object passed directly to cacheLife(), any omitted properties inherit from the default profile. Using cacheLife({}) with an empty object applies the default profile values.

expire must be longer than revalidate

When both revalidate and expire are set in a cache profile, expire must be longer than revalidate. Next.js validates this and raises an error for invalid configurations.

Error thrown for nested short-lived cache without explicit outer cacheLife

When a short-lived cache (zero revalidate or expire under 5 minutes) is nested inside another 'use cache' without an explicit cacheLife, Next.js throws an error during prerendering to prevent accidental misconfiguration where the outer cache would silently become short-lived too.

cacheLife must be called in same function where caching is defined

cacheLife should be called in the same function or component where caching is defined. It should not be abstracted into shared utilities so the cache behavior remains explicit and easy to reason about.

Conditional cache lifetimes example

import { cacheLife, cacheTag } from 'next/cache' async function getPostContent(slug: string) { 'use cache' const post = await fetchPost(slug) cacheTag(`post-${slug}`) if (!post) { cacheLife('minutes') return null } cacheLife('days') return post.data }

cacheLife inline profile example

'use cache' import { cacheLife } from 'next/cache' export default async function Page() { cacheLife({ stale: 3600, revalidate: 900, expire: 86400, }) return <div>Page</div> }

Give your agent this brain