Unverified Commit 7cb68c12 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: create client-side fetching guide (#96341)

## What changed

- Expands the SPA data-fetching guidance with focused SWR and TanStack
Query guides.
- Covers client-only fetching, optional Server Component seeding, shared
cache identities, and optimistic mutations.
- Explains how the Next.js server and client caches relate to
library-owned browser caches, including SWR `preload` and TanStack Query
hydration with Cache Components.
- Aligns the examples with `next-spa-patterns` and the team chat demo.

## Validation

- Prettier and diff checks pass for the updated guides.
- `next-spa-patterns` passes TypeScript checks.
parent 7b848a4e
......@@ -371,6 +371,8 @@ export default function BlogPage() {
}
```
See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating a library cache with the Next.js server and client caches.
## Examples
### Sequential data fetching
......
---
title: Client-side data fetching
description: Fetch data in Client Components with a data-fetching library, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/guides/interactive-apps
- app/getting-started/caching
---
Many apps can provide responsive interactions without a client data-fetching library. If a Client Component only needs to read server data once, [pass it a Promise and unwrap it with React's `use()`](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api).
This avoids adding a library for data that never revalidates on the client. See [Building interactive apps](/docs/app/guides/interactive-apps) for patterns using Server Functions, transitions, optimistic UI, and pending feedback.
Use a client data-fetching library such as [SWR](https://swr.vercel.app), [TanStack Query](https://tanstack.com/query), or [Apollo Client](https://www.apollographql.com/docs/react) when Client Components need a shared browser cache. These libraries can add focus revalidation, interval polling, request deduplication, or optimistic updates across components.
## Choose a client fetching pattern
First decide whether the initial view needs data from the server or can wait for a browser request after hydration. Client data-fetching libraries support three common patterns:
| Pattern | SWR | TanStack Query | When data becomes available |
| ----------------------- | ------------------------------ | --------------------- | -------------------------------------- |
| Inline loading states | `useSWR` | `useQuery` | Browser request after hydration |
| Suspense loading states | `useSWR` with `suspense: true` | `useSuspenseQuery` | Browser request after hydration |
| Provided by the server | `<SWRConfig fallback>` | `<HydrationBoundary>` | Initial render or streamed from server |
Use inline loading states when each component should render its own loading UI. Use [Suspense](/docs/app/getting-started/fetching-data#streaming) to define loading UI at a boundary and coordinate which parts of the interface reveal together or progressively. For client-only fetching, choose the pattern that matches the loading experience you want. Suspense coordinates rendering, while the data library and component structure determine when requests start.
For browser-driven interactions such as autocomplete, you can use either client-only pattern. The initial result waits for hydration and a browser request, which is often the right tradeoff for data that is not needed until an interaction.
Provide initial data from a [Server Component](/docs/app/getting-started/server-and-client-components) when the server knows what the initial render needs. The value can be included in the initial render or streamed through Suspense. The library receives it in the React Server Component payload and can continue managing it in the browser.
## Cache server data with Cache Components (optional)
Providing initial data and caching it on the server are independent choices. Add Cache Components when the server read or rendered view should be reused. When both are enabled, three cache layers can hold related data:
| Layer | What it stores | Freshness control |
| ---------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Next.js server cache | Cached data and Server Component output | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `revalidate` and `expire` |
| Next.js client cache | React Server Component payloads for visited and prefetched routes | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` |
| Client data-fetching library | Browser data stored under an SWR key or TanStack query key | The library's revalidation options and mutations |
Next.js [prefetching](/docs/app/guides/prefetching) can place a route's React Server Component payload in the client cache before navigation.
The cache layers keep independent freshness policies and do not need matching durations. Cache identities and mutation invalidation must stay coordinated across layers.
## Coordinate mutations
Server Components, data-fetching libraries, and mutations manage different parts of the data flow:
- **Server Components** provide the initial data, scoped to the segment that owns it.
- **The data-fetching library** stores the browser value under a shared cache identity.
- **Mutations** can update the browser cache immediately and invalidate cached server data so the next render can read a fresh value.
An optimistic update should restore the previous browser value if the write fails. If the server read is not cached, there is no server tag to invalidate.
After a mutation, invalidate any cached server read that provided the initial data:
| Method | Use when | Next server read |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------ |
| [`updateTag(tag)`](/docs/app/api-reference/functions/updateTag) | A Server Action must make its update visible immediately | Waits for fresh data |
| [`revalidateTag(tag, 'max')`](/docs/app/api-reference/functions/revalidateTag) | The update is passive or stale data is acceptable | Serves stale data while revalidating |
| [`revalidateTag(tag, { expire: 0 })`](/docs/app/api-reference/functions/revalidateTag) | A webhook or external system requires immediate expiration | Waits for fresh data |
## Apply these patterns with SWR or TanStack Query
- [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)
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).
---
title: How to fetch client-side data with SWR
nav_title: SWR
description: Fetch client-side data with SWR, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [SWR](https://swr.vercel.app) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Fetch data on the client
SWR can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useSWR` when the component should render its own loading and error states. A conditional key delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isLoading,
} = useSWR(
query ? `/api/products?query=${encodeURIComponent(query)}` : null,
fetcher
)
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isLoading) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
## Use Suspense for client data
Use `suspense: true` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { Suspense } from 'react'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSWR(
`/api/products?query=${encodeURIComponent(query)}`,
fetcher,
{ suspense: true }
)
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
With an unconditional key, SWR defines `data` after Suspense resolves. Handle request errors with the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
The `isLoading` value is `true` when a request is running and there is no loaded data to display. The `isValidating` value is `true` whenever a request is running, including background revalidation.
With `suspense: true`, Suspense handles the initial no-data state. Later revalidation for the same key keeps the current data rendered instead of showing the Suspense fallback again. Use `isValidating` to provide background refresh feedback. Learn more about [SWR loading states](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux).
Learn more: [SWR data fetching](https://swr.vercel.app/docs/data-fetching).
> **Good to know:** Independent Suspense reads can start in parallel when they render in sibling components. Multiple Suspense reads in one component run sequentially. Learn more about [network waterfalls](/docs/app/guides/migrating/from-create-react-app#network-waterfalls) and [SWR Suspense](https://swr.vercel.app/docs/suspense).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and SWR should continue managing it in the browser. With SWR 2.3.0 and React 19, a Server Component can provide fallback data before the client takes over.
Scope `<SWRConfig>` to the route segment that owns the data. The provider keeps the `fallback` close to its consumer and avoids adding feature data to a shared layout:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
The fallback and Client Component must use the same SWR key. Define the key once so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
}
```
```js filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
}
```
In the page example, the Promise returned by `params.then()` keeps the fallback visible until the route parameters resolve. `ProductData` then creates a separate, unawaited `getProduct(id)` Promise for the SWR `fallback`. React passes that Promise through the React Server Component payload, and the component reading the matching key suspends until the data resolves.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }: { id: string }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
async function fetcher(url) {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly. If they drift, SWR ignores the fallback value and fetches on the client.
The `fallback` provides the hook's initial value. After hydration, SWR can revalidate or mutate the same key in its browser cache.
The SWR key points to a [Route Handler](/docs/app/api-reference/file-conventions/route) with a `GET` method. The Route Handler can call the same `getProduct` function that provides the fallback, while the browser uses the URL for revalidation and polling.
Learn more: [SWR arguments and keys](https://swr.vercel.app/docs/arguments) and [SWR with Next.js App Router](https://swr.vercel.app/docs/with-nextjs).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data used as the SWR fallback. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id: string) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
SWR owns a separate browser cache, so its revalidation options do not need to match `cacheLife`.
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
+ tag: (id: string) => `product:${id}`,
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
+ tag: (id) => `product:${id}`,
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
## Coordinate server and client caches after mutations
The fallback provides the initial value. After hydration, SWR manages the browser cache and revalidation. For reused data, keep the SWR key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId) => `activity:${userId}`,
}
```
Use the same key for the fallback, the Client Component read, and the mutation. With SWR, pass the write to [`mutate`](https://swr.vercel.app/docs/mutation) and provide `optimisticData`. SWR shows the optimistic value immediately and rolls it back if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic SWR value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **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).
---
title: How to fetch client-side data with TanStack Query
nav_title: TanStack Query
description: Fetch client-side data with TanStack Query, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [TanStack Query](https://tanstack.com/query) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Set up the provider
Wrap the routes that use TanStack Query in a `QueryClientProvider`. Create a new query client for each server render and reuse one query client in the browser:
```tsx filename="app/products/providers.tsx"
'use client'
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
let browserQueryClient: QueryClient | undefined
function getQueryClient() {
// Keep server requests isolated and preserve the browser cache across renders.
if (typeof window === 'undefined') return new QueryClient()
browserQueryClient ??= new QueryClient()
return browserQueryClient
}
export function Providers({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={getQueryClient()}>
{children}
</QueryClientProvider>
)
}
```
Render the provider from the nearest shared layout:
```tsx filename="app/products/layout.tsx"
import { Providers } from './providers'
export default function Layout({ children }: LayoutProps<'/products'>) {
return <Providers>{children}</Providers>
}
```
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).
## Fetch data on the client
TanStack Query can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useQuery` when the component should render its own loading and error states. The `enabled` option delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useQuery } from '@tanstack/react-query'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isPending,
} = useQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
enabled: query.length > 0,
})
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isPending) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
Learn more: [TanStack Query queries](https://tanstack.com/query/latest/docs/framework/react/guides/queries).
## Use Suspense for client data
Use `useSuspenseQuery` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { Suspense } from 'react'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSuspenseQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
})
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
If the initial request fails, `useSuspenseQuery` propagates the error to the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
After a query has data, later refetches for the same query keep the cached data rendered instead of showing the Suspense fallback again. Use `isFetching` to provide background refresh feedback.
If the initial view needs the data, provide it from a Server Component as shown below.
> **Good to know:** Multiple `useSuspenseQuery` calls in one component run sequentially. Put independent queries in sibling components, or use [`useSuspenseQueries`](https://tanstack.com/query/latest/docs/framework/react/reference/useSuspenseQueries). Learn more about [request waterfalls](https://tanstack.com/query/latest/docs/framework/react/guides/request-waterfalls).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and TanStack Query should continue managing it in the browser. A Server Component can provide initial query data before the client takes over.
TanStack Query 5.40.0 or later can dehydrate pending queries. Start `prefetchQuery` without awaiting it, then pass the dehydrated state to `<HydrationBoundary>`. Override `queryFn` on the server because the Route Handler's relative URL only resolves in the browser:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
The server and Client Component must use the same query key. Keep the key and query options together so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
import { queryOptions } from '@tanstack/react-query'
export type Product = { id: string; name: string }
export const productCache = {
key: (id: string) => ['product', id] as const,
options: (id: string) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async (): Promise<Product> => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
}),
}
```
```js filename="app/products/[id]/product-cache.js" switcher
import { queryOptions } from '@tanstack/react-query'
export const productCache = {
key: (id) => ['product', id],
options: (id) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async () => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
}),
}
```
The query function fetches a [Route Handler](/docs/app/api-reference/file-conventions/route) so it can run on the client. Larger features can place query options in a separate client-facing module as long as every caller imports the key from the same cache contract.
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProductData` prefetches below the boundary.
The Client Component reads the same query key with `useSuspenseQuery` (or `useQuery` to render `isPending` and `error` states inline):
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }: { id: string }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
Learn more: [TanStack Query Advanced SSR](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data provided to TanStack Query. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
import type { Product } from './product-cache'
export async function getProduct(id: string): Promise<Product> {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
TanStack Query owns a separate browser cache, so its `staleTime` does not need to match `cacheLife`.
With Cache Components enabled, Next.js also prerenders Client Components. Keep a query needed during the initial render behind [Suspense](/docs/app/getting-started/fetching-data#streaming). TanStack Query can read the current time while creating active query state, and the boundary lets Next.js defer that work instead of raising a [current-time prerender error](/docs/messages/blocking-prerender-current-time-client).
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => ['product', id] as const,
+ tag: (id: string) => `product:${id}`,
// ...
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => ['product', id],
+ tag: (id) => `product:${id}`,
// ...
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
> **Good to know:** TanStack Query's `dehydrate()` reads the current time during Cache Components prerendering. Use the [prerenderable hydration helper](#build-a-prerenderable-hydration-state) for cached initial data.
## Coordinate server and client caches after mutations
Hydration provides the initial client cache value. After hydration, TanStack Query owns the browser copy and its revalidation. For reused data, keep the query key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: ['activity', 'unread'] as const,
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: ['activity', 'unread'],
tag: (userId) => `activity:${userId}`,
}
```
On mutation, use `useMutation`'s [`onMutate`](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) callback to update the cache immediately and restore the previous value in `onError` if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic query value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **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.
## Build a prerenderable hydration state
The TanStack Query pattern above uses `dehydrate()` to create the hydration state. With Cache Components, `dehydrate()` reads the current time (`Date.now()`) while prerendering and causes a [current-time prerender error](/docs/messages/blocking-prerender-current-time).
Instead, cache only that timestamp and build the dehydrated state by hand. Wrap the time read in [`use cache`](/docs/app/api-reference/directives/use-cache) with the same tags as the data reads. When a mutation invalidates those tags, the data and its timestamp advance together, so `<HydrationBoundary>` overwrites the client query on the next navigation:
```tsx filename="app/lib/hydrate.ts" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import {
defaultShouldDehydrateQuery,
QueryClient,
type DehydratedState,
type QueryKey,
} from '@tanstack/react-query'
type HydratedQuery = {
queryKey: QueryKey
data: unknown
}
type HydrationOptions = {
tags: string[]
}
async function getHydrationUpdatedAt(tags: string[]) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(
queries: HydratedQuery[],
options: HydrationOptions
): Promise<DehydratedState> {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
```js filename="app/lib/hydrate.js" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { defaultShouldDehydrateQuery, QueryClient } from '@tanstack/react-query'
async function getHydrationUpdatedAt(tags) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(queries, options) {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
Await the helper in the segment that owns the data, passing the data and the same tags used on the underlying `getProduct` read. Hand the result to `<HydrationBoundary>` inside `ProductData`:
```tsx filename="app/products/[id]/page.tsx" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }: { id: string }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
> **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).
......@@ -766,6 +766,8 @@ Most patterns mix two or more of these. Reach for whichever primitive fits the c
Related guides:
- [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and client cache coordination
- [Streaming](/docs/app/guides/streaming) for loading boundaries and `<Suspense>` patterns
- [Instant Navigation](/docs/app/guides/instant-navigation) for validating that navigations stay instant
- [View Transitions](/docs/app/guides/view-transitions) for animating state changes
- [Single-page applications](/docs/app/guides/single-page-applications#mutating-data-with-server-actions) for a shared-reducer `useOptimistic` example that keeps client and server list updates in sync
......@@ -5,26 +5,22 @@ description: Next.js fully supports building Single-Page Applications (SPAs).
related:
description: Related guides and references.
links:
- app/guides/client-side-data-fetching
- app/guides/interactive-apps
- app/guides/server-actions
- app/guides/forms
- app/guides/streaming
- app/api-reference/components/link
- app/guides/static-exports
---
Next.js fully supports building Single-Page Applications (SPAs).
This includes fast route transitions with prefetching, client-side data fetching, using browser APIs, integrating with third-party client libraries, creating static routes, and more.
If you have an existing SPA, you can migrate to Next.js without large changes to your code. Next.js then allows you to progressively add server features as needed.
Build Single-Page Applications (SPAs) with client-side navigation and data fetching. Next.js supports client and server patterns in the same app, and existing SPAs can migrate without a full rewrite.
## What is a Single-Page Application?
The definition of a SPA varies. We’ll define a “strict SPA” as:
The definition of a SPA varies. We'll define a "strict SPA" as:
- **Client-side rendering (CSR)**: The app is served by one HTML file (e.g. `index.html`). Every route, page transition, and data fetch is handled by JavaScript in the browser.
- **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page’s DOM and fetches data as needed.
- **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page's DOM and fetches data as needed.
Strict SPAs often require large amounts of JavaScript to load before the page can be interactive. Further, client data waterfalls can be challenging to manage. Building SPAs with Next.js can address these issues.
......@@ -34,19 +30,21 @@ Next.js can automatically code split your JavaScript bundles, and generate multi
The [`next/link`](/docs/app/api-reference/components/link) component automatically [prefetches](/docs/app/api-reference/components/link#prefetch) routes, giving you the fast page transitions of a strict SPA, but with the advantage of persisting application routing state to the URL for linking and sharing.
Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, Next.js allows you to progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed.
Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, you can progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed.
## Examples
## 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.
### Using React’s `use` within a Context Provider
### Using React's `use` within a Context Provider
You can use React’s [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render.
You can use React's [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render.
Starting the request on the server, before the rest of the app renders, lets the response stream immediately and avoids client-side request waterfalls.
You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook. A provider isn't always the best fit: often you can read the data in a Server Component, or pass the Promise directly, rather than putting everything in context. For general client-side data fetching, a library like [SWR](#spas-with-swr) can help.
You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook.
When a Client Component needs focus revalidation, polling, mutations, or request deduplication, use a library such as SWR or TanStack Query. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating the library cache with the Next.js server and client caches.
Start the request in a Server Component (here, the root layout) without awaiting it, and pass the Promise to the provider:
......@@ -154,7 +152,7 @@ export function Profile() {
const userPromise = useUser()
const user = use(userPromise)
return '...'
return <p>{user.name}</p>
}
```
......@@ -168,13 +166,11 @@ export function Profile() {
const userPromise = useUser()
const user = use(userPromise)
return '...'
return <p>{user.name}</p>
}
```
You can also move the `use()` call into the `useUser` hook so components just call `const user = useUser()`. That reads cleanly, but calling `use()` in the component keeps it clear where the component suspends.
Wrap the consumer in a `<Suspense>` boundary to show a fallback while the Promise resolves:
Wrap the consumer in a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary to show a fallback while the Promise resolves:
```tsx filename="app/page.tsx" switcher
import { Suspense } from 'react'
......@@ -206,325 +202,6 @@ The component that consumes the Promise (e.g. `Profile` above) suspends while th
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).
### SPAs with SWR
[SWR](https://swr.vercel.app) is a popular React library for data fetching.
With SWR 2.3.0 (and React 19+), you can gradually adopt server features alongside your existing SWR-based client data fetching code. This is an abstraction of the above `use()` pattern. This means you can move data fetching between the client and server-side, or use both:
- **Client-only:** `useSWR(key, fetcher)`
- **Server-only:** `useSWR(key)` + RSC-provided data
- **Mixed:** `useSWR(key, fetcher)` + RSC-provided data
Reach for SWR when you need its client-side features, such as revalidation on focus or interval, [`mutate`](https://swr.vercel.app/docs/mutation), or request deduplication across components. If a Client Component only needs to read server data once, pass a Promise to it and unwrap it with [`use()`](#using-reacts-use-within-a-context-provider) instead. That avoids adding a data-fetching library for data that never revalidates on the client.
To provide server data to SWR on the first render, wrap your application in `<SWRConfig>` and provide a `fallback`:
```tsx filename="app/layout.tsx" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
```js filename="app/layout.js" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
Because this is a Server Component, `getUser()` can securely read cookies, headers, or talk to your database. No separate API route is needed. Client components below the `<SWRConfig>` can call `useSWR()` with the same key to retrieve the user data. The component code with `useSWR` **does not require any changes** from your existing client-fetching solution.
```tsx filename="app/profile.tsx" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url: string) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
```jsx filename="app/profile.js" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
The `fallback` data can be prerendered and included in the initial HTML response, then immediately read in the child components using `useSWR`. SWR’s polling, revalidation, and caching still run **client-side only**, so it preserves all the interactivity you rely on for an SPA.
Because Next.js seeds the `fallback` on the server, `useSWR` has data on first render, so there's no need for conditional logic to handle an `undefined` `data`. The seeded data counts as loaded, so [`isLoading`](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux) stays `false`. A client-side revalidation surfaces as `isValidating` instead, which you can use to show a background-refresh indicator.
| | SWR | RSC | RSC + SWR |
| -------------------- | ------------------- | ------------------- | ------------------- |
| SSR data | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Streaming while SSR | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Deduplicate requests | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Client-side features | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> |
#### Scoping server data to the components that use it
`<SWRConfig>` can live in any Server Component, not only the root layout. Placing it on the route segment that owns the data keeps the `fallback` close to where it is read, keeps unrelated keys out of a global config, and lets each segment start its own server-side requests. Nested `<SWRConfig>` providers merge their fallbacks, so a page-level config extends the keys seeded by a parent layout rather than replacing them:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
Inside `<Suspense>`, `params.then()` resolves the `id` and passes it to `ProjectData`, which seeds the `fallback` with the `getProject(id)` promise. Only that subtree suspends while the data loads.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then((res) => res.json())
export function ProjectView({ id }: { id: string }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
export function ProjectView({ id }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly, since SWR looks up the seeded value by key. Nothing warns on a mismatch: the seeded value is never read, `data` starts as `undefined`, and SWR fetches again on the client. When a key is built from dynamic values (route params, search params), derive it in one shared place so the server and client cannot drift apart. `fallback` seeds the first render, not SWR's persistent cache, so use [`preload`](https://swr.vercel.app/docs/prefetching) to fill the cache and reuse the request on revalidation.
See the [live 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).
### SPAs with TanStack Query
You can use [TanStack Query](https://tanstack.com/query) (formerly React Query) with Next.js on the client and the server, and seed its cache from a Server Component the same way as [SWR](#spas-with-swr): prefetch on the server, hand the cache to the client, and let it own revalidation from there.
TanStack Query needs a one-time setup, including a `getQueryClient` (new per request on the server, a singleton in the browser), a `<QueryClientProvider>`, and a client configured to dehydrate pending queries. TanStack Query owns this integration, so follow [its Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) for the full setup and current APIs.
A Server Component starts the request with `prefetchQuery` **without awaiting it**, then serializes the cache into the streamed HTML with `<HydrationBoundary>`:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProjectData` prefetches below the boundary.
The Client Component reads the data with the same query key. Use `useSuspenseQuery` when a `<Suspense>` boundary handles loading and you want `data` to always be defined. Use `useQuery` when you would rather render its `isPending` and `error` states inline:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }: { id: string }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
The query key connects the two sides, the same way the matching `fallback` and `useSWR` keys do above.
> **Good to know:** When you cache this data with [Cache Components](/docs/app/getting-started/caching), add [`"use cache"`](/docs/app/api-reference/directives/use-cache) to the data function (such as `getProject`), not around `dehydrate()`. Caching the dehydrated state also caches TanStack Query metadata such as timestamps, which can serve stale data on later requests.
See the [live 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).
### Rendering components only in the browser
Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/guides/lazy-loading#nextdynamic):
......@@ -545,9 +222,9 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/browser-only) and
If you are migrating from a strict SPA like [Create React App](/docs/app/guides/migrating/from-create-react-app) or [Vite](/docs/app/guides/migrating/from-vite), you might have existing code which shallow routes to update the URL state. This can be useful for manual transitions between views in your application _without_ using the default Next.js file-system routing.
Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
Next.js lets you use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).
The `pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).
```tsx filename="app/ui/sort-products.tsx" switcher
'use client'
......@@ -601,7 +278,7 @@ See the [live demo](https://next-spa-patterns.labs.vercel.dev/shallow-routing) a
### Mutating data with Server Actions
The sections above seed client-side data-fetching libraries from the server, which handle reads. Interactivity means writing data, and that usually happens outside those libraries: a Client Component calls a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. If you already use SWR or TanStack Query, you can instead write through an API route and revalidate with SWR's [`mutate`](https://swr.vercel.app/docs/mutation) or TanStack Query's [`invalidateQueries`](https://tanstack.com/query/latest/docs/framework/react/guides/invalidations-from-mutations). The rest of this section uses Server Actions directly.
Interactivity often requires writing data. A Client Component can call a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. A client data-fetching library can coordinate an optimistic browser update around the same Server Action, as shown in the [client-side data fetching guide](/docs/app/guides/client-side-data-fetching#coordinate-mutations). The rest of this section coordinates the Server Action with React's built-in state APIs.
A Server Action takes time and can fail. React has useful tools to keep the UI responsive while it runs, so a mutation can feel as instant as a client-rendered SPA: [transitions](https://react.dev/reference/react/useTransition), [`useOptimistic`](https://react.dev/reference/react/useOptimistic), [`useActionState`](https://react.dev/reference/react/useActionState), and [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus).
......@@ -863,7 +540,7 @@ To learn more about adding interactivity on top of server-rendered apps so they
Next.js also supports generating a fully [static site](/docs/app/guides/static-exports). This has some advantages over strict SPAs:
- **Automatic code-splitting**: Instead of shipping a single `index.html`, Next.js will generate an HTML file per route, so your visitors get the content faster without waiting for the client JavaScript bundle.
- **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions remain instant and SPA-like.
- **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions are still instant and SPA-like.
To enable a static export, update your configuration:
......
......@@ -24,6 +24,8 @@ kind: insight
A [Client Component](/docs/app/getting-started/server-and-client-components#using-client-components) called [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), [`Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), or [`new Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) inline during render, and the surrounding tree had no [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary. Client Components are server-side rendered on first load, so Next.js can't bake "now" into the prerendered HTML. The SSR timestamp won't match the value the client computes on hydration, so you need to choose: defer the value behind a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary so SSR can stream it, or move the call into [`useEffect`](https://react.dev/reference/react/useEffect) (or an event handler) so it only runs on the client.
An imported library can also read the current time during render. In that case, the stack trace may point to the hook or component that initializes the library instead of its internal `Date.now()` call.
The Server Component case is handled at [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time). Other unpredictable client-side APIs ([`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)) have parallel error pages: [`Math.random()` in a Client Component](/docs/messages/blocking-prerender-random-client) and [Crypto APIs in a Client Component](/docs/messages/blocking-prerender-crypto-client).
## Ways to fix this
......
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