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

functions

556 notes in this subject, read out of this brain and free to use. This is page 6 of 10.

revalidateTag Server Action example

Example of revalidateTag in a Server Action: 'use server'; import { revalidateTag } from 'next/cache'; export default async function submit() { await addPost(); revalidateTag('posts', 'max'); }

unstable_noStore preferred over dynamic export

unstable_noStore is preferred over export const dynamic = 'force-dynamic' because it is more granular and can be used on a per-component basis rather than affecting the entire route.

unstable_noStore import and basic usage

Import unstable_noStore from 'next/cache' and call it inside an async server component. Example: import { unstable_noStore as noStore } from 'next/cache'; export default async function ServerComponent() { noStore(); const result = await db.query(...); }

unstable_noStore function overview

unstable_noStore is a function from 'next/cache' that can be used to declaratively opt out of prerendering and indicate that a particular component should not be cached. In Next.js version 15, the connection function is recommended as a replacement.

unstable_noStore version history

unstable_noStore was introduced in v14.0.0 and deprecated in favor of the connection function in v15.0.0.

unstable_noStore use cases

unstable_noStore can be used as a replacement for fetch options like cache: 'no-store', next: { revalidate: 0 }, and in cases where fetch is not available.

unstable_noStore inside unstable_cache behavior

Using unstable_noStore inside unstable_cache will not opt out of static generation. Instead, it will defer to the cache configuration to determine whether to cache the result or not.

unstable_noStore equivalent to cache no-store

unstable_noStore is equivalent to fetch with cache: 'no-store' option.

unstable_cache cannot access headers and cookies inside cache scope

Accessing uncached data sources such as headers or cookies inside a cache scope is not supported. If you need this data inside a cached function, use headers outside the cached function and pass the required uncached data as an argument.

unstable_cache basic example

Example usage: 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); ... }

unstable_cache introduced in v14.0.0

unstable_cache was introduced in Next.js version 14.0.0.

unstable_cache replaced by use cache

unstable_cache has been replaced by the use cache directive in Next.js 16. The documentation recommends opting into Cache Components and replacing unstable_cache with the use cache directive.

unstable_cache function signature and parameters

unstable_cache takes three parameters: (1) fetchData - an asynchronous function that fetches the data and returns a Promise, (2) keyParts - an optional array of keys that provides additional cache identification; by default unstable_cache uses the arguments and stringified function as cache key, and keyParts is needed when using external variables or closures without passing them as parameters, (3) options - an object controlling cache behavior with properties: tags (array of tags for cache invalidation), and revalidate (number of seconds until cache revalidation, or false/omitted for indefinite caching until revalidateTag() or revalidatePath() is called).

unstable_cache return value

unstable_cache returns a function that when invoked returns a Promise resolving to cached data. If data is not in cache, the provided function is invoked, its result is cached, and then returned.

unstable_cache uses Next.js built-in cache

unstable_cache uses Next.js' built-in cache to persist results across requests and deployments.

unstable_rethrow and Partial Prerendering

Partial Prerendering (PPR) affects the behavior of APIs that throw errors when a route segment is marked to throw an error unless it is static, including cookies(), headers(), searchParams, and fetch calls with cache: 'no-store' or revalidate: 0.

unstable_rethrow purpose

unstable_rethrow is used to avoid catching internal errors thrown by Next.js when attempting to handle errors thrown in application code. It allows framework-controlled exceptions like notFound() and redirect() to be properly handled by Next.js instead of being caught by application try/catch blocks.

unstable_rethrow APIs that throw

The following Next.js APIs rely on throwing errors that should be rethrown using unstable_rethrow: notFound(), redirect(), permanentRedirect(), cookies(), headers(), searchParams in page props, fetch(..., { cache: 'no-store' }), and fetch(..., { next: { revalidate: 0 } }).

unstable_rethrow usage pattern

unstable_rethrow should be called at the top of a catch block, passing the error object as its only argument. It can also be used within a .catch handler of a promise.

unstable_rethrow with resource cleanup

Any resource cleanup like clearing intervals or timers must either happen prior to calling unstable_rethrow or within a finally block, as unstable_rethrow re-throws the error immediately.

notFound() caught by try/catch prevents component rendering

