Unverified Commit 6a79d8aa authored by Joseph's avatar Joseph Committed by GitHub

[lts-active] Backport docs fixes since v16.4.0 (#100246)

Backports documentation fixes from canary to `releases/lts/active` (docs
commits since `v16.4.0`).

### Included commits:

- #99738 Document `next analyze export` and skill are added in 16.4
- #99858 docs: align function sidebar titles
- #99820 docs: clarify Cache Components runtime config
- #100041 docs: update links for transferred demo repositories
- #100119 docs: update links to demos moved to the nextjs org
- #96517 docs(cache-handlers): explain updateTags durations, fix Redis
EX for Infinity
- #100084 docs: fix example path regexr
- #100144 docs: clarify Server Action dispatch across Mutating Data and
the guide
- #100197 docs: update links for newly transferred demos
- #100196 docs: narrow catchError ErrorInfo.error, typed as unknown
- #99542 docs: fix "a HTTP"/"a SSR" grammar and Node.js casing
- #100198 docs: clarify ESLint 10 support
- #96622 Add cache-handler-redis-turbo example (Next.js 16 Cache
Components + Redis)
- #100186 docs: replace unbounded cacheHandler snippets and fix tag
handling in examples
- #100232 docs: type error.js error prop as unknown
- #100003 docs: add instant navigation testing to Playwright guide
- #100252 docs: note that 'use cache: private' results persist across
requests in dev
- #100247 docs: Add Pages Router upgrade guides for versions 15 and 16

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarWill Binns-Smith <wbinnssmith@gmail.com>
Co-authored-by: 's avatarJan Kassens <kassens@vercel.com>
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarEddy (Frontend Engineer) <101346918+leejpsd@users.noreply.github.com>
Co-authored-by: 's avatarHiiTea <luohaojing@gmail.com>
Co-authored-by: 's avatardev <61645523+deveshasawa28@users.noreply.github.com>
Co-authored-by: 's avatarTechnnik <JannikZed@users.noreply.github.com>
Co-authored-by: 's avatarCopilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: 's avatarYousef Dawood <78578298+yousefdawood7@users.noreply.github.com>
parent a75a7827
...@@ -204,7 +204,7 @@ There are two main ways you can invoke a Server Function: ...@@ -204,7 +204,7 @@ There are two main ways you can invoke a Server Function:
1. [Forms](#forms) in Server and Client Components 1. [Forms](#forms) in Server and Client Components
2. [Event Handlers](#event-handlers) and [useEffect](#useeffect) in Client Components 2. [Event Handlers](#event-handlers) and [useEffect](#useeffect) in Client Components
> **Good to know:** Server Functions are designed for server-side mutations. The client currently dispatches and awaits them one at a time. This is an implementation detail and may change. If you need parallel data fetching, use [data fetching](/docs/app/getting-started/fetching-data#server-components) in Server Components, or perform parallel work inside a single Server Function or [Route Handler](/docs/app/guides/backend-for-frontend#manipulating-data). > **Good to know:** Server Functions are designed for server-side mutations. The client dispatches and awaits them one at a time. See [Sequential dispatch on the client](/docs/app/guides/server-actions#sequential-dispatch-on-the-client). If you need parallel data fetching, use [data fetching](/docs/app/getting-started/fetching-data#server-components) in Server Components, or perform parallel work inside a single Server Function or [Route Handler](/docs/app/guides/backend-for-frontend#manipulating-data).
### Forms ### Forms
......
...@@ -217,7 +217,7 @@ export default function ErrorPage({ ...@@ -217,7 +217,7 @@ export default function ErrorPage({
error, error,
retry, retry,
}: { }: {
error: Error & { digest?: string } error: unknown
retry: () => void retry: () => void
}) { }) {
useEffect(() => { useEffect(() => {
...@@ -286,10 +286,12 @@ For component-level error recovery, the [`catchError`](/docs/app/api-reference/f ...@@ -286,10 +286,12 @@ For component-level error recovery, the [`catchError`](/docs/app/api-reference/f
import { catchError, type ErrorInfo } from 'next/error' import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, retry }: ErrorInfo) { function ErrorFallback(props: { title: string }, { error, retry }: ErrorInfo) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
</div> </div>
) )
...@@ -304,10 +306,12 @@ export default catchError(ErrorFallback) ...@@ -304,10 +306,12 @@ export default catchError(ErrorFallback)
import { catchError } from 'next/error' import { catchError } from 'next/error'
function ErrorFallback(props, { error, retry }) { function ErrorFallback(props, { error, retry }) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
</div> </div>
) )
...@@ -403,7 +407,7 @@ export default function GlobalError({ ...@@ -403,7 +407,7 @@ export default function GlobalError({
error, error,
retry, retry,
}: { }: {
error: Error & { digest?: string } error: unknown
retry: () => void retry: () => void
}) { }) {
return ( return (
......
...@@ -286,3 +286,9 @@ Then give the agent a prompt like: ...@@ -286,3 +286,9 @@ Then give the agent a prompt like:
```prompt ```prompt
Make the product title instant when navigating from /products to /products/[id]. Use the next-partial-prefetching-optimizer Skill. Make the product title instant when navigating from /products to /products/[id]. Use the next-partial-prefetching-optimizer Skill.
``` ```
## Version History
| Version | Changes |
| --------- | ------------------------------------ |
| `v16.4.0` | `next-bundle-optimizer` skill added. |
...@@ -69,4 +69,4 @@ After a mutation, invalidate any cached server read that provided the initial da ...@@ -69,4 +69,4 @@ After a mutation, invalidate any cached server read that provided the initial da
- [Client-side data fetching with SWR](/docs/app/guides/client-side-data-fetching/swr) - [Client-side data fetching with SWR](/docs/app/guides/client-side-data-fetching/swr)
- [Client-side data fetching with TanStack Query](/docs/app/guides/client-side-data-fetching/tanstack-query) - [Client-side data fetching with TanStack Query](/docs/app/guides/client-side-data-fetching/tanstack-query)
See both patterns in the live [`next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev) and its [source code](https://github.com/vercel-labs/next-spa-patterns). See both patterns in the live [`next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev) and its [source code](https://github.com/nextjs/next-spa-patterns).
...@@ -429,4 +429,4 @@ The optimistic SWR value updates the current screen. `updateTag` ensures the nex ...@@ -429,4 +429,4 @@ The optimistic SWR value updates the current screen. `updateTag` ensures the nex
> **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors. > **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/swr). Learn more about [SWR mutation and optimistic updates](https://swr.vercel.app/docs/mutation) and the [SWR documentation](https://swr.vercel.app/docs/getting-started). See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/nextjs/next-spa-patterns/tree/main/app/swr). Learn more about [SWR mutation and optimistic updates](https://swr.vercel.app/docs/mutation) and the [SWR documentation](https://swr.vercel.app/docs/getting-started).
...@@ -53,7 +53,7 @@ export default function Layout({ children }: LayoutProps<'/products'>) { ...@@ -53,7 +53,7 @@ export default function Layout({ children }: LayoutProps<'/products'>) {
} }
``` ```
See the [complete provider setup in the demo source](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query) or learn about provider options in the [TanStack Query Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr). See the [complete provider setup in the demo source](https://github.com/nextjs/next-spa-patterns/tree/main/app/react-query) or learn about provider options in the [TanStack Query Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Fetch data on the client ## Fetch data on the client
...@@ -655,4 +655,4 @@ async function ProductData({ id }) { ...@@ -655,4 +655,4 @@ async function ProductData({ id }) {
> **Good to know:** The timestamp must advance whenever the hydrated data changes. The helper suits tag-driven server data because both use the same tags. For time-driven server data, derive the data and hydration timestamp from the same cached snapshot instead of maintaining unrelated time windows. > **Good to know:** The timestamp must advance whenever the hydrated data changes. The helper suits tag-driven server data because both use the same tags. For time-driven server data, derive the data and hydration timestamp from the same cached snapshot instead of maintaining unrelated time windows.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query). Learn more about [TanStack Query optimistic updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) and the [TanStack Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview). See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/nextjs/next-spa-patterns/tree/main/app/react-query). Learn more about [TanStack Query optimistic updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) and the [TanStack Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
...@@ -48,7 +48,7 @@ export default nextConfig ...@@ -48,7 +48,7 @@ export default nextConfig
We'll build a product catalog with category layouts and product detail pages using the [Recipe API](https://next-recipe-api.vercel.dev/). You can find the resources used in this example here: We'll build a product catalog with category layouts and product detail pages using the [Recipe API](https://next-recipe-api.vercel.dev/). You can find the resources used in this example here:
- [Demo](https://partial-fallbacks.labs.vercel.dev/) - [Demo](https://partial-fallbacks.labs.vercel.dev/)
- [Code](https://github.com/vercel-labs/partial-fallbacks) - [Code](https://github.com/nextjs/partial-fallbacks)
### Prepare your routes ### Prepare your routes
......
...@@ -313,7 +313,7 @@ export async function createPost() { ...@@ -313,7 +313,7 @@ export async function createPost() {
} }
``` ```
[View a demo](https://on-demand-isr.vercel.app) and [explore the source code](https://github.com/vercel/on-demand-isr). [View a demo](https://on-demand-isr.vercel.app) and [explore the source code](https://github.com/nextjs/on-demand-isr).
### On-demand revalidation with `revalidateTag` ### On-demand revalidation with `revalidateTag`
......
...@@ -21,7 +21,7 @@ This guide adds responsive feedback to a task management app called _Taskboard_. ...@@ -21,7 +21,7 @@ This guide adds responsive feedback to a task management app called _Taskboard_.
The patterns build in order: stream slow data behind loading boundaries, add an instant priority toggle, build a reusable filter with a callback prop, show comments before they're confirmed, move cards between columns on drop, manage form lifecycle in a create dialog, and signal pending deletion to a parent. The final step caches the reusable reads so navigations stay instant. The patterns build in order: stream slow data behind loading boundaries, add an instant priority toggle, build a reusable filter with a callback prop, show comments before they're confirmed, move cards between columns on drop, manage form lifecycle in a create dialog, and signal pending deletion to a parent. The final step caches the reusable reads so navigations stay instant.
The companion [Taskboard demo](https://async-react-demo.labs.vercel.dev) ([source](https://github.com/vercel-labs/async-react-demo)) lets you see each pattern from this guide in action. The companion [Taskboard demo](https://async-react-demo.labs.vercel.dev) ([source](https://github.com/nextjs/async-react-demo)) lets you see each pattern from this guide in action.
The app is organized by feature. Everything for the task domain (queries, Server Functions, and components) lives under `features/task/`. Shared UI primitives live in `components/ui/`, and pages in `app/` compose feature components. The file paths throughout this guide follow that structure. The app is organized by feature. Everything for the task domain (queries, Server Functions, and components) lives under `features/task/`. Shared UI primitives live in `components/ui/`, and pages in `app/` compose feature components. The file paths throughout this guide follow that structure.
......
...@@ -941,7 +941,7 @@ See [`generateMetadata` with Cache Components](/docs/app/api-reference/functions ...@@ -941,7 +941,7 @@ See [`generateMetadata` with Cache Components](/docs/app/api-reference/functions
## `runtime = 'edge'` ## `runtime = 'edge'`
**Not supported.** Cache Components requires the Node.js runtime. Switch to the Node.js runtime (the default) by removing the [deprecated](/docs/messages/edge-runtime-deprecated) `runtime = 'edge'` export. If you need edge behavior for specific routes, use [Proxy](/docs/app/api-reference/file-conventions/proxy) instead. **Remove the `runtime` export.** Cache Components requires the Node.js runtime, which is the default, and does not support the [`runtime` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/runtime). Remove the export even when it is set to `runtime = 'nodejs'`. If a route uses the [deprecated](/docs/messages/edge-runtime-deprecated) `runtime = 'edge'` export, remove it and use [Proxy](/docs/app/api-reference/file-conventions/proxy) when you need edge behavior.
## `experimental_ppr` ## `experimental_ppr`
......
...@@ -24,7 +24,7 @@ Requests you issue directly with `fetch()` inside a Client Component, or through ...@@ -24,7 +24,7 @@ Requests you issue directly with `fetch()` inside a Client Component, or through
We will build a live-metrics page that fetches fresh data on every request, plus a ping form that calls a Server Action. We will build a live-metrics page that fetches fresh data on every request, plus a ping form that calls a Server Action.
- Source: [github.com/vercel-labs/use-offline](https://github.com/vercel-labs/use-offline) - Source: [github.com/nextjs/use-offline](https://github.com/nextjs/use-offline)
- Live demo: [use-offline.labs.vercel.dev](https://use-offline.labs.vercel.dev) - Live demo: [use-offline.labs.vercel.dev](https://use-offline.labs.vercel.dev)
The companion demo has two versions of this dashboard: `/without-feedback` uses a generic loading fallback, `/with-feedback` uses a connectivity-aware one. The next sections of this guide walk through building each. The companion demo has two versions of this dashboard: `/without-feedback` uses a generic loading fallback, `/with-feedback` uses a connectivity-aware one. The next sections of this guide walk through building each.
......
...@@ -98,6 +98,8 @@ cp -r .next/diagnostics/analyze ./analyze-before-refactor ...@@ -98,6 +98,8 @@ cp -r .next/diagnostics/analyze ./analyze-before-refactor
### Export analysis data ### Export analysis data
> Available in v16.4 and later. You can share feedback in the [dedicated GitHub discussion](https://github.com/vercel/next.js/discussions/86731) and view the demo at [turbopack-bundle-analyzer-demo.vercel.sh](https://turbopack-bundle-analyzer-demo.vercel.sh/).
Use `next analyze export` to stream a saved snapshot as JSON Lines for scripts or AI tools, without rebuilding or starting a server: Use `next analyze export` to stream a saved snapshot as JSON Lines for scripts or AI tools, without rebuilding or starting a server:
```bash filename="Terminal" package="npm" ```bash filename="Terminal" package="npm"
...@@ -353,3 +355,9 @@ module.exports = nextConfig ...@@ -353,3 +355,9 @@ module.exports = nextConfig
``` ```
</PagesOnly> </PagesOnly>
## Version History
| Version | Changes |
| --------- | ---------------------------------------------------------------- |
| `v16.4.0` | Add `next analyze export` and the `next-bundle-optimizer` skill. |
...@@ -544,7 +544,7 @@ The ref persists across hide/show cycles (refs aren't cleaned up), so `hasMounte ...@@ -544,7 +544,7 @@ The ref persists across hide/show cycles (refs aren't cleaned up), so `hasMounte
## Examples ## Examples
The [Activity Patterns Demo](https://react-activity-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/react-activity-patterns)) is a Next.js app with Cache Components enabled and three routes. Navigate between them to see state preservation in action: The [Activity Patterns Demo](https://react-activity-patterns.labs.vercel.dev) ([source](https://github.com/nextjs/react-activity-patterns)) is a Next.js app with Cache Components enabled and three routes. Navigate between them to see state preservation in action:
- **Data** — sortable table and selectable list that keep their state across navigations, plus a reviews section that prerenders in the background - **Data** — sortable table and selectable list that keep their state across navigations, plus a reviews section that prerenders in the background
- **Forms** — filter panel with DOM state (`<details>`, checkboxes, text inputs) that persists, and a newsletter form that resets after submission using `useLayoutEffect` cleanup - **Forms** — filter panel with DOM state (`<details>`, checkboxes, text inputs) that persists, and a newsletter form that resets after submission using `useLayoutEffect` cleanup
......
...@@ -16,7 +16,7 @@ Using an **inline script** that runs synchronously as the browser parses the HTM ...@@ -16,7 +16,7 @@ Using an **inline script** that runs synchronously as the browser parses the HTM
## Example ## Example
The companion [demo](https://preventing-flash-before-hydration.labs.vercel.dev/) ([source](https://github.com/vercel-labs/preventing-flash-before-hydration)) is built with `LANG=ja_JP.UTF-8` to simulate a server/client locale mismatch. It lets you compare: The companion [demo](https://preventing-flash-before-hydration.labs.vercel.dev/) ([source](https://github.com/nextjs/preventing-flash-before-hydration)) is built with `LANG=ja_JP.UTF-8` to simulate a server/client locale mismatch. It lets you compare:
- Inline script date formatting with no flash and no hydration error - Inline script date formatting with no flash and no hydration error
- A Client Component that calls `toLocaleDateString()` directly, showing the hydration error - A Client Component that calls `toLocaleDateString()` directly, showing the hydration error
......
...@@ -24,7 +24,7 @@ You can find the resources used in this example here: ...@@ -24,7 +24,7 @@ You can find the resources used in this example here:
- [Video](https://youtu.be/F6romq71KtI) - [Video](https://youtu.be/F6romq71KtI)
- [Demo](https://cache-components-public-pages.labs.vercel.dev/) - [Demo](https://cache-components-public-pages.labs.vercel.dev/)
- [Code](https://github.com/vercel-labs/cache-components-public-pages) - [Code](https://github.com/nextjs/cache-components-public-pages)
### Step 1: Add a simple header ### Step 1: Add a simple header
......
...@@ -108,9 +108,7 @@ If you want to host static assets on a different domain or CDN, you can use the ...@@ -108,9 +108,7 @@ If you want to host static assets on a different domain or CDN, you can use the
By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. On ephemeral compute platforms (common serverless setups), local disk is often non-persistent or unavailable, so this cache is effectively short-lived and per-instance. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching. By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. On ephemeral compute platforms (common serverless setups), local disk is often non-persistent or unavailable, so this cache is effectively short-lived and per-instance. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching.
To configure the cache location when self-hosting, you can configure a custom handler in your `next.config.js` file: To configure the cache location when self-hosting, set a custom handler in your `next.config.js` file:
For production deployments, use this as a starting point and extend it with durable storage, eviction policies, error handling, and distributed tag coordination. See [Custom Next.js Cache Handler](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) and the [Redis `cacheHandler` example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis). If you are configuring backends for `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers).
```jsx filename="next.config.js" ```jsx filename="next.config.js"
module.exports = { module.exports = {
...@@ -119,55 +117,21 @@ module.exports = { ...@@ -119,55 +117,21 @@ module.exports = {
} }
``` ```
Then, create `cache-handler.js` in the root of your project, for example: The handler file exports a class that implements `get`, `set`, `revalidateTag`, and `resetRequestCache`. See [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) for each method's signature, and the [Redis `cacheHandler` example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis) for a working implementation.
```jsx filename="cache-handler.js"
const cache = new Map()
module.exports = class CacheHandler {
constructor(options) {
this.options = options
}
async get(key) {
// This could be stored anywhere, like durable storage
return cache.get(key)
}
async set(key, data, ctx) {
// This could be stored anywhere, like durable storage
cache.set(key, {
value: data,
lastModified: Date.now(),
tags: ctx.tags,
})
}
async revalidateTag(tags) {
// tags is either a string or an array of strings
tags = [tags].flat()
// Iterate over all entries in the cache
for (let [key, value] of cache) {
// If the value's tags include the specified tag, delete this entry
if (value.tags.some((tag) => tags.includes(tag))) {
cache.delete(key)
}
}
}
// If you want to have temporary in memory cache for a single request that is reset For production deployments, the handler must:
// before the next request you can leverage this method
resetRequestCache() {}
}
```
Using a custom cache handler will allow you to ensure consistency across all pods hosting your Next.js application. For instance, you can save the cached values anywhere, like [Redis](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis) or AWS S3. - **Store entries where every instance can reach them**, like [Redis](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis) or AWS S3. A store inside the process, such as a `Map`, gives each pod its own copy of the cache again.
- **Bound the store's size.** Use a TTL or size-based eviction to remove entries for paths and `fetch` keys that are no longer requested.
- **Serialize entries.** Any store outside the process needs this. An entry can contain `Buffer` (for example `rscData`) and `Map` (for example `segmentData`) values that `JSON.stringify`/`JSON.parse` can't serialize and restore on their own. Not handling this serialization results in errors like `segmentData.get is not a function` or `failed to pipe response` on client-side navigation or prefetch (RSC) requests.
- **Index entries by tag.** `APP_PAGE`, `APP_ROUTE`, and `PAGES` entries carry their tags in the `x-next-cache-tags` response header (`data.headers`), while `ctx.tags` carries tags for `fetch` entries. Keep the index in the shared store, so a `revalidateTag` call on one instance invalidates the entry on every instance.
- **Handle storage errors**, such as timeouts and dropped connections.
> **Good to know:** > **Good to know:**
> >
> - `revalidatePath` is a convenience layer on top of cache tags. Calling `revalidatePath` will call the `revalidateTag` function with a special default tag for the provided page. > - `revalidatePath` is a convenience layer on top of cache tags. Calling `revalidatePath` will call the `revalidateTag` function with a special default tag for the provided page.
> - The example above keeps entries in memory. A handler backed by durable storage (like the [Redis example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis)) must serialize entries itself, and an entry can contain `Buffer` (for example `rscData`) and `Map` (for example `segmentData`) values that `JSON.stringify`/`JSON.parse` can't serialize and restore on their own. Not handling this serialization results in errors like `segmentData.get is not a function` or `failed to pipe response` on client-side navigation or prefetch (RSC) requests. > - If you are configuring backends for `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers).
> - When indexing entries for `revalidateTag`, read cache tags from the right place: `APP_PAGE`, `APP_ROUTE`, and `PAGES` entries carry them in the `x-next-cache-tags` response header (`data.headers`), while `ctx.tags` carries tags for `fetch` entries. > - Production-oriented community Redis handlers (GET timeouts, in-memory coalescing, multi-instance tag coordination) are listed in the [Redis example README](https://github.com/vercel/next.js/blob/canary/examples/cache-handler-redis/README.md#production-community-handlers), including [`@trieb.work/nextjs-turbo-redis-cache`](https://github.com/trieb-work/nextjs-turbo-redis-cache) and [`@mrjasonroy/cache-components-cache-handler`](https://github.com/mrjasonroy/cache-components-cache-handler).
## Build Cache ## Build Cache
......
...@@ -29,7 +29,7 @@ Next.js dispatches Server Actions one at a time per client. If a user triggers t ...@@ -29,7 +29,7 @@ Next.js dispatches Server Actions one at a time per client. If a user triggers t
A consequence: do not rely on `Promise.all` to parallelize Server Actions from the client. If you need parallel work, do it inside a single Server Action, fetch in parallel from a [Server Component](/docs/app/getting-started/fetching-data#server-components), or use a [Route Handler](/docs/app/guides/backend-for-frontend#manipulating-data) for non-mutation requests. A consequence: do not rely on `Promise.all` to parallelize Server Actions from the client. If you need parallel work, do it inside a single Server Action, fetch in parallel from a [Server Component](/docs/app/getting-started/fetching-data#server-components), or use a [Route Handler](/docs/app/guides/backend-for-frontend#manipulating-data) for non-mutation requests.
> **Good to know:** This is a property of the client dispatcher, not of Server Functions in general. Server-side, an action runs in its own request and can do anything an async function can do. > **Good to know:** This is a property of the client dispatcher, not of Server Functions in general. The server does not queue Server Actions. Each one runs in its own request as it arrives, and can do anything an async function can do.
## A single response carries data and UI ## A single response carries data and UI
......
...@@ -34,7 +34,7 @@ Next.js can start as a static site or even a strict SPA where everything is rend ...@@ -34,7 +34,7 @@ Next.js can start as a static site or even a strict SPA where everything is rend
## Build common SPA patterns ## Build common SPA patterns
The following examples cover common patterns for building an SPA with Next.js. The companion [demo](https://next-spa-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/next-spa-patterns)) shows each pattern in action. The following examples cover common patterns for building an SPA with Next.js. The companion [demo](https://next-spa-patterns.labs.vercel.dev) ([source](https://github.com/nextjs/next-spa-patterns)) shows each pattern in action.
### Using React's `use` within a Context Provider ### Using React's `use` within a Context Provider
...@@ -200,7 +200,7 @@ export default function Page() { ...@@ -200,7 +200,7 @@ export default function Page() {
The component that consumes the Promise (e.g. `Profile` above) suspends while the Promise resolves, so you see the streamed, prerendered HTML before JavaScript has finished loading. The component that consumes the Promise (e.g. `Profile` above) suspends while the Promise resolves, so you see the streamed, prerendered HTML before JavaScript has finished loading.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/use-context) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/use-context). See the [live demo](https://next-spa-patterns.labs.vercel.dev/use-context) and its [source code](https://github.com/nextjs/next-spa-patterns/tree/main/app/use-context).
### Rendering components only in the browser ### Rendering components only in the browser
...@@ -260,7 +260,7 @@ export default function Page() { ...@@ -260,7 +260,7 @@ export default function Page() {
In the browser, `browser()` returns `undefined`, and the editor renders with the saved draft. In the browser, `browser()` returns `undefined`, and the editor renders with the saved draft.
See both approaches in the [live demo](https://next-spa-patterns.labs.vercel.dev/browser-only). The [demo source](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/browser-only) contains the complete examples. See both approaches in the [live demo](https://next-spa-patterns.labs.vercel.dev/browser-only). The [demo source](https://github.com/nextjs/next-spa-patterns/tree/main/app/browser-only) contains the complete examples.
### Shallow routing on the client ### Shallow routing on the client
...@@ -318,7 +318,7 @@ export default function SortProducts() { ...@@ -318,7 +318,7 @@ export default function SortProducts() {
Learn more about how [routing and navigation](/docs/app/getting-started/linking-and-navigating#how-navigation-works) work in Next.js. Learn more about how [routing and navigation](/docs/app/getting-started/linking-and-navigating#how-navigation-works) work in Next.js.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/shallow-routing) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/shallow-routing). See the [live demo](https://next-spa-patterns.labs.vercel.dev/shallow-routing) and its [source code](https://github.com/nextjs/next-spa-patterns/tree/main/app/shallow-routing).
### Mutating data with Server Actions ### Mutating data with Server Actions
...@@ -569,7 +569,7 @@ export function TodoList({ initialTodos }) { ...@@ -569,7 +569,7 @@ export function TodoList({ initialTodos }) {
The optimistic update shows instantly, while `useActionState`'s pending flag lets you display a subtle indicator (such as `Syncing to server…`) until the Server Action resolves. The optimistic update shows instantly, while `useActionState`'s pending flag lets you display a subtle indicator (such as `Syncing to server…`) until the Server Action resolves.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/mutations) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/mutations). See the [live demo](https://next-spa-patterns.labs.vercel.dev/mutations) and its [source code](https://github.com/nextjs/next-spa-patterns/tree/main/app/mutations).
To learn more about adding interactivity on top of server-rendered apps so they feel like SPAs, see the [Building interactive apps](/docs/app/guides/interactive-apps) guide and its runnable demo. To learn more about adding interactivity on top of server-rendered apps so they feel like SPAs, see the [Building interactive apps](/docs/app/guides/interactive-apps) guide and its runnable demo.
......
...@@ -22,7 +22,7 @@ React's server renderer produces HTML in chunks aligned with `<Suspense>` bounda ...@@ -22,7 +22,7 @@ React's server renderer produces HTML in chunks aligned with `<Suspense>` bounda
## Example ## Example
The companion [streaming demo](https://streaming-demo.labs.vercel.dev/) ([source](https://github.com/vercel-labs/streaming-demo)) lets you see each concept from this guide in action: The companion [streaming demo](https://streaming-demo.labs.vercel.dev/) ([source](https://github.com/nextjs/streaming-demo)) lets you see each concept from this guide in action:
- Page-level streaming with `loading.tsx` (skeleton appears instantly, content streams in after ~2s) - Page-level streaming with `loading.tsx` (skeleton appears instantly, content streams in after ~2s)
- Granular streaming with sibling `<Suspense>` boundaries that resolve independently - Granular streaming with sibling `<Suspense>` boundaries that resolve independently
......
...@@ -2,6 +2,10 @@ ...@@ -2,6 +2,10 @@
title: How to set up Playwright with Next.js title: How to set up Playwright with Next.js
nav_title: Playwright nav_title: Playwright
description: Learn how to set up Playwright with Next.js for End-to-End (E2E) Testing. description: Learn how to set up Playwright with Next.js for End-to-End (E2E) Testing.
related:
description: Learn more about testing instant navigations.
links:
- app/guides/instant-navigation
--- ---
Playwright is a testing framework that lets you automate Chromium, Firefox, and WebKit with a single API. You can use it to write **End-to-End (E2E)** testing. This guide will show you how to set up Playwright with Next.js and write your first tests. Playwright is a testing framework that lets you automate Chromium, Firefox, and WebKit with a single API. You can use it to write **End-to-End (E2E)** testing. This guide will show you how to set up Playwright with Next.js and write your first tests.
...@@ -131,6 +135,14 @@ test('should navigate to the about page', async ({ page }) => { ...@@ -131,6 +135,14 @@ test('should navigate to the about page', async ({ page }) => {
> **Good to know**: You can use `page.goto("/")` instead of `page.goto("http://localhost:3000/")`, if you add [`"baseURL": "http://localhost:3000"`](https://playwright.dev/docs/api/class-testoptions#test-options-base-url) to the `playwright.config.ts` [configuration file](https://playwright.dev/docs/test-configuration). > **Good to know**: You can use `page.goto("/")` instead of `page.goto("http://localhost:3000/")`, if you add [`"baseURL": "http://localhost:3000"`](https://playwright.dev/docs/api/class-testoptions#test-options-base-url) to the `playwright.config.ts` [configuration file](https://playwright.dev/docs/test-configuration).
<AppOnly>
### Testing instant navigations
If you're using Cache Components, the `instant()` helper from `@next/playwright` lets you assert what is visible immediately after a navigation, before any dynamic content streams in. See the [Instant navigation guide](/docs/app/guides/instant-navigation) and the [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for setup and examples.
</AppOnly>
### Running your Playwright tests ### Running your Playwright tests
Playwright will simulate a user navigating your application using three browsers: Chromium, Firefox and WebKit, this requires your Next.js server to be running. We recommend running your tests against your production code to more closely resemble how your application will behave. Playwright will simulate a user navigating your application using three browsers: Chromium, Firefox and WebKit, this requires your Next.js server to be running. We recommend running your tests against your production code to more closely resemble how your application will behave.
......
...@@ -50,13 +50,26 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest ...@@ -50,13 +50,26 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest
## React 19 ## React 19
<AppOnly>
- The minimum versions of `react` and `react-dom` is now 19. - The minimum versions of `react` and `react-dom` is now 19.
</AppOnly>
<PagesOnly>
- The Pages Router supports both React 18 and React 19, so upgrading `react` and `react-dom` to 19 is optional.
</PagesOnly>
- `useFormState` has been replaced by `useActionState`. The `useFormState` hook is still available in React 19, but it is deprecated and will be removed in a future release. `useActionState` is recommended and includes additional properties like reading the `pending` state directly. [Learn more](https://react.dev/reference/react/useActionState). - `useFormState` has been replaced by `useActionState`. The `useFormState` hook is still available in React 19, but it is deprecated and will be removed in a future release. `useActionState` is recommended and includes additional properties like reading the `pending` state directly. [Learn more](https://react.dev/reference/react/useActionState).
- `useFormStatus` now includes additional keys like `data`, `method`, and `action`. If you are not using React 19, only the `pending` key is available. [Learn more](https://react.dev/reference/react-dom/hooks/useFormStatus). - `useFormStatus` now includes additional keys like `data`, `method`, and `action`. If you are not using React 19, only the `pending` key is available. [Learn more](https://react.dev/reference/react-dom/hooks/useFormStatus).
- Read more in the [React 19 upgrade guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide). - Read more in the [React 19 upgrade guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide).
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions. > **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions.
<AppOnly>
## Async Request APIs (Breaking change) ## Async Request APIs (Breaking change)
Previously synchronous Request-time APIs that rely on request information are now **asynchronous**: Previously synchronous Request-time APIs that rely on request information are now **asynchronous**:
...@@ -472,14 +485,10 @@ export async function GET(request, segmentData) { ...@@ -472,14 +485,10 @@ export async function GET(request, segmentData) {
} }
``` ```
<AppOnly>
## `runtime` configuration (Breaking change) ## `runtime` configuration (Breaking change)
The `runtime` [segment configuration](/docs/app/api-reference/file-conventions/route-segment-config/runtime) previously supported a value of `experimental-edge` in addition to `edge`. Both configurations refer to the same thing, and to simplify the options, we will now error if `experimental-edge` is used. To fix this, update your `runtime` configuration to `edge`. A [codemod](/docs/app/guides/upgrading/codemods#app-dir-runtime-config-experimental-edge) is available to automatically do this. The `runtime` [segment configuration](/docs/app/api-reference/file-conventions/route-segment-config/runtime) previously supported a value of `experimental-edge` in addition to `edge`. Both configurations refer to the same thing, and to simplify the options, we will now error if `experimental-edge` is used. To fix this, update your `runtime` configuration to `edge`. A [codemod](/docs/app/guides/upgrading/codemods#app-dir-runtime-config-experimental-edge) is available to automatically do this.
</AppOnly>
## `fetch` requests ## `fetch` requests
[`fetch` requests](/docs/app/api-reference/functions/fetch) are no longer cached by default. [`fetch` requests](/docs/app/api-reference/functions/fetch) are no longer cached by default.
...@@ -542,6 +551,8 @@ module.exports = nextConfig ...@@ -542,6 +551,8 @@ module.exports = nextConfig
[Layouts](/docs/app/api-reference/file-conventions/layout) and [loading states](/docs/app/api-reference/file-conventions/loading) are still cached and reused on navigation. [Layouts](/docs/app/api-reference/file-conventions/layout) and [loading states](/docs/app/api-reference/file-conventions/loading) are still cached and reused on navigation.
</AppOnly>
## `next/font` ## `next/font`
The `@next/font` package has been removed in favor of the built-in [`next/font`](/docs/app/api-reference/components/font). A [codemod is available](/docs/app/guides/upgrading/codemods#built-in-next-font) to safely and automatically rename your imports. The `@next/font` package has been removed in favor of the built-in [`next/font`](/docs/app/api-reference/components/font). A [codemod is available](/docs/app/guides/upgrading/codemods#built-in-next-font) to safely and automatically rename your imports.
...@@ -645,10 +656,15 @@ After applying the changes relevant to your app, review these action items befor ...@@ -645,10 +656,15 @@ After applying the changes relevant to your app, review these action items befor
you consider the migration complete: you consider the migration complete:
- [ ] React dependencies and types meet the React 19 requirements for the app's router. - [ ] React dependencies and types meet the React 19 requirements for the app's router.
- [ ] Async Request API access, including affected helpers and callers, is migrated. Resolve codemod error comments and `UnsafeUnwrapped` casts instead of treating them as completed repairs.
- [ ] Route segment runtime settings no longer use `experimental-edge`.
- [ ] Font imports use `next/font` instead of `@next/font`. - [ ] Font imports use `next/font` instead of `@next/font`.
- [ ] Existing `bundlePagesExternals` and `serverComponentsExternalPackages` settings use their documented stable names while preserving package configuration. - [ ] Existing `bundlePagesExternals` and `serverComponentsExternalPackages` settings use their documented stable names while preserving package configuration.
- [ ] `NextRequest` `geo` and `ip` consumers use an appropriate source for the actual hosting provider. - [ ] `NextRequest` `geo` and `ip` consumers use an appropriate source for the actual hosting provider.
- [ ] Apps that relied on automatic Speed Insights instrumentation have an explicit integration if they still need it. - [ ] Apps that relied on automatic Speed Insights instrumentation have an explicit integration if they still need it.
- [ ] The app's supported checks and affected runtime behavior pass. Remaining required failures keep the migration incomplete. - [ ] The app's supported checks and affected runtime behavior pass. Remaining required failures keep the migration incomplete.
<AppOnly>
- [ ] Async Request API access, including affected helpers and callers, is migrated. Resolve codemod error comments and `UnsafeUnwrapped` casts instead of treating them as completed repairs.
- [ ] Route segment runtime settings no longer use `experimental-edge`.
</AppOnly>
...@@ -254,6 +254,8 @@ export default nextConfig ...@@ -254,6 +254,8 @@ export default nextConfig
Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`, through `experimental.turbopackFileSystemCacheForDev` and `experimental.turbopackFileSystemCacheForBuild`. See [Turbopack FileSystem Caching](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable either one. Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`, through `experimental.turbopackFileSystemCacheForDev` and `experimental.turbopackFileSystemCacheForBuild`. See [Turbopack FileSystem Caching](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable either one.
<AppOnly>
## Async Request APIs (Breaking change) ## Async Request APIs (Breaking change)
Version 15 introduced [Async Request APIs](https://nextjs.org/docs/app/guides/upgrading/version-15#async-request-apis-breaking-change) as a breaking change, with **temporary** synchronous compatibility. Version 15 introduced [Async Request APIs](https://nextjs.org/docs/app/guides/upgrading/version-15#async-request-apis-breaking-change) as a breaking change, with **temporary** synchronous compatibility.
...@@ -368,6 +370,8 @@ The App Router in **Next.js 16** uses the latest React [Canary release](https:// ...@@ -368,6 +370,8 @@ The App Router in **Next.js 16** uses the latest React [Canary release](https://
Learn more in the [React 19.2 announcement](https://react.dev/blog/2025/10/01/react-19-2). Learn more in the [React 19.2 announcement](https://react.dev/blog/2025/10/01/react-19-2).
</AppOnly>
## React Compiler Support ## React Compiler Support
Built-in support for the React Compiler is now stable in **Next.js 16** following the React Compiler's 1.0 release. The React Compiler automatically memoizes components, reducing unnecessary re-renders with zero manual code changes. Built-in support for the React Compiler is now stable in **Next.js 16** following the React Compiler's 1.0 release. The React Compiler automatically memoizes components, reducing unnecessary re-renders with zero manual code changes.
...@@ -413,6 +417,8 @@ bun add -D babel-plugin-react-compiler ...@@ -413,6 +417,8 @@ bun add -D babel-plugin-react-compiler
> **Good to know:** Expect compile times in development and during builds to be higher when enabling this option as the React Compiler relies on Babel. > **Good to know:** Expect compile times in development and during builds to be higher when enabling this option as the React Compiler relies on Babel.
<AppOnly>
## Caching APIs ## Caching APIs
### revalidateTag ### revalidateTag
...@@ -585,6 +591,8 @@ const nextConfig = { ...@@ -585,6 +591,8 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
</AppOnly>
## `middleware` to `proxy` ## `middleware` to `proxy`
The `middleware` filename is deprecated, and has been renamed to `proxy` to clarify network boundary and routing focus. The `middleware` filename is deprecated, and has been renamed to `proxy` to clarify network boundary and routing focus.
...@@ -906,6 +914,8 @@ yarn next internal trace .next-profiles/trace-turbopack.bin ...@@ -906,6 +914,8 @@ yarn next internal trace .next-profiles/trace-turbopack.bin
bunx next internal trace .next-profiles/trace-turbopack.bin bunx next internal trace .next-profiles/trace-turbopack.bin
``` ```
<AppOnly>
## Parallel Routes `default.js` requirement ## Parallel Routes `default.js` requirement
All [parallel route](/docs/app/api-reference/file-conventions/parallel-routes) slots now require explicit `default.js` files. Builds will fail without them. All [parallel route](/docs/app/api-reference/file-conventions/parallel-routes) slots now require explicit `default.js` files. Builds will fail without them.
...@@ -928,6 +938,8 @@ export default function Default() { ...@@ -928,6 +938,8 @@ export default function Default() {
} }
``` ```
</AppOnly>
## ESLint Flat Config ## ESLint Flat Config
`@next/eslint-plugin-next` now defaults to ESLint Flat Config format, aligning with ESLint v10 which will drop legacy config support. `@next/eslint-plugin-next` now defaults to ESLint Flat Config format, aligning with ESLint v10 which will drop legacy config support.
...@@ -950,6 +962,8 @@ In **Next.js 16**, this behavior has changed. By default, Next.js will **no long ...@@ -950,6 +962,8 @@ In **Next.js 16**, this behavior has changed. By default, Next.js will **no long
**If you want Next.js to perform this override** (the previous default behavior), add the `data-scroll-behavior="smooth"` attribute to your `<html>` element: **If you want Next.js to perform this override** (the previous default behavior), add the `data-scroll-behavior="smooth"` attribute to your `<html>` element:
<AppOnly>
```tsx filename="app/layout.tsx" ```tsx filename="app/layout.tsx"
export default function RootLayout({ children }) { export default function RootLayout({ children }) {
return ( return (
...@@ -960,6 +974,28 @@ export default function RootLayout({ children }) { ...@@ -960,6 +974,28 @@ export default function RootLayout({ children }) {
} }
``` ```
</AppOnly>
<PagesOnly>
```tsx filename="pages/_document.tsx"
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en" data-scroll-behavior="smooth">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
</PagesOnly>
## Performance Improvements ## Performance Improvements
Significant performance optimizations for `next dev` and `next start` commands, along with improved terminal output with clearer formatting, better error messages, and improved performance metrics. Significant performance optimizations for `next dev` and `next start` commands, along with improved terminal output with clearer formatting, better error messages, and improved performance metrics.
...@@ -1175,6 +1211,8 @@ The following options have been removed from [`devIndicators`](/docs/app/api-ref ...@@ -1175,6 +1211,8 @@ The following options have been removed from [`devIndicators`](/docs/app/api-ref
The indicator itself remains available. The indicator itself remains available.
<AppOnly>
### `experimental.dynamicIO` and `experimental.useCache` ### `experimental.dynamicIO` and `experimental.useCache`
The `experimental.dynamicIO` and `experimental.useCache` flags have been removed. The `experimental.dynamicIO` and `experimental.useCache` flags have been removed.
...@@ -1225,6 +1263,8 @@ For the full migration path, see [Migrating to Cache Components](/docs/app/guide ...@@ -1225,6 +1263,8 @@ For the full migration path, see [Migrating to Cache Components](/docs/app/guide
The `unstable_rootParams` function has been removed. Use [`next/root-params`](/docs/app/api-reference/functions/next-root-params) instead. The `unstable_rootParams` function has been removed. Use [`next/root-params`](/docs/app/api-reference/functions/next-root-params) instead.
</AppOnly>
## Troubleshooting ## Troubleshooting
### Installation fails after upgrading to React 19 ### Installation fails after upgrading to React 19
...@@ -1233,7 +1273,7 @@ The `unstable_rootParams` function has been removed. Use [`next/root-params`](/d ...@@ -1233,7 +1273,7 @@ The `unstable_rootParams` function has been removed. Use [`next/root-params`](/d
### Installation fails after upgrading ESLint ### Installation fails after upgrading ESLint
Next.js 16 removes `next lint`, but migrating to the ESLint CLI does not require upgrading ESLint. `eslint-config-next@16` requires ESLint 9; an existing compatible lint configuration can use an older version. Next.js 16 removes `next lint`, but migrating to the ESLint CLI does not require upgrading ESLint. `eslint-config-next@16` requires ESLint 9 or later, and `eslint-config-next@16.4.0` or later supports ESLint 10. If your existing lint configuration does not use `eslint-config-next@16`, you can keep its compatible ESLint version.
- [ ] If an ESLint upgrade causes peer dependency conflicts, restore the previous compatible versions of `eslint`, `eslint-config-next`, and `@next/eslint-plugin-next` (if present), along with the previous lint configuration. - [ ] If an ESLint upgrade causes peer dependency conflicts, restore the previous compatible versions of `eslint`, `eslint-config-next`, and `@next/eslint-plugin-next` (if present), along with the previous lint configuration.
- [ ] If installation interrupted the upgrade, retry the same exact target with `--skip-eslint-upgrade` to preserve the repaired lint stack and skip the lint codemod. If Next.js already matches the target, install dependencies and complete interrupted migrations individually. Replace `next lint` scripts with ESLint CLI commands compatible with the preserved configuration. Confirm installation and lint pass. - [ ] If installation interrupted the upgrade, retry the same exact target with `--skip-eslint-upgrade` to preserve the repaired lint stack and skip the lint codemod. If Next.js already matches the target, install dependencies and complete interrupted migrations individually. Replace `next lint` scripts with ESLint CLI commands compatible with the preserved configuration. Confirm installation and lint pass.
...@@ -1244,13 +1284,18 @@ After applying the changes relevant to your app, review these action items befor ...@@ -1244,13 +1284,18 @@ After applying the changes relevant to your app, review these action items befor
you consider the migration complete: you consider the migration complete:
- [ ] The app meets the Node.js, TypeScript, and React requirements in this guide. - [ ] The app meets the Node.js, TypeScript, and React requirements in this guide.
- [ ] Async Request API access and affected callers are migrated. Resolve codemod error comments and `UnsafeUnwrapped` casts; use React `use` for synchronous Client Components where appropriate.
- [ ] Dynamic metadata image functions and sitemap functions handle their asynchronous parameters, and affected generated URLs work.
- [ ] Development and build scripts agree with the effective bundler configuration, including plugins, loaders, aliases, and affected Sass imports. - [ ] Development and build scripts agree with the effective bundler configuration, including plugins, loaders, aliases, and affected Sass imports.
- [ ] Middleware and proxy changes preserve the required runtime and routing behavior. Edge middleware is not blindly renamed to proxy. - [ ] Middleware and proxy changes preserve the required runtime and routing behavior. Edge middleware is not blindly renamed to proxy.
- [ ] Parallel route slots have appropriate defaults, and direct navigation and reloads retain the intended fallback behavior.
- [ ] Affected image requests succeed under the documented restrictions and defaults while preserving the intended quality. - [ ] Affected image requests succeed under the documented restrictions and defaults while preserving the intended quality.
- [ ] Existing cache API calls follow the documented signatures and semantics. React Compiler and Cache Components are not enabled merely to complete the upgrade. - [ ] Existing cache API calls follow the documented signatures and semantics. React Compiler and Cache Components are not enabled merely to complete the upgrade.
- [ ] Removed APIs and configuration have no remaining consumers. Runtime configuration replacements preserve server and client visibility and the required evaluation time. - [ ] Removed APIs and configuration have no remaining consumers. Runtime configuration replacements preserve server and client visibility and the required evaluation time.
- [ ] Scripts and CI no longer invoke `next lint`; linting runs separately where the app requires it. - [ ] Scripts and CI no longer invoke `next lint`; linting runs separately where the app requires it.
- [ ] The app's supported checks and affected runtime behavior pass. A green build alone does not close runtime findings. - [ ] The app's supported checks and affected runtime behavior pass. A green build alone does not close runtime findings.
<AppOnly>
- [ ] Async Request API access and affected callers are migrated. Resolve codemod error comments and `UnsafeUnwrapped` casts; use React `use` for synchronous Client Components where appropriate.
- [ ] Dynamic metadata image functions and sitemap functions handle their asynchronous parameters, and affected generated URLs work.
- [ ] Parallel route slots have appropriate defaults, and direct navigation and reloads retain the intended fallback behavior.
</AppOnly>
...@@ -45,7 +45,7 @@ We'll start by morphing a thumbnail into a hero image (shared elements), then an ...@@ -45,7 +45,7 @@ We'll start by morphing a thumbnail into a hero image (shared elements), then an
You can find the resources used in this example here: You can find the resources used in this example here:
- [Demo](https://react-view-transitions-demo.labs.vercel.dev) - [Demo](https://react-view-transitions-demo.labs.vercel.dev)
- [Code](https://github.com/vercel-labs/react-view-transitions-demo) - [Code](https://github.com/nextjs/react-view-transitions-demo)
View transitions work in the App Router with no configuration. React 19.3 includes the `<ViewTransition>` component and `addTransitionType` API used in this guide. View transitions work in the App Router with no configuration. React 19.3 includes the `<ViewTransition>` component and `addTransitionType` API used in this guide.
...@@ -440,4 +440,4 @@ For API details and more patterns: ...@@ -440,4 +440,4 @@ For API details and more patterns:
- [Link `transitionTypes` prop](/docs/app/api-reference/components/link#transitiontypes) - [Link `transitionTypes` prop](/docs/app/api-reference/components/link#transitiontypes)
- [`useRouter`](/docs/app/api-reference/functions/use-router), which also supports `transitionTypes` in `push()` and `replace()` - [`useRouter`](/docs/app/api-reference/functions/use-router), which also supports `transitionTypes` in `push()` and `replace()`
- [React `ViewTransition` component](https://react.dev/reference/react/ViewTransition) - [React `ViewTransition` component](https://react.dev/reference/react/ViewTransition)
- [Complete CSS from this guide](https://github.com/vercel-labs/react-view-transitions-demo/blob/main/src/app/globals.css) — all keyframes and view transition rules in one file - [Complete CSS from this guide](https://github.com/nextjs/react-view-transitions-demo/blob/main/src/app/globals.css) — all keyframes and view transition rules in one file
...@@ -11,7 +11,7 @@ related: ...@@ -11,7 +11,7 @@ related:
- app/api-reference/functions/cacheTag - app/api-reference/functions/cacheTag
--- ---
The `'use cache: private'` directive allows functions to access runtime request APIs like `cookies()`, `headers()`, and `searchParams` within a cached scope. In production, matching calls within one request can reuse the same result, but Next.js does not store it in a server cache across requests. The `'use cache: private'` directive allows functions to access runtime request APIs like `cookies()`, `headers()`, and `searchParams` within a cached scope. In production, matching calls within one request can reuse the same result, but Next.js does not store it in a server cache across requests. In development, Next.js stores it in memory, keyed by the request's cookies and headers, and serves it to the next matching request while a fresh result is generated in the background.
The client router can keep the rendered output in browser memory for the [`stale` time](/docs/app/api-reference/functions/cacheLife#client-cache-behavior) configured with `cacheLife`. This client-side cache does not persist across page reloads. The client router can keep the rendered output in browser memory for the [`stale` time](/docs/app/api-reference/functions/cacheLife#client-cache-behavior) configured with `cacheLife`. This client-side cache does not persist across page reloads.
......
...@@ -21,4 +21,5 @@ export const runtime = 'nodejs' ...@@ -21,4 +21,5 @@ export const runtime = 'nodejs'
> **Good to know**: > **Good to know**:
> >
> - The Edge Runtime is deprecated. Remove the `runtime` export from your route files. See [Edge Runtime Deprecated](/docs/messages/edge-runtime-deprecated). > - The Edge Runtime is deprecated. Remove the `runtime` export from your route files. See [Edge Runtime Deprecated](/docs/messages/edge-runtime-deprecated).
> - When [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled, remove the `runtime` export, including `runtime = 'nodejs'`. Cache Components uses the default Node.js runtime and does not support the `runtime` route segment config. See [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components#runtime--edge).
> - This option cannot be used in [Proxy](/docs/app/api-reference/file-conventions/proxy). > - This option cannot be used in [Proxy](/docs/app/api-reference/file-conventions/proxy).
...@@ -26,7 +26,7 @@ export default function Error({ ...@@ -26,7 +26,7 @@ export default function Error({
error, error,
retry, retry,
}: { }: {
error: Error & { digest?: string } error: unknown
retry: () => void retry: () => void
}) { }) {
useEffect(() => { useEffect(() => {
...@@ -101,7 +101,7 @@ In the [component hierarchy](/docs/app/getting-started/project-structure#compone ...@@ -101,7 +101,7 @@ In the [component hierarchy](/docs/app/getting-started/project-structure#compone
#### `error` #### `error`
An instance of an [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) object forwarded to the `error.js` Client Component. The value that was thrown, forwarded to the `error.js` Client Component. Errors from Server Components arrive as an [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) instance, while a value thrown in a Client Component is passed as-is and may not be an `Error`. Narrow it, for example with `instanceof Error`, before reading properties like `message` or `digest`.
> **Good to know:** During development, the `Error` object forwarded to the client will be serialized and include the `message` of the original error for easier debugging. However, **this behavior is different in production** to avoid leaking potentially sensitive details included in the error to the client. > **Good to know:** During development, the `Error` object forwarded to the client will be serialized and include the `message` of the original error for easier debugging. However, **this behavior is different in production** to avoid leaking potentially sensitive details included in the error to the client.
...@@ -127,7 +127,7 @@ export default function Error({ ...@@ -127,7 +127,7 @@ export default function Error({
error, error,
retry, retry,
}: { }: {
error: Error & { digest?: string } error: unknown
retry: () => void retry: () => void
}) { }) {
return ( return (
...@@ -173,7 +173,7 @@ export default function GlobalError({ ...@@ -173,7 +173,7 @@ export default function GlobalError({
error, error,
retry, retry,
}: { }: {
error: Error & { digest?: string } error: unknown
retry: () => void retry: () => void
}) { }) {
return ( return (
......
...@@ -76,7 +76,7 @@ Consider the following UI pattern, where a user can open a photo modal from a ga ...@@ -76,7 +76,7 @@ Consider the following UI pattern, where a user can open a photo modal from a ga
In the above example, the path to the `photo` segment can use the `(..)` matcher since `@modal` is a slot and **not** a segment. This means that the `photo` route is only one segment level higher, despite being two file-system levels higher. In the above example, the path to the `photo` segment can use the `(..)` matcher since `@modal` is a slot and **not** a segment. This means that the `photo` route is only one segment level higher, despite being two file-system levels higher.
See the [Parallel Routes](/docs/app/api-reference/file-conventions/parallel-routes#modals) documentation for a step-by-step example, or see our [image gallery example](https://github.com/vercel-labs/nextgram). See the [Parallel Routes](/docs/app/api-reference/file-conventions/parallel-routes#modals) documentation for a step-by-step example, or see our [image gallery example](https://github.com/nextjs/nextgram).
> **Good to know:** > **Good to know:**
> >
......
...@@ -484,7 +484,7 @@ export default function CatchAll() { ...@@ -484,7 +484,7 @@ export default function CatchAll() {
> >
> - We use a catch-all route in our `@auth` slot to close the modal because of how parallel routes behave. Since client-side navigations to a route that no longer match the slot will remain visible, we need to match the slot to a route that returns `null` to close the modal. > - We use a catch-all route in our `@auth` slot to close the modal because of how parallel routes behave. Since client-side navigations to a route that no longer match the slot will remain visible, we need to match the slot to a route that returns `null` to close the modal.
> - Other examples could include opening a photo modal in a gallery while also having a dedicated `/photo/[id]` page, or opening a shopping cart in a side modal. > - Other examples could include opening a photo modal in a gallery while also having a dedicated `/photo/[id]` page, or opening a shopping cart in a side modal.
> - [View an example](https://github.com/vercel-labs/nextgram) of modals with Intercepted and Parallel Routes. > - [View an example](https://github.com/nextjs/nextgram) of modals with Intercepted and Parallel Routes.
### Loading and Error UI ### Loading and Error UI
......
...@@ -26,10 +26,12 @@ Compared to a custom React error boundary, `catchError` is designed to work with ...@@ -26,10 +26,12 @@ Compared to a custom React error boundary, `catchError` is designed to work with
import { catchError, type ErrorInfo } from 'next/error' import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, retry }: ErrorInfo) { function ErrorFallback(props: { title: string }, { error, retry }: ErrorInfo) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
</div> </div>
) )
...@@ -44,10 +46,12 @@ export default catchError(ErrorFallback) ...@@ -44,10 +46,12 @@ export default catchError(ErrorFallback)
import { catchError } from 'next/error' import { catchError } from 'next/error'
function ErrorFallback(props, { error, retry }) { function ErrorFallback(props, { error, retry }) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
</div> </div>
) )
...@@ -71,10 +75,12 @@ Compared to a custom React error boundary, `catchError` is designed to work with ...@@ -71,10 +75,12 @@ Compared to a custom React error boundary, `catchError` is designed to work with
import { catchError, type ErrorInfo } from 'next/error' import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, reset }: ErrorInfo) { function ErrorFallback(props: { title: string }, { error, reset }: ErrorInfo) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => reset()}>Try again</button> <button onClick={() => reset()}>Try again</button>
</div> </div>
) )
...@@ -87,10 +93,12 @@ export default catchError(ErrorFallback) ...@@ -87,10 +93,12 @@ export default catchError(ErrorFallback)
import { catchError } from 'next/error' import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) { function ErrorFallback(props, { error, reset }) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<h2>{props.title}</h2> <h2>{props.title}</h2>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => reset()}>Try again</button> <button onClick={() => reset()}>Try again</button>
</div> </div>
) )
...@@ -120,11 +128,11 @@ A function that renders the error UI when an error is caught. It receives two ar ...@@ -120,11 +128,11 @@ A function that renders the error UI when an error is caught. It receives two ar
<AppOnly> <AppOnly>
| Property | Type | Description | | Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | -------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. | | `error` | `unknown` | The value that was thrown. Narrow it, for example with `instanceof Error`, before reading properties like `message`. |
| `retry` | `() => void` | Re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result. | | `retry` | `() => void` | Re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result. |
| `reset` | `() => void` | Resets the error state and re-renders without re-fetching. Use [`retry()`](/docs/app/api-reference/file-conventions/error#retry) in most cases. | | `reset` | `() => void` | Resets the error state and re-renders without re-fetching. Use [`retry()`](/docs/app/api-reference/file-conventions/error#retry) in most cases. |
The `fallback` function must be a Client Component (or defined in a `'use client'` module). The `fallback` function must be a Client Component (or defined in a `'use client'` module).
...@@ -132,10 +140,10 @@ The `fallback` function must be a Client Component (or defined in a `'use client ...@@ -132,10 +140,10 @@ The `fallback` function must be a Client Component (or defined in a `'use client
<PagesOnly> <PagesOnly>
| Property | Type | Description | | Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | -------- | ------------ | -------------------------------------------------------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. | | `error` | `unknown` | The value that was thrown. Narrow it, for example with `instanceof Error`, before reading properties like `message`. |
| `reset` | `() => void` | Resets the error state and re-renders the error boundary's children. | | `reset` | `() => void` | Resets the error state and re-renders the error boundary's children. |
</PagesOnly> </PagesOnly>
...@@ -207,9 +215,11 @@ In most cases, use `retry()` instead of `reset()`. The `reset()` function only c ...@@ -207,9 +215,11 @@ In most cases, use `retry()` instead of `reset()`. The `reset()` function only c
import { catchError, type ErrorInfo } from 'next/error' import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: {}, { error, retry, reset }: ErrorInfo) { function ErrorFallback(props: {}, { error, retry, reset }: ErrorInfo) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
<button onClick={() => reset()}>Reset</button> <button onClick={() => reset()}>Reset</button>
</div> </div>
...@@ -225,9 +235,11 @@ export default catchError(ErrorFallback) ...@@ -225,9 +235,11 @@ export default catchError(ErrorFallback)
import { catchError } from 'next/error' import { catchError } from 'next/error'
function ErrorFallback(props, { error, retry, reset }) { function ErrorFallback(props, { error, retry, reset }) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => retry()}>Try again</button> <button onClick={() => retry()}>Try again</button>
<button onClick={() => reset()}>Reset</button> <button onClick={() => reset()}>Reset</button>
</div> </div>
...@@ -247,9 +259,11 @@ Use `reset()` to prompt the user to recover from the error. When called, the fun ...@@ -247,9 +259,11 @@ Use `reset()` to prompt the user to recover from the error. When called, the fun
import { catchError, type ErrorInfo } from 'next/error' import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: {}, { error, reset }: ErrorInfo) { function ErrorFallback(props: {}, { error, reset }: ErrorInfo) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => reset()}>Try again</button> <button onClick={() => reset()}>Try again</button>
</div> </div>
) )
...@@ -262,9 +276,11 @@ export default catchError(ErrorFallback) ...@@ -262,9 +276,11 @@ export default catchError(ErrorFallback)
import { catchError } from 'next/error' import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) { function ErrorFallback(props, { error, reset }) {
const message = error instanceof Error ? error.message : String(error)
return ( return (
<div> <div>
<p>{error.message}</p> <p>{message}</p>
<button onClick={() => reset()}>Try again</button> <button onClick={() => reset()}>Try again</button>
</div> </div>
) )
......
--- ---
title: navigation title: navigation
nav_title: navigation() nav_title: navigation
description: Defer runtime work until the user navigates with the navigation function. description: Defer runtime work until the user navigates with the navigation function.
related: related:
links: links:
......
--- ---
title: prefetch title: prefetch
nav_title: prefetch() nav_title: prefetch
description: Defer runtime work until a per-link prefetch or navigation with the prefetch function. description: Defer runtime work until a per-link prefetch or navigation with the prefetch function.
related: related:
links: links:
......
...@@ -28,7 +28,7 @@ export default nextConfig ...@@ -28,7 +28,7 @@ export default nextConfig
Set `partialPrefetching` explicitly. Leaving it unset logs a warning, because the first release of Cache Components did not include Partial Prefetching. Set it to `false` only while [migrating an app that adopted Cache Components before Partial Prefetching](/docs/app/guides/adopting-partial-prefetching). Both features will be enabled everywhere in the next major release, and the options will be removed. Set `partialPrefetching` explicitly. Leaving it unset logs a warning, because the first release of Cache Components did not include Partial Prefetching. Set it to `false` only while [migrating an app that adopted Cache Components before Partial Prefetching](/docs/app/guides/adopting-partial-prefetching). Both features will be enabled everywhere in the next major release, and the options will be removed.
> **Good to know**: Cache Components requires the Node.js runtime. Migrate any routes that set the deprecated `runtime = 'edge'` export, and note that other server-side JavaScript runtimes are not guaranteed to work. See [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components#runtime--edge). > **Good to know**: Cache Components requires the Node.js runtime and does not support the [`runtime` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/runtime). Remove any `runtime` export, including `runtime = 'nodejs'` and the deprecated `runtime = 'edge'`. Other server-side JavaScript runtimes are not guaranteed to work. See [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components#runtime--edge).
When `cacheComponents` is enabled, you can use the following cache functions and configurations: When `cacheComponents` is enabled, you can use the following cache functions and configurations:
......
...@@ -270,25 +270,39 @@ Called when tags are revalidated or expired. ...@@ -270,25 +270,39 @@ Called when tags are revalidated or expired.
updateTags(tags: string[], durations?: { expire?: number }): Promise<void> updateTags(tags: string[], durations?: { expire?: number }): Promise<void>
``` ```
| Parameter | Type | Description | | Parameter | Type | Description |
| ----------- | --------------------- | ---------------------------------------- | | ----------- | --------------------- | ------------------------------------------------------------------------------- |
| `tags` | `string[]` | Array of tags to update. | | `tags` | `string[]` | Array of tags to update. |
| `durations` | `{ expire?: number }` | Optional expiration duration in seconds. | | `durations` | `{ expire?: number }` | Present for profile-based revalidation; carries the profile's `expire` seconds. |
Your handler should update its internal state to mark these tags as invalidated. Your handler should update its internal state to mark these tags as invalidated.
Whether `durations` is present tells you which kind of invalidation this is:
- **Absent**: invalidate immediately. Entries carrying these tags should not be served again. `updateTag()` and a single-argument `revalidateTag()` take this path, and the caller expects its own next read to miss.
- **Present**: the tags go stale now, but entries carrying them may still be served while they refresh in the background, until `durations.expire` seconds have passed. `revalidateTag(tag, 'max')` takes this path.
Returns `Promise<void>`. Returns `Promise<void>`.
When tags are revalidated, your handler should invalidate all cache entries that have any of those tags. Iterate through your cache and remove entries whose tags match the provided list. Your handler should record when each tag was invalidated. [`get()`](#get) compares those times against an entry's `timestamp`, and [`getExpiration()`](#getexpiration) does the same for [soft tags](#soft-tags). Soft tags are not stored in an entry's `tags`, so deleting the entries that carry a tag does not cover [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath).
```js ```js
const cacheHandler = { const cacheHandler = {
async updateTags(tags, durations) { async updateTags(tags, durations) {
// Invalidate all cache entries with matching tags const now = Date.now()
for (const [key, entry] of cache.entries()) { for (const tag of tags) {
if (entry.tags.some((tag) => tags.includes(tag))) { const timestamps = tagTimestamps.get(tag) ?? {}
cache.delete(key) if (durations) {
// Serve while refreshing, and expire after `durations.expire` seconds
timestamps.stale = now
if (durations.expire !== undefined) {
timestamps.expired = now + durations.expire * 1000
}
} else {
// Expire immediately
timestamps.expired = now
} }
tagTimestamps.set(tag, timestamps)
} }
}, },
} }
...@@ -370,14 +384,18 @@ Cache operations should be implemented defensively: ...@@ -370,14 +384,18 @@ Cache operations should be implemented defensively:
## Examples ## Examples
### Basic in-memory cache handler The examples below show how a handler meets the API contract. They leave out the eviction, error handling, and multi-instance coordination that a production handler must add. The [`cache-handler-redis` example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis) is a fuller Redis implementation of both cache APIs, and its README lists community handlers that cover more cases.
### In-memory handler for learning and debugging
Here's a minimal implementation using a `Map` for storage. This example demonstrates the core concepts, but for a production-ready implementation with LRU eviction, error handling, and tag management, see the [default cache handler](https://github.com/vercel/next.js/blob/canary/packages/next/src/server/lib/cache-handlers/default.ts). This handler keeps entries in a `Map`, which makes it a place to log or inspect what Next.js stores and how tags invalidate it. It runs per process and has no eviction. The [built-in handler](https://github.com/vercel/next.js/blob/canary/packages/next/src/server/lib/cache-handlers/default.ts) is also in memory, and adds a size-bounded LRU and error handling.
```js filename="cache-handlers/memory-handler.js" ```js filename="cache-handlers/memory-handler.js"
// Entries hold the serialized bytes, never the stream they arrived on // Entries hold the serialized bytes, never the stream they arrived on
const cache = new Map() const cache = new Map()
const pendingSets = new Map() const pendingSets = new Map()
// Tag invalidation times in milliseconds: { stale, expired }
const tagTimestamps = new Map()
function streamFromBytes(bytes) { function streamFromBytes(bytes) {
return new ReadableStream({ return new ReadableStream({
...@@ -402,10 +420,21 @@ module.exports = { ...@@ -402,10 +420,21 @@ module.exports = {
} }
// No age check: Next.js compares `timestamp` against `expire` itself. // No age check: Next.js compares `timestamp` against `expire` itself.
// Soft tags are checked by Next.js through `getExpiration()`.
// This `Map` also has no eviction, which a real handler needs. // This `Map` also has no eviction, which a real handler needs.
let revalidate = entry.revalidate
for (const tag of entry.tags) {
const { stale = 0, expired = 0 } = tagTimestamps.get(tag) ?? {}
if (expired > entry.timestamp && expired <= Date.now()) {
return undefined
}
if (stale > entry.timestamp) {
revalidate = -1
}
}
// Every hit gets its own stream over the stored bytes // Every hit gets its own stream over the stored bytes
return { ...entry, value: streamFromBytes(entry.value) } return { ...entry, revalidate, value: streamFromBytes(entry.value) }
}, },
async set(cacheKey, pendingEntry) { async set(cacheKey, pendingEntry) {
...@@ -434,20 +463,31 @@ module.exports = { ...@@ -434,20 +463,31 @@ module.exports = {
}, },
async refreshTags() { async refreshTags() {
// No-op for in-memory cache // Tag state lives in this process, so there is nothing to sync
}, },
async getExpiration(tags) { async getExpiration(tags) {
// Return 0 to indicate no tags have been revalidated return Math.max(
return 0 ...tags.map((tag) => tagTimestamps.get(tag)?.expired ?? 0),
0
)
}, },
async updateTags(tags, durations) { async updateTags(tags, durations) {
// Implement tag-based invalidation const now = Date.now()
for (const [key, entry] of cache.entries()) { for (const tag of tags) {
if (entry.tags.some((tag) => tags.includes(tag))) { const timestamps = tagTimestamps.get(tag) ?? {}
cache.delete(key) if (durations) {
// Serve while refreshing, and expire after `durations.expire` seconds
timestamps.stale = now
if (durations.expire !== undefined) {
timestamps.expired = now + durations.expire * 1000
}
} else {
// Expire immediately
timestamps.expired = now
} }
tagTimestamps.set(tag, timestamps)
} }
}, },
} }
...@@ -455,7 +495,7 @@ module.exports = { ...@@ -455,7 +495,7 @@ module.exports = {
### External storage pattern ### External storage pattern
For durable storage like Redis or a database, you'll need to serialize the cache entries. Here's a simple Redis example: A handler backed by Redis or a database must serialize each entry. Drain the stream in `set()`, and rebuild one from the stored bytes in `get()`:
```js filename="cache-handlers/redis-handler.js" ```js filename="cache-handlers/redis-handler.js"
const { createClient } = require('redis') const { createClient } = require('redis')
...@@ -518,25 +558,17 @@ module.exports = { ...@@ -518,25 +558,17 @@ module.exports = {
expire: entry.expire, expire: entry.expire,
revalidate: entry.revalidate, revalidate: entry.revalidate,
}), }),
{ EX: entry.expire } // Use Redis TTL for automatic expiration // `EX` needs a positive integer.
// By definition `expire: Infinity` ("never expire")
// maps to no TTL at all, so omit `EX` and let Redis persist the key.
Number.isFinite(entry.expire)
? { EX: Math.max(1, Math.ceil(entry.expire)) }
: {}
) )
}, },
async refreshTags() { // refreshTags(), getExpiration(), and updateTags() also need shared state.
// No-op for basic Redis implementation // See Distributed Tag Coordination for that half of the handler.
// Could sync with external tag service if needed
},
async getExpiration(tags) {
// Return 0 to indicate no tags have been revalidated
// Could query Redis for tag expiration timestamps if tracking them
return 0
},
async updateTags(tags, durations) {
// Implement tag-based invalidation if needed
// Could iterate over keys with matching tags and delete them
},
} }
``` ```
......
...@@ -15,7 +15,7 @@ module.exports = { ...@@ -15,7 +15,7 @@ module.exports = {
} }
``` ```
View an example of a [custom cache handler](/docs/app/guides/self-hosting#configuring-caching) and learn more about the implementation. See the [Redis `cacheHandler` example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis) for a working implementation, and [Configuring Caching](/docs/app/guides/self-hosting#configuring-caching) for what a handler backed by a shared store needs.
## API Reference ## API Reference
......
...@@ -65,7 +65,7 @@ Since this is only logged in development, this option doesn't affect production ...@@ -65,7 +65,7 @@ Since this is only logged in development, this option doesn't affect production
module.exports = { module.exports = {
logging: { logging: {
incomingRequests: { incomingRequests: {
ignore: [/\api\/v1\/health/], ignore: [/\/api\/v1\/health/],
}, },
}, },
} }
......
...@@ -78,7 +78,11 @@ Get linting working quickly with the ESLint CLI (flat config): ...@@ -78,7 +78,11 @@ Get linting working quickly with the ESLint CLI (flat config):
bunx eslint . bunx eslint .
``` ```
> **Good to know**: `eslint-config-next` supports ESLint 9 and ESLint 10. ESLint 10 requires Node.js `^20.19.0`, `^22.13.0`, or `>=24`. Some of the plugins included in `eslint-config-next` don't list ESLint 10 in their peer dependencies yet, so your package manager may show peer dependency warnings, or fail when strict peer dependencies are enabled. > **Good to know**:
>
> - `eslint-config-next` supports ESLint 9 and ESLint 10. ESLint 10 requires Node.js `^20.19.0`, `^22.13.0`, or `>=24`.
> - Starting with `eslint-config-next@16.4.0`, the default React version detection works with ESLint 10. You can remove a `settings.react.version` override added as a workaround for a `context.getFilename` error.
> - Some of the plugins included in `eslint-config-next` don't list ESLint 10 in their peer dependencies yet, so your package manager may show peer dependency warnings, or fail when strict peer dependencies are enabled.
## Reference ## Reference
...@@ -384,4 +388,5 @@ When you spread `...nextConfig`, you're adding multiple config objects that incl ...@@ -384,4 +388,5 @@ When you spread `...nextConfig`, you're adding multiple config objects that incl
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v16.4.0` | `eslint-config-next` added ESLint 10 compatibility, including support for default React version detection. |
| `v16.0.0` | `next lint` and the `eslint` next.config.js option were removed in favor of the ESLint CLI. A [codemod](/docs/app/guides/upgrading/codemods#migrate-from-next-lint-to-eslint-cli) is available to help you migrate. | | `v16.0.0` | `next lint` and the `eslint` next.config.js option were removed in favor of the ESLint CLI. A [codemod](/docs/app/guides/upgrading/codemods#migrate-from-next-lint-to-eslint-cli) is available to help you migrate. |
...@@ -434,6 +434,7 @@ The generated `.cpuprofile` files can be opened in Chrome DevTools (Performance ...@@ -434,6 +434,7 @@ The generated `.cpuprofile` files can be opened in Chrome DevTools (Performance
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------- |
| `v16.4.0` | Add the `next analyze export` command. |
| `v16.1.0` | Add the `next upgrade` command | | `v16.1.0` | Add the `next upgrade` command |
| `v16.1.0` | Add the `next experimental-analyze` command | | `v16.1.0` | Add the `next experimental-analyze` command |
| `v16.0.0` | The JS bundle size metrics have been removed from `next build` | | `v16.0.0` | The JS bundle size metrics have been removed from `next build` |
......
---
title: How to upgrade to version 15
nav_title: Version 15
description: Upgrade your Next.js Application from Version 14 to 15.
source: app/guides/upgrading/version-15
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: How to upgrade to version 16
nav_title: Version 16
description: Upgrade your Next.js Application from Version 15 to 16.
source: app/guides/upgrading/version-16
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -239,11 +239,11 @@ export default async function handler(req, res) { ...@@ -239,11 +239,11 @@ export default async function handler(req, res) {
} }
``` ```
### Sending a HTTP response ### Sending an HTTP response
Sending an HTTP response works the same way as when sending a JSON response. The only difference is that the response body can be a `string`, an `object` or a `Buffer`. Sending an HTTP response works the same way as when sending a JSON response. The only difference is that the response body can be a `string`, an `object` or a `Buffer`.
The following example sends a HTTP response with the status code `200` (`OK`) and the result of the async operation. The following example sends an HTTP response with the status code `200` (`OK`) and the result of the async operation.
```ts filename="pages/api/hello.ts" switcher ```ts filename="pages/api/hello.ts" switcher
import type { NextApiRequest, NextApiResponse } from 'next' import type { NextApiRequest, NextApiResponse } from 'next'
......
...@@ -60,7 +60,7 @@ Handles client-side transitions, this method is useful for cases where [`next/li ...@@ -60,7 +60,7 @@ Handles client-side transitions, this method is useful for cases where [`next/li
router.push(url, as, options) router.push(url, as, options)
``` ```
- `url`: `UrlObject | String` - The URL to navigate to (see [Node.JS URL module documentation](https://nodejs.org/api/url.html#legacy-urlobject) for `UrlObject` properties). - `url`: `UrlObject | String` - The URL to navigate to (see [Node.js URL module documentation](https://nodejs.org/api/url.html#legacy-urlobject) for `UrlObject` properties).
- `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes. - `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes.
- `options` - Optional object with the following configuration options: - `options` - Optional object with the following configuration options:
- `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true`
...@@ -298,7 +298,7 @@ router.beforePopState(cb) ...@@ -298,7 +298,7 @@ router.beforePopState(cb)
If `cb` returns `false`, the Next.js router will not handle `popstate`, and you'll be responsible for handling it in that case. See [Disabling file-system routing](/docs/pages/guides/custom-server#disabling-file-system-routing). If `cb` returns `false`, the Next.js router will not handle `popstate`, and you'll be responsible for handling it in that case. See [Disabling file-system routing](/docs/pages/guides/custom-server#disabling-file-system-routing).
You could use `beforePopState` to manipulate the request, or force a SSR refresh, as in the following example: You could use `beforePopState` to manipulate the request, or force an SSR refresh, as in the following example:
```jsx ```jsx
import { useEffect } from 'react' import { useEffect } from 'react'
......
# dependencies
/node_modules
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# typescript
next-env.d.ts
# Next.js Redis Cache Integration Example (Turbo Redis Cache)
This example shows a production Redis cache for self-hosted Next.js using
[`@trieb.work/nextjs-turbo-redis-cache`](https://www.npmjs.com/package/@trieb.work/nextjs-turbo-redis-cache).
The [`cache-handler-redis`](../cache-handler-redis) example is the canonical
no-dependency starting point: both Next.js cache APIs against the `redis`
client directly. Use this example when you want a maintained package with GET
timeouts, request coalescing, an in-memory tag map, key-space notifications,
and TLS / multi-instance ops knobs.
It covers **both** Next.js cache handler interfaces:
| Interface | Used by | Handler file |
| --- | --- | --- |
| `cacheHandler` (singular) | ISR (`/isr`), on-demand revalidation | `cache-handler.js` |
| `cacheHandlers.remote` (plural) | `'use cache: remote'` (`/cet`, `/gmt`, `/use-cache`), `cacheComponents: true` (Next.js 16+) | `cache-components-handler.js` |
The plain `'use cache'` directive uses the default in-memory handler. This
example opts into the shared Redis-backed `remote` handler explicitly on both
Cache Components demos. The separate `/isr` route exercises the singular
handler. Both handlers use the build ID as a Redis key prefix by default, so
rebuilding does not reuse cached pages from an older build. The default ISR
in-memory cache is disabled so both instances use Redis. Set `KEY_PREFIX` to
share a namespace across deployments deliberately.
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example cache-handler-redis-turbo cache-handler-redis-turbo-app
```
```bash
yarn create next-app --example cache-handler-redis-turbo cache-handler-redis-turbo-app
```
```bash
pnpm create next-app --example cache-handler-redis-turbo cache-handler-redis-turbo-app
```
### 1. Start Redis
```bash
docker compose up -d
```
This starts a `redis/redis-stack` container on port `6379` with RedisInsight on
port `8001`.
### 2. Enable Redis key-space notifications
The handler uses Redis key-space notifications to keep its in-memory tag map in
sync across instances. Enable them with:
```bash
redis-cli -h localhost config set notify-keyspace-events Exe
```
> If your Redis provider forbids `CONFIG` commands (e.g. some managed Redis
> services), set `SKIP_KEYSPACE_CONFIG_CHECK=true` to skip the check.
### 3. Build and start the Next.js app
```bash
npm run build
npm start
```
> `next build` does **not** require a running Redis instance — both handlers
> no-op during `PHASE_PRODUCTION_BUILD`. Redis is only needed at runtime.
### 4. View the cache
Open [http://localhost:3000](http://localhost:3000) and navigate to:
- **`/cet`** or **`/gmt`** — Time demo using `'use cache: remote'` with
`cacheLife("minutes")` and `cacheTag("time-data")`. Shows the current time,
a cache-state watcher, and a "Revalidate" button that calls
`updateTag("time-data")`.
- **`/use-cache`** — Cache Components demo (plural `cacheHandlers`). Uses the
`'use cache: remote'` directive with `cacheLife("minutes")` and `cacheTag(...)`.
The "Revalidate" button calls `updateTag("use-cache-fact")`, which
invalidates the cached entry across all server instances sharing the Redis
cache.
- **`/isr`** — Pages Router ISR demo (singular `cacheHandler`). Displays the
time generated by `getStaticProps` and regenerates after 10 seconds.
To see cache debug logs:
```bash
DEBUG_CACHE_HANDLER=true npm start
```
## Documentation
- [Package README](https://github.com/trieb-work/nextjs-turbo-redis-cache#readme)
- [Architecture deep dive](https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/ARCHITECTURE.md)
- [TRWK Case Study](https://trwk.de/case-studies/nextjs-turbo-redis-cache)
## Key Features
- **L1 + L2 caching**: in-memory L1 cache per instance + Redis L2 as the shared
source of truth across all instances.
- **Request deduplication**: concurrent `get` calls for the same key are
deduplicated to avoid redundant Redis round-trips.
- **Batch tag invalidation**: `revalidateTag` operations are grouped and
optimized for minimal Redis stress.
- **Key-space notifications**: the in-memory tag map is automatically updated
when Redis keys expire or are evicted.
- **Cache Components support**: full support for the `'use cache'` directive,
`cacheTag`, and `cacheLife` (Next.js 16+).
- **Pages Router support**: ISR pages, `notFound`/`redirect` results, and
on-demand `res.revalidate(path)` — including across multiple instances.
## Environment Variables
| Variable | Required | Description |
| --- | --- | --- |
| `REDIS_URL` | Recommended | Redis connection URL, e.g. `redis://localhost:6379` |
| `REDISHOST` | If no `REDIS_URL` | Redis host (with `REDISPORT`) |
| `REDISPORT` | If no `REDIS_URL` | Redis port |
| `VERCEL_URL` | Optional | Used as a key prefix for multi-tenant / deploy isolation |
| `VERCEL_ENV` | Optional | `production` → Redis DB 0; anything else → DB 1 |
| `KEY_PREFIX` | Optional | Explicit cache key prefix |
| `DEBUG_CACHE_HANDLER` | Optional | Set to `true` for debug logging |
| `SKIP_KEYSPACE_CONFIG_CHECK` | Optional | Set to `true` to skip the `notify-keyspace-events` check |
| `KILL_CONTAINER_ON_ERROR_THRESHOLD` | Optional | Exit after N Redis errors (for container restarts) |
| `REDIS_COMMAND_TIMEOUT_MS` | Optional | Timeout for Redis GET (default: 500ms) |
## Development and Production Considerations
- The provided `compose.yaml` is intended for local development. For production
deployment, refer to the official
[Redis installation](https://redis.io/docs/install/) and
[management](https://redis.io/docs/management/) guidelines.
- **Clearing Redis Cache:**
```bash
docker exec -it cache-handler-redis-turbo redis-cli
127.0.0.1:6379> flushall
OK
```
import { notFound } from "next/navigation";
import { cacheLife, cacheTag } from "next/cache";
import { CacheStateWatcher } from "../cache-state-watcher";
import { Suspense } from "react";
import { RevalidateFrom } from "../revalidate-from";
import Link from "next/link";
type TimeData = {
dateTime: string;
timeZone: string;
};
type CachedTime = {
time: TimeData;
generatedAt: number;
};
// Map the friendly route segment to an IANA timezone for the time API.
const timeZones = {
cet: "Europe/Amsterdam",
gmt: "Etc/UTC",
} as const;
/**
* `'use cache: remote'` with a short cacheLife so the cache-state watcher can show
* the fresh → stale transition. Tagged with "time-data" so the server action
* can invalidate it via `updateTag("time-data")`.
*
* Falls back to a placeholder when the time API is unreachable (e.g. during
* `next build` without network access).
*/
async function getTimeData(ianaTimeZone: string): Promise<CachedTime> {
"use cache: remote";
cacheLife("minutes");
cacheTag("time-data");
try {
const res = await fetch(
`https://timeapi.io/api/time/current/zone?timeZone=${ianaTimeZone}`,
);
if (res.ok) {
const time: TimeData = await res.json();
return { time, generatedAt: Date.now() };
}
} catch {
// Network error — fall through to placeholder.
}
return {
time: {
dateTime: new Date().toISOString(),
timeZone: ianaTimeZone,
},
generatedAt: Date.now(),
};
}
/**
* Async content component rendered inside <Suspense> so that uncached data
* access (the `await params` + `'use cache: remote'` fetch) doesn't block the
* entire route from prerendering.
*/
async function TimeContent({
params,
}: {
params: Promise<{ timezone: string }>;
}) {
const { timezone } = await params;
const ianaTimeZone = timeZones[timezone as keyof typeof timeZones];
if (!ianaTimeZone) {
notFound();
}
const { time: timeData, generatedAt } = await getTimeData(ianaTimeZone);
return (
<>
<div className="pre-rendered-at">
{timeData.timeZone} Time {timeData.dateTime}
</div>
<Suspense fallback={null}>
<CacheStateWatcher revalidateAfter={60 * 1000} time={generatedAt} />
</Suspense>
<RevalidateFrom />
</>
);
}
export function generateStaticParams() {
return Object.keys(timeZones).map((timezone) => ({ timezone }));
}
export default async function Page({ params }: PageProps<"/[timezone]">) {
return (
<>
<header className="header">
{Object.keys(timeZones).map((timeZone) => (
<Link key={timeZone} className="link" href={`/${timeZone}`}>
{timeZone.toUpperCase()} Time
</Link>
))}
<Link className="link" href="/use-cache">
&quot;use cache&quot; demo &rarr;
</Link>
</header>
<main className="widget">
<Suspense fallback={<div className="pre-rendered-at">Loading…</div>}>
<TimeContent params={params} />
</Suspense>
</main>
<footer className="footer">
<Link
href={
process.env.NEXT_PUBLIC_REDIS_INSIGHT_URL ?? "http://localhost:8001"
}
className="link"
target="_blank"
rel="noopener noreferrer"
>
View RedisInsight &#x21AA;
</Link>
</footer>
</>
);
}
"use client";
import { ReactNode, useEffect, useState } from "react";
type CacheStateWatcherProps = { time: number; revalidateAfter: number };
export function CacheStateWatcher({
time,
revalidateAfter,
}: CacheStateWatcherProps): ReactNode {
const [cacheState, setCacheState] = useState("");
const [countDown, setCountDown] = useState("");
useEffect(() => {
let id = -1;
function check(): void {
const now = Date.now();
setCountDown(
Math.max(0, (time + revalidateAfter - now) / 1000).toFixed(3),
);
if (now > time + revalidateAfter) {
setCacheState("stale");
return;
}
setCacheState("fresh");
id = requestAnimationFrame(check);
}
id = requestAnimationFrame(check);
return () => {
cancelAnimationFrame(id);
};
}, [revalidateAfter, time]);
return (
<>
<div className={`cache-state ${cacheState}`}>
Cache state: {cacheState}
</div>
<div className="stale-after">Stale in: {countDown}s</div>
</>
);
}
:root {
--bg: #0a0a0a;
--fg: #ededed;
--accent: #0070f3;
--stale: #f97316;
--fresh: #22c55e;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
max-width: 100vw;
overflow-x: hidden;
background: var(--bg);
color: var(--fg);
font-family:
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
sans-serif;
}
main {
display: flex;
flex-direction: column;
align-items: center;
padding: 4rem 1rem;
min-height: 100vh;
gap: 2rem;
}
.header {
display: flex;
gap: 1rem;
padding: 1rem;
justify-content: center;
}
.link {
color: var(--accent);
text-decoration: none;
font-size: 0.9rem;
}
.link:hover {
text-decoration: underline;
}
.widget {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
padding: 2rem;
border: 1px solid #333;
border-radius: 0.5rem;
min-width: 320px;
}
.pre-rendered-at {
font-size: 1.25rem;
font-weight: 600;
}
.cache-state {
font-size: 0.85rem;
padding: 0.25rem 0.75rem;
border-radius: 999px;
}
.cache-state.fresh {
background: rgba(34, 197, 94, 0.15);
color: var(--fresh);
}
.cache-state.stale {
background: rgba(249, 115, 22, 0.15);
color: var(--stale);
}
.stale-after {
font-size: 0.8rem;
color: #888;
}
.revalidate-from {
display: flex;
gap: 0.5rem;
}
.revalidate-from-button {
background: var(--accent);
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.85rem;
}
.revalidate-from-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.footer {
padding: 1rem;
text-align: center;
}
.card {
border: 1px solid #333;
border-radius: 0.5rem;
padding: 1.5rem;
min-width: 320px;
}
.card h2 {
font-size: 1rem;
margin-bottom: 0.75rem;
color: #aaa;
font-weight: 500;
}
.card .value {
font-size: 1.5rem;
font-weight: 700;
word-break: break-all;
}
.badge {
display: inline-block;
font-size: 0.7rem;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background: rgba(0, 112, 243, 0.15);
color: var(--accent);
margin-top: 0.5rem;
}
import "./global.css";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
import Link from "next/link";
export default function HomePage() {
return (
<main className="widget">
<h1>Redis Cache Handler Example</h1>
<p style={{ color: "#888", textAlign: "center" }}>
Powered by{" "}
<a
href="https://www.npmjs.com/package/@trieb.work/nextjs-turbo-redis-cache"
className="link"
target="_blank"
rel="noopener noreferrer"
>
@trieb.work/nextjs-turbo-redis-cache
</a>
</p>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
<Link className="link" href="/cet">
Remote Cache Components: time demo &rarr;
</Link>
<Link className="link" href="/use-cache">
Remote Cache Components: fact demo &rarr;
</Link>
<Link className="link" href="/isr">
ISR demo (singular cacheHandler) &rarr;
</Link>
</div>
</main>
);
}
"use client";
import { useFormStatus } from "react-dom";
import revalidate from "./server-actions";
function RevalidateButton() {
const { pending } = useFormStatus();
return (
<button
className="revalidate-from-button"
type="submit"
disabled={pending}
aria-disabled={pending}
>
Revalidate
</button>
);
}
export function RevalidateFrom() {
return (
<form className="revalidate-from" action={revalidate}>
<RevalidateButton />
</form>
);
}
"use server";
import { updateTag } from "next/cache";
export default async function revalidate() {
updateTag("time-data");
}
import { cacheLife, cacheTag } from "next/cache";
import Link from "next/link";
import { RevalidateUseCacheFrom } from "./revalidate-from";
type UselessFact = {
id: string;
text: string;
};
/**
* `'use cache: remote'` directive (Next.js 16+ Cache Components).
*
* This function's return value is cached via the plural `cacheHandlers`
* API — pointed at `cache-components-handler.js` in next.config.js.
* The cached entry is shared across all server instances through Redis,
* and `updateTag("use-cache-fact")` invalidates it on every
* instance.
*
* Falls back to a placeholder when the API is unreachable (e.g. during
* `next build` without network access).
*/
async function getUselessFact(): Promise<UselessFact> {
"use cache: remote";
cacheLife("minutes");
cacheTag("use-cache-fact");
try {
const res = await fetch("https://uselessfacts.jsph.pl/api/v2/facts/random");
if (res.ok) {
return res.json();
}
} catch {
// Network error — fall through to placeholder.
}
return {
id: "placeholder",
text: "Cache is king — this placeholder shows when the API is unreachable during build.",
};
}
export default async function UseCachePage() {
const fact = await getUselessFact();
return (
<>
<header className="header">
<Link className="link" href="/cet">
&larr; Time demo
</Link>
</header>
<main className="widget">
<div className="card">
<h2>&quot;use cache: remote&quot; — shared via Redis</h2>
<div className="value">{fact.text}</div>
<span className="badge">cacheLife: minutes</span>
</div>
<RevalidateUseCacheFrom />
</main>
<footer className="footer">
<Link
href={
process.env.NEXT_PUBLIC_REDIS_INSIGHT_URL ?? "http://localhost:8001"
}
className="link"
target="_blank"
rel="noopener noreferrer"
>
View RedisInsight &#x21AA;
</Link>
</footer>
</>
);
}
"use client";
import { useFormStatus } from "react-dom";
import revalidate from "./server-actions";
function RevalidateButton() {
const { pending } = useFormStatus();
return (
<button
className="revalidate-from-button"
type="submit"
disabled={pending}
aria-disabled={pending}
>
Revalidate &quot;use cache&quot;
</button>
);
}
export function RevalidateUseCacheFrom() {
return (
<form className="revalidate-from" action={revalidate}>
<RevalidateButton />
</form>
);
}
"use server";
import { updateTag } from "next/cache";
export default async function revalidateUseCache() {
// Invalidates the "use-cache-fact" tag across all server instances
// sharing the Redis cache.
updateTag("use-cache-fact");
}
/**
* Cache Components handler (plural `cacheHandlers` API, Next.js 16+).
*
* Used by the `'use cache: remote'` directive, `cacheTag`, `cacheLife`, and
* `revalidateTag` when `cacheComponents: true` is set in `next.config.js`.
*
* `@trieb.work/nextjs-turbo-redis-cache` ships a ready-to-export
* `redisCacheHandler` singleton that implements the full plural interface
* (`get`, `set`, `refreshTags`, `getExpiration`, `updateTags`).
*
* During `PHASE_PRODUCTION_BUILD` we export a no-op so `next build` works
* without a running Redis instance.
*/
const { PHASE_PRODUCTION_BUILD } = require("next/constants");
const isBuildPhase = PHASE_PRODUCTION_BUILD === process.env.NEXT_PHASE;
if (isBuildPhase) {
// No-op handler — Redis is a runtime concern only.
module.exports = {
get: () => Promise.resolve(undefined),
set: () => Promise.resolve(),
refreshTags: () => Promise.resolve(),
getExpiration: () => Promise.resolve(0),
updateTags: () => Promise.resolve(),
};
} else {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { redisCacheHandler } = require("@trieb.work/nextjs-turbo-redis-cache");
module.exports = redisCacheHandler;
}
/**
* ISR cache handler (singular `cacheHandler` API) for App and Pages Router.
*
* Next.js instantiates this class and calls the methods on the returned object.
* We therefore return the singleton adapter instance itself after lazy
* initialization so the `RedisStringsHandler` methods are the ones that receive
* runtime calls. The wrapper methods below are intentionally omitted; any
* monitoring logic belongs in the adapter instance and should be wired there.
*/
const { PHASE_PRODUCTION_BUILD } = require("next/constants");
const { readFileSync } = require("node:fs");
const { join } = require("node:path");
let cachedHandler;
class CacheHandler {
constructor({ serverDistDir }) {
if (cachedHandler) {
return cachedHandler;
}
// No-op during build phase — Redis is a runtime concern only.
if (PHASE_PRODUCTION_BUILD === process.env.NEXT_PHASE) {
cachedHandler = {
get: () => Promise.resolve(null),
set: () => Promise.resolve(undefined),
revalidateTag: () => Promise.resolve(undefined),
resetRequestCache: () => Promise.resolve(undefined),
};
return cachedHandler;
}
// Lazily import so the Redis client is only created at runtime.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {
RedisStringsHandler,
} = require("@trieb.work/nextjs-turbo-redis-cache");
cachedHandler = new RedisStringsHandler({
// REDIS_URL is recommended; falls back to REDISHOST/REDISPORT, then
// redis://localhost:6379.
// redisUrl: process.env.REDIS_URL,
keyPrefix:
process.env.KEY_PREFIX ||
process.env.VERCEL_URL ||
readFileSync(join(serverDistDir, "..", "BUILD_ID"), "utf8").trim(),
});
return cachedHandler;
}
}
module.exports = CacheHandler;
services:
redis-stack:
image: redis/redis-stack:latest
container_name: cache-handler-redis-turbo
ports:
- "6379:6379"
- "8001:8001"
/**
* Next.js config for the cache-handler-redis-turbo example.
*
* This example demonstrates BOTH Next.js cache interfaces side by side:
*
* 1. `cacheHandler` (singular) — ISR for App and Pages Router, on-demand
* revalidation. Pointed at `./cache-handler.js`.
* 2. `cacheHandlers` (plural) — the `'use cache'` family with
* `cacheComponents: true`. The `remote` kind is the one that couples to a
* shared remote cache, so we point it at `./cache-components-handler.js`.
*
* The canonical no-dependency Redis example is `examples/cache-handler-redis`.
* This example wires the same two APIs through `@trieb.work/nextjs-turbo-redis-cache`.
*
* Redis is only needed at runtime, not at build time. The handlers below
* no-op during `PHASE_PRODUCTION_BUILD` so `next build` works without a
* running Redis instance.
*/
/** @type {import('next').NextConfig} */
const nextConfig = {
// Next.js 16+ Cache Components: enables the `'use cache'` directive.
cacheComponents: true,
// ISR / Pages Router / on-demand revalidation handler.
cacheHandler:
process.env.NODE_ENV === "production"
? require.resolve("./cache-handler.js")
: undefined,
cacheMaxMemorySize: 0,
// `'use cache'` directive handler (plural API, Next.js 16+).
// `remote` is the cache kind that should be coupled to a backing remote store.
cacheHandlers: {
remote: require.resolve("./cache-components-handler.js"),
},
env: {
NEXT_PUBLIC_REDIS_INSIGHT_URL:
process.env.REDIS_INSIGHT_URL ?? "http://localhost:8001",
},
};
module.exports = nextConfig;
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@trieb.work/nextjs-turbo-redis-cache": "^1.15.0",
"next": "latest",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"redis": "4.7.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5.3.3"
}
}
import "../app/global.css";
import type { AppProps } from "next/app";
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
import Link from "next/link";
import type { GetStaticProps, InferGetStaticPropsType } from "next";
export const getStaticProps = (async () => ({
props: { generatedAt: new Date().toISOString() },
revalidate: 10,
})) satisfies GetStaticProps<{ generatedAt: string }>;
export default function IsrPage({
generatedAt,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return (
<>
<header className="header">
<Link className="link" href="/">
&larr; Home
</Link>
</header>
<main className="widget">
<h1>ISR via the singular cacheHandler</h1>
<p>Generated at: {generatedAt}</p>
<p>Regenerates after 10 seconds.</p>
</main>
</>
);
}
{
"compilerOptions": {
"target": "es2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
...@@ -9,6 +9,13 @@ Both are configured in [`next.config.js`](./next.config.js), which enables `cach ...@@ -9,6 +9,13 @@ Both are configured in [`next.config.js`](./next.config.js), which enables `cach
Check out this [repository](https://github.com/ezeparziale/nextjs-k8s) that contains a comprehensive setup for Kubernetes. Check out this [repository](https://github.com/ezeparziale/nextjs-k8s) that contains a comprehensive setup for Kubernetes.
## Production community handlers
This example is the no-dependency starting point: both Next.js cache APIs against the `redis` client. For production features such as GET timeouts, request coalescing, in-memory tag maps, key-space notifications, and TLS, community packages include:
- [`@trieb.work/nextjs-turbo-redis-cache`](https://www.npmjs.com/package/@trieb.work/nextjs-turbo-redis-cache) — also available as [`cache-handler-redis-turbo`](../cache-handler-redis-turbo)
- [`@mrjasonroy/cache-components-cache-handler`](https://github.com/mrjasonroy/cache-components-cache-handler)
## How to use ## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
......
"use client"; "use client";
export default function Error({ error }: { error: Error }) { export default function ErrorPage({ error }: { error: unknown }) {
return <h2>{error.message}</h2>; const message = error instanceof Error ? error.message : String(error);
return <h2>{message}</h2>;
} }
"use client"; "use client";
export default function Error({ error }: { error: Error }) { export default function ErrorPage({ error }: { error: unknown }) {
return <h2>{error.message}</h2>; const message = error instanceof Error ? error.message : String(error);
return <h2>{message}</h2>;
} }
"use client"; "use client";
export default function Error({ error }: { error: Error }) { export default function ErrorPage({ error }: { error: unknown }) {
return <h2>{error.message}</h2>; const message = error instanceof Error ? error.message : String(error);
return <h2>{message}</h2>;
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment