Unverified Commit b56eb16e authored by Joseph's avatar Joseph Committed by GitHub

Backport/docs fixes 16.2 - July round (#96031)

## Summary

- docs: server actions guide x-refs (#95143)
- docs: remove unnecessary async from rewrites/headers/redirects
examples (#95148)
- docs: Update FormEvent to SubmitEvent in form handling example
(#95453)
- docs: remove incorrect statement that force-cache is the default
(#95235)
- docs: note default error/not-found UI follows OS color scheme (#95673)
- docs: useSearchParams example stray link (#95759)
- docs: remove experimental @next/routing note (#94903)
- docs: add 'Set up your editor' to the installation guide (#95928)
- docs: clarify layout.js nesting behavior in route groups (#95720)
- Include examples of static export tools & GitHub Pages template
(#95929)
- docs: fix unstable_cache syntax error (#96002)
- docs: clarify sequential data fetching example (#94930)
- docs: Fix broken link to Node.js Debugging Guide (#93958)
- docs: fix broken Node.js inspector URL in debugging guide (#94934)
- docs(authentication): add Auth and streaming, fix code fences and
imports (#95056)

---------
Co-authored-by: 's avatarthsid <63248890+thsid@users.noreply.github.com>
Co-authored-by: 's avatarMarco Dotzler <122102508+M4cM4rco@users.noreply.github.com>
Co-authored-by: 's avatarPranav <mohnapranav@gmail.com>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarAnkur Prajapati <91510065+ankurdotio@users.noreply.github.com>
Co-authored-by: 's avatarWildCharger <46546991+WildChargerTV@users.noreply.github.com>
Co-authored-by: 's avatarDavid GG <hola@davidgg.es>
Co-authored-by: 's avatarGiles Thompson <giles@papaiti.com>
Co-authored-by: 's avatarJahanzaib iqbal <78400134+jahanzaib-iqbal-dev@users.noreply.github.com>
parent 9beca082
...@@ -348,6 +348,39 @@ You can enable the plugin in VS Code by: ...@@ -348,6 +348,39 @@ You can enable the plugin in VS Code by:
See the [TypeScript reference](/docs/app/api-reference/config/typescript) page for more information. See the [TypeScript reference](/docs/app/api-reference/config/typescript) page for more information.
<AppOnly>
## Set up your editor
The App Router names files by convention, like `page.tsx`, `layout.tsx`, and `route.ts`, so your editor quickly fills with same-named tabs. Label each tab with its enclosing folders, like `blog/[id]`, so you can tell them apart.
In VS Code 1.88+ or Cursor, add [custom editor labels](https://code.visualstudio.com/updates/v1_88#_customize-editor-labels) to `.vscode/settings.json`. Labeling two folders deep keeps dynamic routes like `blog/[id]/page.tsx` from all collapsing to the same `[id]` label:
```json filename=".vscode/settings.json"
{
"workbench.editor.customLabels.patterns": {
"**/app/**/page.tsx": "${dirname(1)}/${dirname} - page.tsx",
"**/app/**/layout.tsx": "${dirname(1)}/${dirname} - layout.tsx",
"**/app/**/loading.tsx": "${dirname(1)}/${dirname} - loading.tsx",
"**/app/**/error.tsx": "${dirname(1)}/${dirname} - error.tsx",
"**/app/**/not-found.tsx": "${dirname(1)}/${dirname} - not-found.tsx",
"**/app/**/template.tsx": "${dirname(1)}/${dirname} - template.tsx",
"**/app/**/default.tsx": "${dirname(1)}/${dirname} - default.tsx",
"**/app/**/route.ts": "${dirname(1)}/${dirname} - route.ts"
}
}
```
Or copy this prompt to have your coding agent set it up:
```prompt
Set up custom editor labels so my Next.js App Router files are easy to tell apart. Read https://nextjs.org/docs/app/getting-started/installation#set-up-your-editor and add the workbench.editor.customLabels.patterns config shown there to my .vscode/settings.json, creating the file if it doesn't exist. Adjust the labels to taste. If I use a different editor, apply the equivalent setting or tell me it's automatic, and leave my other settings untouched.
```
> **Good to know:** JetBrains IDEs (WebStorm, IntelliJ) show the folder for same-named files automatically, so no setup is needed.
</AppOnly>
## Set up linting ## Set up linting
Next.js supports linting with either ESLint or Biome. Choose a linter and run it directly via `package.json` scripts. Next.js supports linting with either ESLint or Biome. Choose a linter and run it directly via `package.json` scripts.
......
...@@ -368,7 +368,7 @@ To organize routes without affecting the URL, create a group to keep related rou ...@@ -368,7 +368,7 @@ To organize routes without affecting the URL, create a group to keep related rou
height="930" height="930"
/> />
Even though routes inside `(marketing)` and `(shop)` share the same URL hierarchy, you can create a different layout for each group by adding a `layout.js` file inside their folders. Even though routes inside `(marketing)` and `(shop)` share the same URL hierarchy, you can create a different layout for each group by adding a `layout.js` file inside their folders. These layouts nest within the existing app layout.
<Image <Image
alt="Route Groups with Multiple Layouts" alt="Route Groups with Multiple Layouts"
......
...@@ -374,7 +374,7 @@ export default function BlogPage() { ...@@ -374,7 +374,7 @@ export default function BlogPage() {
Sequential data fetching happens when one request depends on data from another. Sequential data fetching happens when one request depends on data from another.
For example, `<Playlists>` can only fetch data after `<Artist>` completes because it needs the `artistID`: For example, `<Playlists>` can only fetch data after `getArtist()` resolves because it needs the `artistID`:
```tsx filename="app/artist/[username]/page.tsx" switcher ```tsx filename="app/artist/[username]/page.tsx" switcher
export default async function Page({ export default async function Page({
......
...@@ -118,7 +118,7 @@ See the [`revalidateTag` API reference](/docs/app/api-reference/functions/revali ...@@ -118,7 +118,7 @@ See the [`revalidateTag` API reference](/docs/app/api-reference/functions/revali
## `updateTag` ## `updateTag`
`updateTag` immediately expires cached data for read-your-own-writes scenarios — the user sees their change right away instead of stale content. Unlike `revalidateTag`, it can only be used in [Server Actions](/docs/app/getting-started/mutating-data). `updateTag` immediately expires cached data for read-your-own-writes scenarios — the user sees their change right away instead of stale content. Unlike `revalidateTag`, it can only be used in [Server Actions](/docs/app/guides/server-actions).
```tsx filename="app/lib/actions.ts" highlight={1,12} switcher ```tsx filename="app/lib/actions.ts" highlight={1,12} switcher
import { updateTag } from 'next/cache' import { updateTag } from 'next/cache'
......
...@@ -878,7 +878,7 @@ To create and manage database sessions, you'll need to follow these steps: ...@@ -878,7 +878,7 @@ To create and manage database sessions, you'll need to follow these steps:
For example: For example:
```ts filename="app/lib/session.ts" switcher ```ts filename="app/lib/session.ts" switcher
import cookies from 'next/headers' import { cookies } from 'next/headers'
import { db } from '@/app/lib/db' import { db } from '@/app/lib/db'
import { encrypt } from '@/app/lib/session' import { encrypt } from '@/app/lib/session'
...@@ -913,7 +913,7 @@ export async function createSession(id: number) { ...@@ -913,7 +913,7 @@ export async function createSession(id: number) {
``` ```
```js filename="app/lib/session.js" switcher ```js filename="app/lib/session.js" switcher
import cookies from 'next/headers' import { cookies } from 'next/headers'
import { db } from '@/app/lib/db' import { db } from '@/app/lib/db'
import { encrypt } from '@/app/lib/session' import { encrypt } from '@/app/lib/session'
...@@ -1351,9 +1351,17 @@ Due to [Partial Rendering](/docs/app/getting-started/linking-and-navigating#clie ...@@ -1351,9 +1351,17 @@ Due to [Partial Rendering](/docs/app/getting-started/linking-and-navigating#clie
Instead, you should do the checks close to your data source or the component that'll be conditionally rendered. Instead, you should do the checks close to your data source or the component that'll be conditionally rendered.
For example, consider a shared layout that fetches the user data and displays the user image in a nav. Instead of doing the auth check in the layout, you should fetch the user data (`getUser()`) in the layout and do the auth check in your DAL. For example, consider a shared layout that fetches the user data and displays the user image in a nav. Instead of doing the auth check in the layout, you should fetch the user data (`getUser()`) in the layout and do the auth check in your [DAL](#creating-a-data-access-layer-dal).
This guarantees that wherever `getUser()` is called within your application, the auth check is performed, and prevents developers from forgetting to check that the user is authorized to access the data.
#### Auth and streaming
This guarantees that wherever `getUser()` is called within your application, the auth check is performed, and prevents developers forgetting to check the user is authorized to access the data. Session and user data often appear in shell UI (header, nav) that repeats across routes. A top-level `await` on `cookies()`, `headers()`, or the DAL in a layout delays the first streamed chunk for that segment and holds `{children}` behind that work.
If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern.
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Sharing data with context and `React.cache`](/docs/app/getting-started/fetching-data#sharing-data-with-context-and-reactcache).
#### Auth checks in page components #### Auth checks in page components
...@@ -1448,7 +1456,7 @@ This pattern allows you to show or hide UI elements based on user permissions wh ...@@ -1448,7 +1456,7 @@ This pattern allows you to show or hide UI elements based on user permissions wh
### Server Actions ### Server Actions
Treat [Server Actions](/docs/app/getting-started/mutating-data) with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation. Treat [Server Actions](/docs/app/guides/server-actions) with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation.
In the example below, we check the user's role before allowing the action to proceed: In the example below, we check the user's role before allowing the action to proceed:
...@@ -1546,7 +1554,7 @@ Using context providers for auth works due to [interleaving](/docs/app/getting-s ...@@ -1546,7 +1554,7 @@ Using context providers for auth works due to [interleaving](/docs/app/getting-s
This works, but any child Server Components will be rendered on the server first, and will not have access to the context provider’s session data: This works, but any child Server Components will be rendered on the server first, and will not have access to the context provider’s session data:
```tsx filename="app/layout.ts" switcher ```tsx filename="app/layout.tsx" switcher
import { ContextProvider } from 'auth-lib' import { ContextProvider } from 'auth-lib'
export default function RootLayout({ children }) { export default function RootLayout({ children }) {
...@@ -1560,8 +1568,8 @@ export default function RootLayout({ children }) { ...@@ -1560,8 +1568,8 @@ export default function RootLayout({ children }) {
} }
``` ```
```tsx filename="app/ui/profile.ts switcher ```tsx filename="app/ui/profile.tsx" switcher
'use client'; 'use client'
import { useSession } from "auth-lib"; import { useSession } from "auth-lib";
...@@ -1575,8 +1583,8 @@ export default function Profile() { ...@@ -1575,8 +1583,8 @@ export default function Profile() {
} }
``` ```
```jsx filename="app/ui/profile.js switcher ```jsx filename="app/ui/profile.jsx" switcher
'use client'; 'use client'
import { useSession } from "auth-lib"; import { useSession } from "auth-lib";
......
...@@ -897,7 +897,7 @@ For these, use community libraries like [`swr`](https://swr.vercel.app/) or [`re ...@@ -897,7 +897,7 @@ For these, use community libraries like [`swr`](https://swr.vercel.app/) or [`re
### Server Actions ### Server Actions
Server Actions let you run server-side code from the client. Their primary purpose is to mutate data from your frontend client. [Server Actions](/docs/app/guides/server-actions) let you run server-side code from the client. Their primary purpose is to mutate data from your frontend client.
Server Actions are queued. Using them for data fetching introduces sequential execution. Server Actions are queued. Using them for data fetching introduces sequential execution.
......
...@@ -8,7 +8,7 @@ description: Learn how to debug your Next.js application with VS Code, Chrome De ...@@ -8,7 +8,7 @@ description: Learn how to debug your Next.js application with VS Code, Chrome De
This documentation explains how you can debug your Next.js frontend and backend code with full source maps support using the [VS Code debugger](https://code.visualstudio.com/docs/editor/debugging), [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools), or [Firefox DevTools](https://firefox-source-docs.mozilla.org/devtools-user/). This documentation explains how you can debug your Next.js frontend and backend code with full source maps support using the [VS Code debugger](https://code.visualstudio.com/docs/editor/debugging), [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools), or [Firefox DevTools](https://firefox-source-docs.mozilla.org/devtools-user/).
Any debugger that can attach to Node.js can also be used to debug a Next.js application. You can find more details in the Node.js [Debugging Guide](https://nodejs.org/en/docs/guides/debugging-getting-started/). Any debugger that can attach to Node.js can also be used to debug a Next.js application. You can find more details in the Node.js [Debugging Guide](https://nodejs.org/learn/getting-started/debugging/).
## Debugging with VS Code ## Debugging with VS Code
...@@ -137,7 +137,7 @@ Launching the Next.js server with the `--inspect` flag will look something like ...@@ -137,7 +137,7 @@ Launching the Next.js server with the `--inspect` flag will look something like
```bash filename="Terminal" ```bash filename="Terminal"
Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95 Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95
For help, see: https://nodejs.org/en/docs/inspector For help, see: https://nodejs.org/learn/getting-started/debugging
ready - started server on 0.0.0.0:3000, url: http://localhost:3000 ready - started server on 0.0.0.0:3000, url: http://localhost:3000
``` ```
......
...@@ -525,18 +525,20 @@ The `pages` directory uses `getServerSideProps` and `getStaticProps` to fetch da ...@@ -525,18 +525,20 @@ The `pages` directory uses `getServerSideProps` and `getStaticProps` to fetch da
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
export default async function Page() { export default async function Page() {
// This request should be cached until manually invalidated. // Opt into the Next.js Data Cache for this request.
// The cached response can be reused across requests and revalidated on demand.
// Similar to `getStaticProps`. // Similar to `getStaticProps`.
// `force-cache` is the default and can be omitted. const cachedData = await fetch('https://...', { cache: 'force-cache' })
const staticData = await fetch(`https://...`, { cache: 'force-cache' })
// This request should be refetched on every request. // Opt out of caching for this request.
// Next.js fetches this from the data source on every request.
// This is the default fetch behavior.
// Similar to `getServerSideProps`. // Similar to `getServerSideProps`.
const dynamicData = await fetch(`https://...`, { cache: 'no-store' }) const uncachedData = await fetch('https://...', { cache: 'no-store' })
// This request should be cached with a lifetime of 10 seconds. // Cache this request, but revalidate it at most every 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option. // Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, { const revalidatedData = await fetch('https://...', {
next: { revalidate: 10 }, next: { revalidate: 10 },
}) })
...@@ -546,18 +548,20 @@ export default async function Page() { ...@@ -546,18 +548,20 @@ export default async function Page() {
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
export default async function Page() { export default async function Page() {
// This request should be cached until manually invalidated. // Opt into the Next.js Data Cache for this request.
// The cached response can be reused across requests and revalidated on demand.
// Similar to `getStaticProps`. // Similar to `getStaticProps`.
// `force-cache` is the default and can be omitted. const cachedData = await fetch('https://...', { cache: 'force-cache' })
const staticData = await fetch(`https://...`, { cache: 'force-cache' })
// This request should be refetched on every request. // Opt out of caching for this request.
// Next.js fetches this from the data source on every request.
// This is the default fetch behavior.
// Similar to `getServerSideProps`. // Similar to `getServerSideProps`.
const dynamicData = await fetch(`https://...`, { cache: 'no-store' }) const uncachedData = await fetch('https://...', { cache: 'no-store' })
// This request should be cached with a lifetime of 10 seconds. // Cache this request, but revalidate it at most every 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option. // Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, { const revalidatedData = await fetch('https://...', {
next: { revalidate: 10 }, next: { revalidate: 10 },
}) })
......
...@@ -25,7 +25,7 @@ Next.js can automatically code split your JavaScript bundles, and generate multi ...@@ -25,7 +25,7 @@ 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. 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/getting-started/mutating-data), 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, 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.
## Examples ## Examples
......
...@@ -358,6 +358,8 @@ server { ...@@ -358,6 +358,8 @@ server {
} }
``` ```
To deploy to GitHub Pages, use our [template](https://github.com/nextjs/deploy-github-pages) to create a new project or as a reference for configuring an existing project.
## Version History ## Version History
| Version | Changes | | Version | Changes |
......
...@@ -401,6 +401,6 @@ export default async function PostPage({ params }) { ...@@ -401,6 +401,6 @@ export default async function PostPage({ params }) {
} }
``` ```
See the [Server Actions](/docs/app/getting-started/mutating-data) docs for more examples. See [Mutating data](/docs/app/getting-started/mutating-data) for more examples.
</AppOnly> </AppOnly>
...@@ -162,6 +162,8 @@ In most cases, you should use [`unstable_retry()`](#unstable_retry) instead. How ...@@ -162,6 +162,8 @@ In most cases, you should use [`unstable_retry()`](#unstable_retry) instead. How
While less common, you can handle errors in the root layout or template using `global-error.jsx`, located in the root app directory, even when leveraging [internationalization](/docs/app/guides/internationalization). Global error UI must define its own `<html>` and `<body>` tags, global styles, fonts, or other dependencies that your error page requires. This file replaces the root layout or template when active. While less common, you can handle errors in the root layout or template using `global-error.jsx`, located in the root app directory, even when leveraging [internationalization](/docs/app/guides/internationalization). Global error UI must define its own `<html>` and `<body>` tags, global styles, fonts, or other dependencies that your error page requires. This file replaces the root layout or template when active.
> **Good to know**: `global-error` and the built-in 500 page render their own document and do **not** include your global styles, so an app-level theme toggle (a class or `data-theme` attribute) won't reach them. The default UI follows the OS color scheme; to match your app's theme, apply it inside your own `global-error` component.
> **Good to know**: Error boundaries must be [Client Components](/docs/app/getting-started/server-and-client-components#using-client-components), which means that [`metadata` and `generateMetadata`](/docs/app/getting-started/metadata-and-og-images) exports are not supported in `global-error.jsx`. As an alternative, you can use the React [`<title>`](https://react.dev/reference/react-dom/components/title) component. > **Good to know**: Error boundaries must be [Client Components](/docs/app/getting-started/server-and-client-components#using-client-components), which means that [`metadata` and `generateMetadata`](/docs/app/getting-started/metadata-and-og-images) exports are not supported in `global-error.jsx`. As an alternative, you can use the React [`<title>`](https://react.dev/reference/react-dom/components/title) component.
```tsx filename="app/global-error.tsx" switcher ```tsx filename="app/global-error.tsx" switcher
......
...@@ -42,11 +42,13 @@ export default function NotFound() { ...@@ -42,11 +42,13 @@ export default function NotFound() {
In the [component hierarchy](/docs/app/getting-started/project-structure#component-hierarchy), `not-found.js` renders between `loading.js` and `page.js`. It is wrapped by the `<Suspense>` boundary from `loading.js` and the error boundary from `error.js` in the same segment. In the [component hierarchy](/docs/app/getting-started/project-structure#component-hierarchy), `not-found.js` renders between `loading.js` and `page.js`. It is wrapped by the `<Suspense>` boundary from `loading.js` and the error boundary from `error.js` in the same segment.
> **Good to know**: The default not found UI follows the operating system's color scheme via `prefers-color-scheme` and does not read an app-level theme (such as a class or `data-theme` attribute on `<html>`). Because it renders inside your root layout, the quickest way to match an explicit theme is to add a higher-specificity rule pair in your global stylesheet, scoped to your theme selector — for example `html[data-theme='light'] body` and `html[data-theme='dark'] body`. For full control over the markup, provide your own `not-found.js`.
## `global-not-found.js` (experimental) ## `global-not-found.js` (experimental)
The `global-not-found.js` file lets you define a 404 page for your entire application. Unlike `not-found.js`, which works at the route level, this is used when a requested URL doesn't match any route at all. Next.js **skips rendering** and directly returns this global page. The `global-not-found.js` file lets you define a 404 page for your entire application. Unlike `not-found.js`, which works at the route level, this is used when a requested URL doesn't match any route at all. Next.js **skips rendering** and directly returns this global page.
The `global-not-found.js` file bypasses your app's normal rendering, which means you'll need to import any global styles, fonts, or other dependencies that your 404 page requires. The `global-not-found.js` file bypasses your app's normal rendering, which means you'll need to import any global styles, fonts, or other dependencies that your 404 page requires. This includes your theme: because `global-not-found.js` bypasses your layout, the OS color scheme is the only signal the default UI sees, so apply your theme (class or attribute) inside this file.
> **Good to know**: A smaller version of your global styles, and a simpler font family could improve performance of this page. > **Good to know**: A smaller version of your global styles, and a simpler font family could improve performance of this page.
......
...@@ -4,6 +4,7 @@ description: API Reference for the redirect function. ...@@ -4,6 +4,7 @@ description: API Reference for the redirect function.
related: related:
links: links:
- app/api-reference/functions/permanentRedirect - app/api-reference/functions/permanentRedirect
- app/guides/server-actions
--- ---
The `redirect` function allows you to redirect the user to another URL. `redirect` can be used while rendering in [Server and Client Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data). The `redirect` function allows you to redirect the user to another URL. `redirect` can be used while rendering in [Server and Client Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data).
......
--- ---
title: refresh title: refresh
description: API Reference for the refresh function. description: API Reference for the refresh function.
related:
links:
- app/guides/server-actions
--- ---
`refresh` allows you to refresh the client router from within a [Server Action](/docs/app/getting-started/mutating-data). `refresh` allows you to refresh the client router from within a [Server Action](/docs/app/guides/server-actions).
## Usage ## Usage
......
--- ---
title: revalidatePath title: revalidatePath
description: API Reference for the revalidatePath function. description: API Reference for the revalidatePath function.
related:
links:
- app/guides/server-actions
--- ---
`revalidatePath` allows you to invalidate [cached data](/docs/app/getting-started/caching) on-demand for a specific path. `revalidatePath` allows you to invalidate [cached data](/docs/app/getting-started/caching) on-demand for a specific path.
......
--- ---
title: revalidateTag title: revalidateTag
description: API Reference for the revalidateTag function. description: API Reference for the revalidateTag function.
related:
links:
- app/guides/server-actions
--- ---
`revalidateTag` allows you to invalidate cached data on-demand for a specific cache tag. `revalidateTag` allows you to invalidate cached data on-demand for a specific cache tag.
......
...@@ -72,20 +72,20 @@ export default async function Page({ ...@@ -72,20 +72,20 @@ export default async function Page({
``` ```
```jsx filename="app/page.jsx" switcher ```jsx filename="app/page.jsx" switcher
import { unstable_cache } from 'next/cache'; import { unstable_cache } from 'next/cache'
export default async function Page({ params } }) { export default async function Page({ params }) {
const { userId } = await params const { userId } = await params
const getCachedUser = unstable_cache( const getCachedUser = unstable_cache(
async () => { async () => {
return { id: userId }; return { id: userId }
}, },
[userId], // add the user ID to the cache key [userId], // add the user ID to the cache key
{ {
tags: ["users"], tags: ['users'],
revalidate: 60, revalidate: 60,
} }
); )
//... //...
} }
......
...@@ -83,7 +83,7 @@ If a route is [prerendered](/docs/app/glossary#prerendering), calling `useSearch ...@@ -83,7 +83,7 @@ If a route is [prerendered](/docs/app/glossary#prerendering), calling `useSearch
This allows a part of the route to be prerendered while the dynamic part that uses `useSearchParams` is client-side rendered. This allows a part of the route to be prerendered while the dynamic part that uses `useSearchParams` is client-side rendered.
We recommend wrapping the Client Component that uses `useSearchParams` in a `<Suspense/>` boundary. This will allow any Client Components above it to be prerendered and sent as part of initial HTML. [Example](/docs/app/api-reference/functions/use-search-params#prerendering). We recommend wrapping the Client Component that uses `useSearchParams` in a `<Suspense/>` boundary. This will allow any Client Components above it to be prerendered and sent as part of initial HTML.
For example: For example:
......
...@@ -11,7 +11,7 @@ To set custom HTTP headers you can use the `headers` key in `next.config.js`: ...@@ -11,7 +11,7 @@ To set custom HTTP headers you can use the `headers` key in `next.config.js`:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
source: '/about', source: '/about',
...@@ -31,7 +31,7 @@ module.exports = { ...@@ -31,7 +31,7 @@ module.exports = {
} }
``` ```
`headers` is an async function that expects an array to be returned holding objects with `source` and `headers` properties: `headers` can be defined as a synchronous or async function. It should return, or resolve to, an array of objects with `source` and `headers` properties:
- `source` is the incoming request path pattern. - `source` is the incoming request path pattern.
- `headers` is an array of response header objects, with `key` and `value` properties. - `headers` is an array of response header objects, with `key` and `value` properties.
...@@ -48,7 +48,7 @@ If two headers match the same path and set the same header key, the last header ...@@ -48,7 +48,7 @@ If two headers match the same path and set the same header key, the last header
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
source: '/:path*', source: '/:path*',
...@@ -79,7 +79,7 @@ Path matches are allowed, for example `/blog/:slug` will match `/blog/first-post ...@@ -79,7 +79,7 @@ Path matches are allowed, for example `/blog/:slug` will match `/blog/first-post
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
source: '/blog/:slug', source: '/blog/:slug',
...@@ -111,7 +111,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/: ...@@ -111,7 +111,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
source: '/blog/:slug*', source: '/blog/:slug*',
...@@ -137,7 +137,7 @@ To match a regex path you can wrap the regex in parenthesis after a parameter, f ...@@ -137,7 +137,7 @@ To match a regex path you can wrap the regex in parenthesis after a parameter, f
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
source: '/blog/:post(\\d{1,})', source: '/blog/:post(\\d{1,})',
...@@ -157,7 +157,7 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg ...@@ -157,7 +157,7 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
{ {
// this will match `/english(default)/something` being requested // this will match `/english(default)/something` being requested
...@@ -186,7 +186,7 @@ To only apply a header when header, cookie, or query values also match the `has` ...@@ -186,7 +186,7 @@ To only apply a header when header, cookie, or query values also match the `has`
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async headers() { headers() {
return [ return [
// if the header `x-add-header` is present, // if the header `x-add-header` is present,
// the `x-another-header` header will be applied // the `x-another-header` header will be applied
...@@ -296,7 +296,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config- ...@@ -296,7 +296,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config-
module.exports = { module.exports = {
basePath: '/docs', basePath: '/docs',
async headers() { headers() {
return [ return [
{ {
source: '/with-basePath', // becomes /docs/with-basePath source: '/with-basePath', // becomes /docs/with-basePath
...@@ -343,7 +343,7 @@ module.exports = { ...@@ -343,7 +343,7 @@ module.exports = {
defaultLocale: 'en', defaultLocale: 'en',
}, },
async headers() { headers() {
return [ return [
{ {
source: '/with-locale', // automatically handles all locales source: '/with-locale', // automatically handles all locales
...@@ -486,7 +486,7 @@ export async function getServerSideProps({ req, res }) { ...@@ -486,7 +486,7 @@ export async function getServerSideProps({ req, res }) {
[Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/docs/Web/HTTP/CORS) is a security feature that allows you to control which sites can access your resources. You can set the `Access-Control-Allow-Origin` header to allow a specific origin to access your <PagesOnly>API Endpoints</PagesOnly><AppOnly>Route Handlers</AppOnly>. [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/docs/Web/HTTP/CORS) is a security feature that allows you to control which sites can access your resources. You can set the `Access-Control-Allow-Origin` header to allow a specific origin to access your <PagesOnly>API Endpoints</PagesOnly><AppOnly>Route Handlers</AppOnly>.
```js ```js
async headers() { headers() {
return [ return [
{ {
source: "/api/:path*", source: "/api/:path*",
......
...@@ -11,7 +11,7 @@ To use redirects you can use the `redirects` key in `next.config.js`: ...@@ -11,7 +11,7 @@ To use redirects you can use the `redirects` key in `next.config.js`:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
source: '/about', source: '/about',
...@@ -23,7 +23,7 @@ module.exports = { ...@@ -23,7 +23,7 @@ module.exports = {
} }
``` ```
`redirects` is an async function that expects an array to be returned holding objects with `source`, `destination`, and `permanent` properties: `redirects` can be defined as a synchronous or async function. It should return, or resolve to, an array of objects with `source`, `destination`, and `permanent` properties:
- `source` is the incoming request path pattern. - `source` is the incoming request path pattern.
- `destination` is the path you want to route to. - `destination` is the path you want to route to.
...@@ -60,7 +60,7 @@ Path matches are allowed, for example `/old-blog/:slug` will match `/old-blog/fi ...@@ -60,7 +60,7 @@ Path matches are allowed, for example `/old-blog/:slug` will match `/old-blog/fi
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
source: '/old-blog/:slug', source: '/old-blog/:slug',
...@@ -84,7 +84,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/: ...@@ -84,7 +84,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
source: '/blog/:slug*', source: '/blog/:slug*',
...@@ -102,7 +102,7 @@ To match a regex path you can wrap the regex in parentheses after a parameter, f ...@@ -102,7 +102,7 @@ To match a regex path you can wrap the regex in parentheses after a parameter, f
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
source: '/post/:slug(\\d{1,})', source: '/post/:slug(\\d{1,})',
...@@ -118,7 +118,7 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg ...@@ -118,7 +118,7 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
// this will match `/english(default)/something` being requested // this will match `/english(default)/something` being requested
...@@ -143,7 +143,7 @@ To only match a redirect when header, cookie, or query values also match the `ha ...@@ -143,7 +143,7 @@ To only match a redirect when header, cookie, or query values also match the `ha
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
// if the header `x-redirect-me` is present, // if the header `x-redirect-me` is present,
// this redirect will be applied // this redirect will be applied
...@@ -233,7 +233,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config- ...@@ -233,7 +233,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config-
module.exports = { module.exports = {
basePath: '/docs', basePath: '/docs',
async redirects() { redirects() {
return [ return [
{ {
source: '/with-basePath', // automatically becomes /docs/with-basePath source: '/with-basePath', // automatically becomes /docs/with-basePath
...@@ -262,7 +262,7 @@ For dynamic or per-request locale handling, use [dynamic route segments and prox ...@@ -262,7 +262,7 @@ For dynamic or per-request locale handling, use [dynamic route segments and prox
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async redirects() { redirects() {
return [ return [
{ {
// Manually handle locale prefixes for App Router // Manually handle locale prefixes for App Router
...@@ -306,7 +306,7 @@ module.exports = { ...@@ -306,7 +306,7 @@ module.exports = {
defaultLocale: 'en', defaultLocale: 'en',
}, },
async redirects() { redirects() {
return [ return [
{ {
source: '/with-locale', // automatically handles all locales source: '/with-locale', // automatically handles all locales
......
...@@ -23,7 +23,7 @@ To use rewrites you can use the `rewrites` key in `next.config.js`: ...@@ -23,7 +23,7 @@ To use rewrites you can use the `rewrites` key in `next.config.js`:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/about', source: '/about',
...@@ -36,7 +36,7 @@ module.exports = { ...@@ -36,7 +36,7 @@ module.exports = {
Rewrites are applied to client-side routing. In the example above, navigating to `<Link href="/about">` will serve content from `/` while keeping the URL as `/about`. Rewrites are applied to client-side routing. In the example above, navigating to `<Link href="/about">` will serve content from `/` while keeping the URL as `/about`.
`rewrites` is an async function that expects to return either an array or an object of arrays (see below) holding objects with `source` and `destination` properties: `rewrites` can be defined as a synchronous or async function. It should return, or resolve to, either an array or an object of arrays (see below) holding objects with `source` and `destination` properties:
- `source`: `String` - is the incoming request path pattern. - `source`: `String` - is the incoming request path pattern.
- `destination`: `String` is the path you want to route to. - `destination`: `String` is the path you want to route to.
...@@ -49,7 +49,7 @@ When the `rewrites` function returns an array, rewrites are applied after checki ...@@ -49,7 +49,7 @@ When the `rewrites` function returns an array, rewrites are applied after checki
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return { return {
beforeFiles: [ beforeFiles: [
// These rewrites are checked after headers/redirects // These rewrites are checked after headers/redirects
...@@ -117,7 +117,7 @@ When using parameters in a rewrite the parameters will be passed in the query by ...@@ -117,7 +117,7 @@ When using parameters in a rewrite the parameters will be passed in the query by
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/old-about/:path*', source: '/old-about/:path*',
...@@ -132,7 +132,7 @@ If a parameter is used in the destination none of the parameters will be automat ...@@ -132,7 +132,7 @@ If a parameter is used in the destination none of the parameters will be automat
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/docs/:path*', source: '/docs/:path*',
...@@ -147,7 +147,7 @@ You can still pass the parameters manually in the query if one is already used i ...@@ -147,7 +147,7 @@ You can still pass the parameters manually in the query if one is already used i
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/:first/:second', source: '/:first/:second',
...@@ -169,7 +169,7 @@ Path matches are allowed, for example `/blog/:slug` will match `/blog/first-post ...@@ -169,7 +169,7 @@ Path matches are allowed, for example `/blog/:slug` will match `/blog/first-post
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/blog/:slug', source: '/blog/:slug',
...@@ -192,7 +192,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/: ...@@ -192,7 +192,7 @@ To match a wildcard path you can use `*` after a parameter, for example `/blog/:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/blog/:slug*', source: '/blog/:slug*',
...@@ -209,7 +209,7 @@ To match a regex path you can wrap the regex in parenthesis after a parameter, f ...@@ -209,7 +209,7 @@ To match a regex path you can wrap the regex in parenthesis after a parameter, f
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/old-blog/:post(\\d{1,})', source: '/old-blog/:post(\\d{1,})',
...@@ -224,7 +224,7 @@ The following characters `(`, `)`, `{`, `}`, `[`, `]`, `|`, `\`, `^`, `.`, `:`, ...@@ -224,7 +224,7 @@ The following characters `(`, `)`, `{`, `}`, `[`, `]`, `|`, `\`, `^`, `.`, `:`,
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
// this will match `/english(default)/something` being requested // this will match `/english(default)/something` being requested
...@@ -248,7 +248,7 @@ To only match a rewrite when header, cookie, or query values also match the `has ...@@ -248,7 +248,7 @@ To only match a rewrite when header, cookie, or query values also match the `has
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
// if the header `x-rewrite-me` is present, // if the header `x-rewrite-me` is present,
// this rewrite will be applied // this rewrite will be applied
...@@ -338,7 +338,7 @@ Rewrites allow you to rewrite to an external URL. This is especially useful for ...@@ -338,7 +338,7 @@ Rewrites allow you to rewrite to an external URL. This is especially useful for
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return [ return [
{ {
source: '/blog', source: '/blog',
...@@ -358,7 +358,7 @@ If you're using `trailingSlash: true`, you also need to insert a trailing slash ...@@ -358,7 +358,7 @@ If you're using `trailingSlash: true`, you also need to insert a trailing slash
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
trailingSlash: true, trailingSlash: true,
async rewrites() { rewrites() {
return [ return [
{ {
source: '/blog/', source: '/blog/',
...@@ -381,7 +381,7 @@ This way you don't have to change the rewrites configuration when migrating more ...@@ -381,7 +381,7 @@ This way you don't have to change the rewrites configuration when migrating more
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
async rewrites() { rewrites() {
return { return {
fallback: [ fallback: [
{ {
...@@ -402,7 +402,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config- ...@@ -402,7 +402,7 @@ When leveraging [`basePath` support](/docs/app/api-reference/config/next-config-
module.exports = { module.exports = {
basePath: '/docs', basePath: '/docs',
async rewrites() { rewrites() {
return [ return [
{ {
source: '/with-basePath', // automatically becomes /docs/with-basePath source: '/with-basePath', // automatically becomes /docs/with-basePath
...@@ -433,7 +433,7 @@ module.exports = { ...@@ -433,7 +433,7 @@ module.exports = {
defaultLocale: 'en', defaultLocale: 'en',
}, },
async rewrites() { rewrites() {
return [ return [
{ {
source: '/with-locale', // automatically handles all locales source: '/with-locale', // automatically handles all locales
......
--- ---
title: serverActions title: serverActions
description: Configure Server Actions behavior in your Next.js application. description: Configure Server Actions behavior in your Next.js application.
related:
links:
- app/guides/server-actions
--- ---
Options for configuring Server Actions behavior in your Next.js application. Options for configuring Server Actions behavior in your Next.js application. For how Server Actions work, including the security boundary these options tune, see the [Server Actions guide](/docs/app/guides/server-actions).
## `allowedOrigins` ## `allowedOrigins`
......
...@@ -5,9 +5,6 @@ description: Use `@next/routing` to apply Next.js route matching behavior in ada ...@@ -5,9 +5,6 @@ description: Use `@next/routing` to apply Next.js route matching behavior in ada
You can use [`@next/routing`](https://www.npmjs.com/package/@next/routing) to reproduce Next.js route matching behavior with data from `onBuildComplete`. You can use [`@next/routing`](https://www.npmjs.com/package/@next/routing) to reproduce Next.js route matching behavior with data from `onBuildComplete`.
> [!NOTE]
> `@next/routing` is experimental and will stabilize with the adapters API.
```typescript ```typescript
import { resolveRoutes } from '@next/routing' import { resolveRoutes } from '@next/routing'
......
...@@ -36,10 +36,10 @@ export default function handler(req, res) { ...@@ -36,10 +36,10 @@ export default function handler(req, res) {
Then, call the API Route from the client with an event handler: Then, call the API Route from the client with an event handler:
```tsx filename="pages/index.tsx" switcher ```tsx filename="pages/index.tsx" switcher
import { FormEvent } from 'react' import { SubmitEvent } from 'react'
export default function Page() { export default function Page() {
async function onSubmit(event: FormEvent<HTMLFormElement>) { async function onSubmit(event: SubmitEvent<HTMLFormElement>) {
event.preventDefault() event.preventDefault()
const formData = new FormData(event.currentTarget) const formData = new FormData(event.currentTarget)
...@@ -133,13 +133,13 @@ export default async function handler(req, res) { ...@@ -133,13 +133,13 @@ export default async function handler(req, res) {
You can use React state to show an error message when a form submission fails: You can use React state to show an error message when a form submission fails:
```tsx filename="pages/index.tsx" switcher ```tsx filename="pages/index.tsx" switcher
import React, { useState, FormEvent } from 'react' import React, { useState, SubmitEvent } from 'react'
export default function Page() { export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false) const [isLoading, setIsLoading] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
async function onSubmit(event: FormEvent<HTMLFormElement>) { async function onSubmit(event: SubmitEvent<HTMLFormElement>) {
event.preventDefault() event.preventDefault()
setIsLoading(true) setIsLoading(true)
setError(null) // Clear previous errors when a new request starts setError(null) // Clear previous errors when a new request starts
...@@ -235,12 +235,12 @@ export default function Page() { ...@@ -235,12 +235,12 @@ export default function Page() {
You can use React state to show a loading state when a form is submitting on the server: You can use React state to show a loading state when a form is submitting on the server:
```tsx filename="pages/index.tsx" switcher ```tsx filename="pages/index.tsx" switcher
import React, { useState, FormEvent } from 'react' import React, { useState, SubmitEvent } from 'react'
export default function Page() { export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false) const [isLoading, setIsLoading] = useState<boolean>(false)
async function onSubmit(event: FormEvent<HTMLFormElement>) { async function onSubmit(event: SubmitEvent<HTMLFormElement>) {
event.preventDefault() event.preventDefault()
setIsLoading(true) // Set loading to true when the request starts setIsLoading(true) // Set loading to true when the request starts
......
...@@ -9,6 +9,8 @@ A 404 page may be accessed very often. Server-rendering an error page for every ...@@ -9,6 +9,8 @@ A 404 page may be accessed very often. Server-rendering an error page for every
To avoid the above pitfalls, Next.js provides a static 404 page by default without having to add any additional files. To avoid the above pitfalls, Next.js provides a static 404 page by default without having to add any additional files.
> **Good to know**: The default 404 and 500 pages follow the operating system's color scheme via `prefers-color-scheme` and do not read an app-level theme. Because `pages/404.js` and `pages/500.js` render inside your custom `App`, providing your own files lets your global styles and theme apply.
### Customizing The 404 Page ### Customizing The 404 Page
To create a custom 404 page you can create a `pages/404.js` file. This file is statically generated at build time. To create a custom 404 page you can create a `pages/404.js` file. This file is statically generated at build time.
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
Shared route resolving package for Next.js. Shared route resolving package for Next.js.
**NOTE: This package is experimental and will become stable along with adapters API**
## Overview ## Overview
This package provides a comprehensive route resolution system that handles rewrites, redirects, middleware invocation, and dynamic route matching with support for conditional routing based on headers, cookies, queries, and host. This package provides a comprehensive route resolution system that handles rewrites, redirects, middleware invocation, and dynamic route matching with support for conditional routing based on headers, cookies, queries, and host.
......
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