When notFound() is called inside a try block, if the error is caught by a catch block without using unstable_rethrow, the error will be caught and the not-found.js component will not render as expected.

unstable_rethrow example with notFound

Example showing how to use unstable_rethrow to prevent notFound() from being caught: import { notFound, unstable_rethrow } from 'next/navigation' export default async function Page() { try { const post = await fetch('https://.../posts/1').then((res) => { if (res.status === 404) notFound() if (!res.ok) throw new Error(res.statusText) return res.json() }) } catch (err) { unstable_rethrow(err) console.error(err) } }

unstable_rethrow alternatives

You may be able to avoid using unstable_rethrow if you encapsulate your API calls that throw and let the caller handle the exception. Only use unstable_rethrow if your caught exceptions may include both application errors and framework-controlled exceptions like redirect() or notFound().

Assigning tags to cached data with fetch

Tags can be assigned to cached data using the next.tags option with fetch for caching external API requests: fetch(url, { next: { tags: ['posts'] } })

updateTag behavior with cached data

updateTag immediately expires the cached data for the specified tag. The next request will wait to fetch fresh data rather than serving stale content from the cache, ensuring users see their changes immediately.

updateTag return value

updateTag does not return a value.

updateTag context restrictions

updateTag can only be called from within Server Actions. It cannot be used in Route Handlers, Client Components, or any other context. If you need to invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead.

updateTag parameters

updateTag(tag: string): void. The tag parameter is a string representing the cache tag associated with the data you want to update. It must not exceed 256 characters and is case-sensitive.

updateTag function overview

updateTag allows you to update cached data on-demand for a specific cache tag from within Server Actions. It is designed for read-your-own-writes scenarios, where a user makes a change and the UI immediately shows the change rather than stale data.

When to use revalidateTag instead

Use revalidateTag instead when you are in a Route Handler or other non-action context, want stale-while-revalidate semantics, or are building a webhook or API endpoint for cache invalidation.

When to use updateTag

Use updateTag when you are in a Server Action, need immediate cache invalidation for read-your-own-writes, and want to ensure the next request sees updated data.

updateTag error in Route Handler

Attempting to use updateTag in a Route Handler will throw an error with message: 'updateTag can only be called from within a Server Action'. Use revalidateTag instead in Route Handlers.

updateTag Server Action example

Example showing updateTag in a Server Action: 'use server' import { updateTag } from 'next/cache' import { redirect } from 'next/navigation' export async function createPost(formData: FormData) { const title = formData.get('title') const content = formData.get('content') const post = await db.post.create({ data: { title, content }, }) updateTag('posts') updateTag(`post-${post.id}`) redirect(`/posts/${post.id}`) }

updateTag vs revalidateTag differences

updateTag and revalidateTag serve different purposes. updateTag can only be used in Server Actions and ensures the next request waits for fresh data with no stale content served, designed for read-your-own-writes scenarios. revalidateTag can be used in Server Actions and Route Handlers; with profile='max' it serves cached data while fetching fresh data in the background (stale-while-revalidate); without profile it has legacy behavior equivalent to updateTag.

Assigning tags with cacheTag function

Tags can be assigned to cached data using cacheTag inside cached functions or components with the 'use cache' directive. Example: import { cacheTag } from 'next/cache'; async function getData() { 'use cache'; cacheTag('posts'); }

useLinkStatus must be used within a Link descendant component

useLinkStatus must be used within a descendant component of a Link component. Using it outside this context will not work properly.

useLinkStatus hook purpose and use cases

The useLinkStatus hook lets you track the pending state of a Link component. It is useful when prefetching is disabled or in progress meaning navigation is blocked, or when the destination route is dynamic and doesn't include a loading.js file. Use it for subtle, inline feedback like a shimmer effect over the clicked link while navigation completes. Route-level fallbacks with loading.js and prefetching are preferred alternatives.

useLinkStatus hook return value

useLinkStatus returns an object with a single property: pending (boolean). The pending property is true before history updates and false after.

useLinkStatus hook parameters

useLinkStatus does not take any parameters. It is called with no arguments: const { pending } = useLinkStatus()

useLinkStatus with prefetch=false is most useful

The useLinkStatus hook is most useful when prefetch={false} is set on the Link component. If the linked route has been prefetched, the pending state will be skipped.

useLinkStatus with multiple rapid link clicks

When clicking multiple links in quick succession, only the last link's pending state is shown.

useLinkStatus not supported in Pages Router

useLinkStatus is not supported in the Pages Router and always returns { pending: false }.

useLinkStatus inline indicators and layout shifts

Inline indicators using useLinkStatus can easily introduce layout shifts. Prefer a fixed-size, always-rendered hint element and toggle its opacity, or use an animation instead.

useLinkStatus introduced in v15.3.0

The useLinkStatus hook was introduced in Next.js version 15.3.0.

useLinkStatus basic example with inline hint

Example showing useLinkStatus used within a Hint component that renders a span with a pending class: ```tsx 'use client' import Link from 'next/link' import { useLinkStatus } from 'next/link' function Hint() { const { pending } = useLinkStatus() return ( <span aria-hidden className={`link-hint ${pending ? 'is-pending' : ''}`} /> ) } export default function Header() { return ( <header> <Link href="/dashboard" prefetch={false}> <span className="label">Dashboard</span> <Hint /> </Link> </header> ) } ```

useLinkStatus with animation delay for fast navigation

To avoid showing the hint on fast navigation, use an animation delay (e.g. 100ms) and start the animation as invisible (e.g. opacity: 0). Example CSS shows using animation-delay: 100ms to ensure the hint only appears if navigation takes time to complete.

useOffline requires experimental.useOffline config

Enabling the experimental.useOffline config option in next.config.js turns on offline connectivity detection and automatic retry of blocked navigation, prefetch, and Server Action requests, and exposes the useOffline hook so Client Components can read the state. Without this flag, the useOffline hook always returns false.

useOffline hook - returns boolean

The useOffline hook is imported from 'next/offline' and returns a boolean indicating whether the app is currently offline. It is used to render connectivity-aware UI such as banners or offline-aware Suspense fallbacks. Without the experimental.useOffline config flag enabled, the hook always returns false.

useOffline offline behavior

When the experimental.useOffline flag is enabled, Next.js provides automatic retry of blocked navigation, prefetch, and Server Action requests when the app is offline. The useOffline hook exposes the offline state so Client Components can render connectivity-aware UI.

useOffline with Suspense fallback

The useOffline hook can be used in a loading.tsx file to provide connectivity-aware messages. When a user navigates to a route while offline, the prefetched static shell renders immediately but dynamic content behind a Suspense boundary blocks on the network. Inside loading.tsx, use useOffline to show 'Waiting for connection to load this page...' when offline, or 'Loading...' when online. When connectivity is restored, Next.js automatically retries the blocked request and the dynamic content streams in.

useOffline version history

The useOffline hook was introduced in v16.x.0.

useOffline offline banner example

Example: A component that imports useOffline from 'next/offline', checks if isOffline is true, and renders a banner with role="status" and the message 'You are offline. Some content may be unavailable.' when offline. When online (isOffline is false), it returns null.

useOffline client-only hook

The useOffline hook must be used in Client Components. It requires the 'use client' directive at the top of the component file.

useOffline does not take parameters

The useOffline hook does not accept any parameters. It is called with no arguments: const isOffline = useOffline()

useOffline return value false

The useOffline hook returns false when the app is online, when rendering on the server, or as the initial value before hydration completes.

useOffline return value true

The useOffline hook returns true when the app is offline. This occurs when a network request has failed, or the browser has fired an offline event.

experimental.useOffline configuration

Set the experimental.useOffline option to true in next.config.js: module.exports = { experimental: { useOffline: true } }

useParams with Cache Components and Suspense

When cacheComponents is enabled, useParams may require a Suspense boundary depending on whether the params can be resolved during prerendering. For static routes and routes with generateStaticParams, every dynamic param is known at build time and useParams resolves on the server without requiring a Suspense boundary. For routes with dynamic params not covered by generateStaticParams, the param is not known until request time, so useParams suspends and the component must be wrapped (or a parent component wrapped) in a Suspense boundary so its fallback can be rendered during prerendering; otherwise, the build fails.

useParams introduced in v13.3.0

useParams was introduced in Next.js version 13.3.0.

useParams hook overview

useParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL. It must be imported from 'next/navigation'. It does not take any parameters.

Give your agent this brain