Unverified Commit 92b4d673 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

docs: Next.js 14 (#57342)

- Fetch logging configuration is no longer experimental
- Add `unstable_noStore` reference
- Add `unstable_cache` reference
- Add codemod docs for `next/og` import changes
- Update docs around stable Server Actions
- Add example of revalidating the entire data cache
- Update static export docs for `next export` command removal
- Update minimum required Node.js version
- Add `viewport` and `generateViewport` reference
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
Co-authored-by: 's avatarDelba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
parent fd0a96ff
...@@ -10,7 +10,7 @@ related: ...@@ -10,7 +10,7 @@ related:
System Requirements: System Requirements:
- [Node.js 16.14](https://nodejs.org/) or later. - [Node.js 18.17](https://nodejs.org/) or later.
- macOS, Windows (including WSL), and Linux are supported. - macOS, Windows (including WSL), and Linux are supported.
## Automatic Installation ## Automatic Installation
......
...@@ -17,7 +17,7 @@ There are four ways you can fetch data: ...@@ -17,7 +17,7 @@ There are four ways you can fetch data:
Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree. Next.js extends the native [`fetch` Web API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow you to configure the [caching](#caching-data) and [revalidating](#revalidating-data) behavior for each fetch request on the server. React extends `fetch` to automatically [memoize](/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed) fetch requests while rendering a React component tree.
You can use `fetch` with [`async`/`await` in Server Components](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md), in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). You can use `fetch` with `async`/`await` in Server Components, in [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and in [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations).
For example: For example:
...@@ -117,7 +117,7 @@ Learn more about [time-based revalidation](/docs/app/building-your-application/c ...@@ -117,7 +117,7 @@ Learn more about [time-based revalidation](/docs/app/building-your-application/c
#### On-demand Revalidation #### On-demand Revalidation
Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a Route Handler or a Server Action. Data can be revalidated on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)) inside a [Server Action](/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).
Next.js has a cache tagging system for invalidating `fetch` requests across routes. Next.js has a cache tagging system for invalidating `fetch` requests across routes.
...@@ -142,89 +142,25 @@ export default async function Page() { ...@@ -142,89 +142,25 @@ export default async function Page() {
} }
``` ```
If using a Route Handler, you should create a secret token only known by your Next.js app. This secret will be used to prevent unauthorized revalidation attempts. For example, you can access the route (either manually or with a webhook) with the following URL structure: You can then revalidate this `fetch` call tagged with `collection` by calling `revalidateTag` in a Server Action:
```bash filename="URL" ```ts filename="app/actions.ts" switcher
https://<your-site.com>/api/revalidate?tag=collection&secret=<token> 'use server'
```
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=<token>`
export async function POST(request: NextRequest) {
const secret = request.nextUrl.searchParams.get('secret')
const tag = request.nextUrl.searchParams.get('tag')
if (secret !== process.env.MY_SECRET_TOKEN) {
return Response.json({ message: 'Invalid secret' }, { status: 401 })
}
if (!tag) {
return Response.json({ message: 'Missing tag param' }, { status: 400 })
}
revalidateTag(tag)
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { revalidateTag } from 'next/cache' import { revalidateTag } from 'next/cache'
// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=<token>` export default async function action() {
export async function POST(request) { revalidateTag('collection')
const secret = request.nextUrl.searchParams.get('secret')
const tag = request.nextUrl.searchParams.get('tag')
if (secret !== process.env.MY_SECRET_TOKEN) {
return Response.json({ message: 'Invalid secret' }, { status: 401 })
}
if (!tag) {
return Response.json({ message: 'Missing tag param' }, { status: 400 })
}
revalidateTag(tag)
return Response.json({ revalidated: true, now: Date.now() })
} }
``` ```
Alternatively, you can use [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) to revalidate all data associated with a path. ```js filename="app/actions.js" switcher
'use server'
```ts filename="app/api/revalidate/route.ts" switcher import { revalidateTag } from 'next/cache'
import { NextRequest } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function POST(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (!path) {
return Response.json({ message: 'Missing path param' }, { status: 400 })
}
revalidatePath(path)
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { revalidatePath } from 'next/cache'
export async function POST(request) {
const path = request.nextUrl.searchParams.get('path')
if (!path) {
return Response.json({ message: 'Missing path param' }, { status: 400 })
}
revalidatePath(path)
return Response.json({ revalidated: true, now: Date.now() }) export default async function action() {
revalidateTag('collection')
} }
``` ```
...@@ -260,14 +196,7 @@ View all the available `cache` options in the [`fetch` API reference](/docs/app/ ...@@ -260,14 +196,7 @@ View all the available `cache` options in the [`fetch` API reference](/docs/app/
If you have multiple `fetch` requests in a route segment (e.g. a Layout or Page), you can configure the caching behavior of all data requests in the segment using the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config). If you have multiple `fetch` requests in a route segment (e.g. a Layout or Page), you can configure the caching behavior of all data requests in the segment using the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config).
For example, using `const dynamic = 'force-dynamic'` will cause all data to be fetched at request time, and the segment to be rendered dynamically. However, we recommend configuring the caching behavior of each `fetch` request individually. This gives you more granular control over the caching behavior.
```js filename="layout.js | page.js"
// Add
export const dynamic = 'force-dynamic'
```
There's an extensive list of Segment Config options, giving you fine-grained control of static and dynamic behavior of a route segment. See the [API reference](/docs/app/api-reference/file-conventions/route-segment-config) for more.
## Fetching data on the Server with third-party libraries ## Fetching data on the Server with third-party libraries
...@@ -275,9 +204,7 @@ In cases where you're using a third-party library that doesn't support or expose ...@@ -275,9 +204,7 @@ In cases where you're using a third-party library that doesn't support or expose
Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered. Whether the data is cached or not will depend on whether the route segment is [statically or dynamically rendered](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies). If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will _not_ be cached and will be re-fetched on every request when the segment is rendered.
> **Good to know:** You can also use the experimental [`unstable_cache` API](/docs/app/api-reference/functions/unstable_cache).
>
> Next.js is working on an API, `unstable_cache`, for configuring the caching and revalidating behavior of individual third-party requests.
### Example ### Example
...@@ -370,4 +297,4 @@ You can also fetch data on the client using a third-party library such as [SWR]( ...@@ -370,4 +297,4 @@ You can also fetch data on the client using a third-party library such as [SWR](
> **Future APIs**: > **Future APIs**:
> >
> `use` is a React function that **accepts and handles a promise** returned by a function. Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. Learn more about `use` in the [React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#usepromise). > `use` is a React function that **accepts and handles a promise** returned by a function. Wrapping `fetch` in `use` is currently **not** recommended in Client Components and may trigger multiple re-renders. Learn more about `use` in the [React docs](https://react.dev/reference/react/use).
...@@ -360,7 +360,7 @@ export default async function submit(formData) { ...@@ -360,7 +360,7 @@ export default async function submit(formData) {
<AppOnly> <AppOnly>
Use the `useFormStatus` hook to show a loading state when a form is submitting on the server. The `useFormStatus` hook can only be used as a child of a `form` element using a Server Action. Use the [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) hook to show a loading state when a form is submitting on the server. The `useFormStatus` hook can only be used as a child of a `form` element using a Server Action.
For example, the following submit button: For example, the following submit button:
...@@ -731,7 +731,7 @@ Use `useOptimistic` to optimistically update the UI before the Server Action fin ...@@ -731,7 +731,7 @@ Use `useOptimistic` to optimistically update the UI before the Server Action fin
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
'use client' 'use client'
import { experimental_useOptimistic as useOptimistic } from 'react' import { useOptimistic } from 'react'
import { send } from './actions' import { send } from './actions'
type Message = { type Message = {
...@@ -770,7 +770,7 @@ export function Thread({ messages }: { messages: Message[] }) { ...@@ -770,7 +770,7 @@ export function Thread({ messages }: { messages: Message[] }) {
```jsx filename="app/page.jsx" switcher ```jsx filename="app/page.jsx" switcher
'use client' 'use client'
import { experimental_useOptimistic as useOptimistic } from 'react' import { useOptimistic } from 'react'
import { send } from './actions' import { send } from './actions'
export function Thread({ messages }) { export function Thread({ messages }) {
......
...@@ -103,4 +103,4 @@ This means the Client Component JavaScript bundle is downloaded and parsed. Once ...@@ -103,4 +103,4 @@ This means the Client Component JavaScript bundle is downloaded and parsed. Once
Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server. Sometimes, after you've declared the `"use client"` boundary, you may want to go back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server.
You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and Server Actions. See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information. You can keep code on the server even though it's theoretically nested inside Client Components by interleaving Client and Server Components and [Server Actions](/docs/app/building-your-application/data-fetching/forms-and-mutations). See the [Composition Patterns](/docs/app/building-your-application/rendering/composition-patterns) page for more information.
...@@ -417,7 +417,7 @@ The following table provides an overview of how different Next.js APIs affect ca ...@@ -417,7 +417,7 @@ The following table provides an overview of how different Next.js APIs affect ca
| [`headers`, `useSearchParams`, `searchParams`](#dynamic-functions) | | Opt out | | | | [`headers`, `useSearchParams`, `searchParams`](#dynamic-functions) | | Opt out | | |
| [`generateStaticParams`](#generatestaticparams) | | Cache | | | | [`generateStaticParams`](#generatestaticparams) | | Cache | | |
| [`React.cache`](#react-cache-function) | | | | Cache | | [`React.cache`](#react-cache-function) | | | | Cache |
| [`unstable_cache`](#unstable_cache) (Coming Soon) | | | | | | [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) | | | | |
### `<Link>` ### `<Link>`
...@@ -480,7 +480,7 @@ See the [`fetch` API reference](/docs/app/api-reference/functions/fetch) for mor ...@@ -480,7 +480,7 @@ See the [`fetch` API reference](/docs/app/api-reference/functions/fetch) for mor
Next.js has a cache tagging system for fine-grained data caching and revalidation. Next.js has a cache tagging system for fine-grained data caching and revalidation.
1. When using `fetch` or `unstable_cache`, you have the option to tag cache entries with one or more tags. 1. When using `fetch` or [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache), you have the option to tag cache entries with one or more tags.
2. Then, you can call `revalidateTag` to purge the cache entries associated with that tag. 2. Then, you can call `revalidateTag` to purge the cache entries associated with that tag.
For example, you can set a tag when fetching data: For example, you can set a tag when fetching data:
...@@ -577,27 +577,3 @@ export const getItem = cache(async (id) => { ...@@ -577,27 +577,3 @@ export const getItem = cache(async (id) => {
return item return item
}) })
``` ```
### `unstable_cache`
`unstable_cache` is an experimental API for adding values to the Data Cache when the `fetch` API is not suitable. For example, when using database clients, CMS clients, or GraphQL.
```jsx
import { unstable_cache } from 'next/cache'
export default async function Page() {
const cachedData = await unstable_cache(
async () => {
const data = await db.query('...')
return data
},
['cache-key'],
{
tags: ['a', 'b', 'c'],
revalidate: 10,
}
)()
}
```
> **Warning**: This API is being developed, and we do not recommend using it in production. It's listed here to show the future direction of the Data Cache.
...@@ -6,6 +6,7 @@ related: ...@@ -6,6 +6,7 @@ related:
links: links:
- app/api-reference/functions/generate-metadata - app/api-reference/functions/generate-metadata
- app/api-reference/file-conventions/metadata - app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport
--- ---
Next.js has a Metadata API that can be used to define your application metadata (e.g. `meta` and `link` tags inside your HTML `head` element) for improved SEO and web shareability. Next.js has a Metadata API that can be used to define your application metadata (e.g. `meta` and `link` tags inside your HTML `head` element) for improved SEO and web shareability.
......
...@@ -24,7 +24,7 @@ Metadata helps search engines understand your content better (which can result i ...@@ -24,7 +24,7 @@ Metadata helps search engines understand your content better (which can result i
The Metadata API in Next.js allows you to modify the `<head>` element of a page. You can configure metadata in two ways: The Metadata API in Next.js allows you to modify the `<head>` element of a page. You can configure metadata in two ways:
- **Config-based Metadata**: Export a static metadata object or a dynamic generateMetadata function in a `layout.js` or `page.js` file. - **Config-based Metadata**: Export a [static `metadata` object](/docs/app/api-reference/functions/generate-metadata#metadata-object) or a dynamic [`generateMetadata` function](/docs/app/api-reference/functions/generate-metadata#generatemetadata-function) in a `layout.js` or `page.js` file.
- **File-based Metadata**: Add static or dynamically generated special files to route segments. - **File-based Metadata**: Add static or dynamically generated special files to route segments.
Additionally, you can create dynamic Open Graph Images using JSX and CSS with [imageResponse](/docs/app/api-reference/functions/image-response) constructor. Additionally, you can create dynamic Open Graph Images using JSX and CSS with [imageResponse](/docs/app/api-reference/functions/image-response) constructor.
......
...@@ -323,7 +323,7 @@ export const dynamic = 'error' ...@@ -323,7 +323,7 @@ export const dynamic = 'error'
With a static export, Next.js can be deployed and hosted on any web server that can serve HTML/CSS/JS static assets. With a static export, Next.js can be deployed and hosted on any web server that can serve HTML/CSS/JS static assets.
When running `next build`, Next.js generates the static export into the `out` folder. Using `next export` is no longer needed. For example, let's say you have the following routes: When running `next build`, Next.js generates the static export into the `out` folder. For example, let's say you have the following routes:
- `/` - `/`
- `/blog/[id]` - `/blog/[id]`
...@@ -365,5 +365,6 @@ server { ...@@ -365,5 +365,6 @@ server {
| Version | Changes | | Version | Changes |
| --------- | -------------------------------------------------------------------------------------------------------------------- | | --------- | -------------------------------------------------------------------------------------------------------------------- |
| `v14.0.0` | `next export` has been removed in favor of `"output": "export"` |
| `v13.4.0` | App Router (Stable) adds enhanced static export support, including using React Server Components and Route Handlers. | | `v13.4.0` | App Router (Stable) adds enhanced static export support, including using React Server Components and Route Handlers. |
| `v13.3.0` | `next export` is deprecated and replaced with `"output": "export"` | | `v13.3.0` | `next export` is deprecated and replaced with `"output": "export"` |
...@@ -34,7 +34,7 @@ Replacing `<transform>` and `<path>` with appropriate values. ...@@ -34,7 +34,7 @@ Replacing `<transform>` and `<path>` with appropriate values.
npx @next/codemod@latest next-og-import. npx @next/codemod@latest next-og-import.
``` ```
This codemo migrates the import path of `ImageResponse` from `'next/server'` to `'next/og'` This codemod moves transforms imports from `next/server` to `next/og` for usage of [Dynamic OG Image Generation](/docs/app/building-your-application/optimizing/metadata#dynamic-image-generation).
For example: For example:
...@@ -42,7 +42,7 @@ For example: ...@@ -42,7 +42,7 @@ For example:
import { ImageResponse } from 'next/server' import { ImageResponse } from 'next/server'
``` ```
Transform into: Transforms into:
```js ```js
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
......
...@@ -14,7 +14,7 @@ This guide will help you: ...@@ -14,7 +14,7 @@ This guide will help you:
### Node.js Version ### Node.js Version
The minimum Node.js version is now **v16.14**. See the [Node.js documentation](https://nodejs.org/docs/latest-v16.x/api/) for more information. The minimum Node.js version is now **v18.17**. See the [Node.js documentation](https://nodejs.org/docs/latest-v18.x/api/) for more information.
### Next.js Version ### Next.js Version
......
...@@ -124,7 +124,7 @@ export default function Icon() { ...@@ -124,7 +124,7 @@ export default function Icon() {
``` ```
```jsx filename="app/icon.js" switcher ```jsx filename="app/icon.js" switcher
import { ImageResponse } from 'next/server' import { ImageResponse } from 'next/og'
// Route segment config // Route segment config
export const runtime = 'edge' export const runtime = 'edge'
......
...@@ -147,7 +147,7 @@ export default async function Image() { ...@@ -147,7 +147,7 @@ export default async function Image() {
``` ```
```jsx filename="app/about/opengraph-image.js" switcher ```jsx filename="app/about/opengraph-image.js" switcher
import { ImageResponse } from 'next/server' import { ImageResponse } from 'next/og'
// Route segment config // Route segment config
export const runtime = 'edge' export const runtime = 'edge'
......
...@@ -7,6 +7,7 @@ related: ...@@ -7,6 +7,7 @@ related:
description: View all the Metadata API options. description: View all the Metadata API options.
links: links:
- app/api-reference/file-conventions/metadata - app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport
- app/building-your-application/optimizing/metadata - app/building-your-application/optimizing/metadata
--- ---
...@@ -361,7 +362,6 @@ export const metadata = { ...@@ -361,7 +362,6 @@ export const metadata = {
referrer: 'origin-when-cross-origin', referrer: 'origin-when-cross-origin',
keywords: ['Next.js', 'React', 'JavaScript'], keywords: ['Next.js', 'React', 'JavaScript'],
authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }], authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }],
colorScheme: 'dark',
creator: 'Jiachi Liu', creator: 'Jiachi Liu',
publisher: 'Sebastian Markbåge', publisher: 'Sebastian Markbåge',
formatDetection: { formatDetection: {
...@@ -635,35 +635,7 @@ export const metadata = { ...@@ -635,35 +635,7 @@ export const metadata = {
### `themeColor` ### `themeColor`
Learn more about [theme-color](https://developer.mozilla.org/docs/Web/HTML/Element/meta/name/theme-color). > **Deprecated**: The `themeColor` option in `metadata` is deprecated as of Next.js 14. Please use the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport) instead.
**Simple theme color**
```jsx filename="layout.js | page.js"
export const metadata = {
themeColor: 'black',
}
```
```html filename="<head> output" hideLineNumbers
<meta name="theme-color" content="black" />
```
**With media attribute**
```jsx filename="layout.js | page.js"
export const metadata = {
themeColor: [
{ media: '(prefers-color-scheme: light)', color: 'cyan' },
{ media: '(prefers-color-scheme: dark)', color: 'black' },
],
}
```
```html filename="<head> output" hideLineNumbers
<meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" />
```
### `manifest` ### `manifest`
...@@ -757,24 +729,7 @@ export const metadata = { ...@@ -757,24 +729,7 @@ export const metadata = {
### `viewport` ### `viewport`
> **Good to know**: The `viewport` meta tag is automatically set with the following default values. Usually, manual configuration is unnecessary as the default is sufficient. However, the information is provided for completeness. > **Deprecated**: The `themeColor` option in `metadata` is deprecated as of Next.js 14. Please use the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport) instead.
```jsx filename="layout.js | page.js"
export const metadata = {
viewport: {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
},
}
```
```html filename="<head> output" hideLineNumbers
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
```
### `verification` ### `verification`
...@@ -1154,6 +1109,7 @@ export const metadata = { ...@@ -1154,6 +1109,7 @@ export const metadata = {
## Version History ## Version History
| Version | Changes | | Version | Changes |
| --------- | --------------------------------------------- | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v13.2.0` | `metadata` and `generateMetadata` introduced. | | `v13.2.0` | `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). |
| `v13.2.0` | `metadata` and `generateMetadata` introduced. |
...@@ -299,7 +299,7 @@ export default function Page({ params }) { ...@@ -299,7 +299,7 @@ export default function Page({ params }) {
} }
``` ```
> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable. > **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#request-memoization) if `fetch` is unavailable.
## Version History ## Version History
......
---
title: generateViewport
description: API Reference for the generateViewport function.
related:
title: Next Steps
description: View all the Metadata API options.
links:
- app/api-reference/file-conventions/metadata
- app/building-your-application/optimizing/metadata
---
You can customize the initial viewport of the page with the static `viewport` object or the dynamic `generateViewport` function.
> **Good to know**:
>
> - The `viewport` object and `generateViewport` function exports are **only supported in Server Components**.
> - You cannot export both the `viewport` object and `generateViewport` function from the same route segment.
## The `viewport` object
To define the viewport options, export a `viewport` object from a `layout.js` or `page.js` file.
```tsx filename="layout.tsx | page.tsx" switcher
import { Viewport } from 'next'
export const viewport: Viewport = {
themeColor: 'black',
}
export default function Page() {}
```
```jsx filename="layout.js | page.js" switcher
export const viewport = {
themeColor: 'black',
}
export default function Page() {}
```
## `generateViewport` function
`generateViewport` should return a [`Viewport` object](#viewport-fields) containing one or more viewport fields.
```tsx filename="layout.tsx | page.tsx" switcher
export function generateViewport({ params }) {
return {
themeColor: '...',
}
}
```
```jsx filename="layout.js | page.js" switcher
export function generateViewport({ params }) {
return {
themeColor: '...',
}
}
```
> **Good to know**:
>
> - If the viewport doesn't depend on runtime information, it should be defined using the static [`viewport` object](#the-viewport-object) rather than `generateMetadata`.
> - Marking `generateViewport` as `async` is not yet supported. If you still require this functionality, continue using the previous `generateMetadata` option. We will be adding support for `async` in an upcoming minor release.
## Viewport Fields
### `themeColor`
Learn more about [theme-color](https://developer.mozilla.org/docs/Web/HTML/Element/meta/name/theme-color).
**Simple theme color**
```jsx filename="layout.js | page.js"
export const viewport = {
themeColor: 'black',
}
```
```html filename="<head> output" hideLineNumbers
<meta name="theme-color" content="black" />
```
**With media attribute**
```jsx filename="layout.js | page.js"
export const viewport = {
themeColor: [
{ media: '(prefers-color-scheme: light)', color: 'cyan' },
{ media: '(prefers-color-scheme: dark)', color: 'black' },
],
}
```
```html filename="<head> output" hideLineNumbers
<meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" />
```
### `width`, `initialScale`, and `maximumScale`
> **Good to know**: The `viewport` meta tag is automatically set with the following default values. Usually, manual configuration is unnecessary as the default is sufficient. However, the information is provided for completeness.
```jsx filename="layout.js | page.js"
export const viewport = {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
// Also supported by less commonly used
// interactiveWidget: 'resizes-visual',
}
```
```html filename="<head> output" hideLineNumbers
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
```
### `colorScheme`
Learn more about [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#:~:text=color%2Dscheme%3A%20specifies,of%20the%20following%3A).
```jsx filename="layout.js | page.js"
export const viewport = {
colorScheme: 'dark',
}
```
```html filename="<head> output" hideLineNumbers
<meta name="color-scheme" content="dark" />
```
## Types
You can add type safety to your viewport object by using the `Viewport` type. If you are using the [built-in TypeScript plugin](/docs/app/building-your-application/configuring/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
### `viewport` object
```tsx
import type { Viewport } from 'next'
export const viewport: Viewport = {
themeColor: 'black',
}
```
### `generateViewport` function
#### Regular function
```tsx
import type { Viewport } from 'next'
export function generateViewport(): Viewport {
return {
themeColor: 'black',
}
}
```
#### With segment props
```tsx
import type { Viewport } from 'next'
type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export function generateViewport({ params, searchParams }: Props): Viewport {
return {
themeColor: 'black',
}
}
export default function Page({ params, searchParams }: Props) {}
```
#### JavaScript Projects
For JavaScript projects, you can use JSDoc to add type safety.
```js
/** @type {import("next").Viewport} */
export const viewport = {
themeColor: 'black',
}
```
## Version History
| Version | Changes |
| --------- | --------------------------------------------- |
| `v14.0.0` | `viewport` and `generateViewport` introduced. |
...@@ -56,6 +56,16 @@ revalidatePath('/(main)/post/[slug]', 'layout') ...@@ -56,6 +56,16 @@ revalidatePath('/(main)/post/[slug]', 'layout')
This will revalidate any URL that matches the provided `layout` file on the next page visit. This will cause pages beneath with the same layout to revalidate on the next visit. For example, in the above case, `/blog/[slug]/[another]` would also revalidate on the next visit. This will revalidate any URL that matches the provided `layout` file on the next page visit. This will cause pages beneath with the same layout to revalidate on the next visit. For example, in the above case, `/blog/[slug]/[another]` would also revalidate on the next visit.
### Revalidating All Data
```ts
import { revalidatePath } from 'next/cache'
revalidatePath('/', 'layout')
```
This will purge the Client-side Router Cache, and revalidate the Data Cache on the next page visit.
### Server Action ### Server Action
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
......
...@@ -159,8 +159,8 @@ module.exports = { ...@@ -159,8 +159,8 @@ module.exports = {
The following React API pages are currently being documented: The following React API pages are currently being documented:
- [`"use server"`](https://react.dev/reference/react/use-server) - [`"use server"`](https://react.dev/reference/react/use-server)
- [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus)
- `action` (🚧) - `action` (🚧)
- `formAction` (🚧) - `formAction` (🚧)
- `useFormStatus` (🚧)
- `useFormState` (🚧) - `useFormState` (🚧)
- `useOptimistic` (🚧) - `useOptimistic` (🚧)
---
title: unstable_cache
description: API Reference for the unstable_cache function.
---
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
```jsx
import { getUser } from './data';
import { unstable_cache } from 'next/cache';
const getCachedUser = unstable_cache(
async (id) => getUser(id),
['my-app-user']
);
export default async function Component({ userID }) {
const user = await getCachedUser(userID);
...
}
```
> **Warning**: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes.
## Parameters
```jsx
const data = unstable_cache(fetchData, keyParts, options)()
```
- `fetchData`: This is an asynchronous function that fetches the data you want to cache. It must be a function that returns a `Promise`.
- `keyParts`: This is an array that identifies the cached key. It must contain globally unique values that together identify the key of the data being cached. The cache key also includes the arguments passed to the function.
- `options`: This is an object that controls how the cache behaves. It can contain the following properties:
- `tags`: An array of tags that can be used to control cache invalidation.
- `revalidate`: The number of seconds after which the cache should be revalidated.
## Returns
`unstable_cache` returns a function that when invoked, returns a Promise that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned.
---
title: unstable_noStore
description: API Reference for the unstable_noStore function.
---
`unstable_noStore` can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.
```jsx
import { unstable_noStore as noStore } from 'next/cache';
export default async function Component() {
noStore();
const result = await db.query(...);
...
}
```
> **Good to know**:
>
> - `unstable_noStore` is equivalent to `cache: 'no-store'` on a `fetch`
> - `unstable_noStore` is preferred over `export const dynamic = 'force-dynamic'` as it is more granular and can be used on a per-component basis
- Using `unstable_noStore` inside [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) will not opt out of static generation. Instead, it will defer to the cache configuration to determine whether to cache the result or not.
## Usage
If you prefer not to pass additional options to `fetch`, like `cache: 'no-store'` or `next: { revalidate: 0 }`, you can use `noStore()` as a replacement for all of these use cases.
```jsx
import { unstable_noStore as noStore } from 'next/cache';
export default async function Component() {
noStore();
const result = await db.query(...);
...
}
```
## Version History
| Version | Changes |
| --------- | ------------------------------ |
| `v14.0.0` | `unstable_noStore` introduced. |
---
title: logging
description: Configure how data fetches are logged to the console when running Next.js in development mode.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
You can configure the logging level and whether the full URL is logged to the console when running Next.js in development mode.
Currently, `logging` only applies to data fetching using the `fetch` API. It does not yet apply to other logs inside of Next.js.
```js filename="next.config.js"
module.exports = {
logging: {
fetches: {
fullUrl: true,
},
},
}
```
---
title: Version 14
description: Upgrade your Next.js Application from Version 13 to 14.
---
## Upgrading from 13 to 14
To update to Next.js version 13, run the following command using your preferred package manager:
```bash filename="Terminal"
npm i next@latest react@latest react-dom@latest eslint-config-next@latest
```
```bash filename="Terminal"
yarn add next@latest react@latest react-dom@latest eslint-config-next@latest
```
```bash filename="Terminal"
pnpm up next react react-dom eslint-config-next --latest
```
```bash filename="Terminal"
bun add next@latest react@latest react-dom@latest eslint-config-next@latest
```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions.
### v14 Summary
- The minimum Node.js version has been bumped from 16.14 to 18.17, since 16.x has reached end-of-life.
- The `next export` command is deprecated in favor of `output: 'export'`. Please see the [docs](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) for more information.
- The `next/server` import for `ImageResponse` was renamed to `next/og`. A [codemod is available](/docs/app/building-your-application/upgrading/codemods#next-og-import) to safely and automatically rename your imports.
- The `@next/font` package has been fully removed in favor of the built-in `next/font`. A [codemod is available](/docs/app/building-your-application/upgrading/codemods#built-in-next-font) to safely and automatically rename your imports.
- The WASM target for `next-swc` has been removed.
...@@ -9,14 +9,22 @@ To update to Next.js version 13, run the following command using your preferred ...@@ -9,14 +9,22 @@ To update to Next.js version 13, run the following command using your preferred
```bash filename="Terminal" ```bash filename="Terminal"
npm i next@latest react@latest react-dom@latest eslint-config-next@latest npm i next@latest react@latest react-dom@latest eslint-config-next@latest
# or ```
```bash filename="Terminal"
yarn add next@latest react@latest react-dom@latest eslint-config-next@latest yarn add next@latest react@latest react-dom@latest eslint-config-next@latest
# or ```
```bash filename="Terminal"
pnpm up next react react-dom eslint-config-next --latest pnpm up next react react-dom eslint-config-next --latest
# or ```
```bash filename="Terminal"
bun add next@latest react@latest react-dom@latest eslint-config-next@latest bun add next@latest react@latest react-dom@latest eslint-config-next@latest
``` ```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions.
### v13 Summary ### v13 Summary
- The [Supported Browsers](/docs/architecture/supported-browsers) have been changed to drop Internet Explorer and target modern browsers. - The [Supported Browsers](/docs/architecture/supported-browsers) have been changed to drop Internet Explorer and target modern browsers.
......
...@@ -6,15 +6,23 @@ description: Upgrade your Next.js Application from Version 11 to Version 12. ...@@ -6,15 +6,23 @@ description: Upgrade your Next.js Application from Version 11 to Version 12.
To upgrade to version 12, run the following command: To upgrade to version 12, run the following command:
```bash filename="Terminal" ```bash filename="Terminal"
npm install next@12 npm i next@12 react@17 react-dom@17 eslint-config-next@12
```
yarn add next@12 ```bash filename="Terminal"
yarn add next@12 react@17 react-dom@17 eslint-config-next@12
```
pnpm update next@12 ```bash filename="Terminal"
pnpm up next@12 react@17 react-dom@17 eslint-config-next@12
```
bun add next@12 ```bash filename="Terminal"
bun add next@12 react@17 react-dom@17 eslint-config-next@12
``` ```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their corresponding versions.
### Upgrading to 12.2 ### Upgrading to 12.2
[Middleware](/docs/messages/middleware-upgrade-guide) - If you were using Middleware prior to `12.2`, please see the [upgrade guide](/docs/messages/middleware-upgrade-guide) for more information. [Middleware](/docs/messages/middleware-upgrade-guide) - If you were using Middleware prior to `12.2`, please see the [upgrade guide](/docs/messages/middleware-upgrade-guide) for more information.
......
...@@ -6,11 +6,23 @@ description: Upgrade your Next.js Application from Version 10 to Version 11. ...@@ -6,11 +6,23 @@ description: Upgrade your Next.js Application from Version 10 to Version 11.
To upgrade to version 11, run the following command: To upgrade to version 11, run the following command:
```bash filename="Terminal" ```bash filename="Terminal"
npm install next@11 npm i next@11 react@17 react-dom@17
```
yarn add next@11 ```bash filename="Terminal"
yarn add next@11 react@17 react-dom@17
```
```bash filename="Terminal"
pnpm up next@11 react@17 react-dom@17
``` ```
```bash filename="Terminal"
bun add next@11 react@17 react-dom@17
```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their corresponding versions.
### Webpack 5 ### Webpack 5
Webpack 5 is now the default for all Next.js applications. If you did not have a custom webpack configuration, your application is already using webpack 5. If you do have a custom webpack configuration, you can refer to the [Next.js webpack 5 documentation](/docs/messages/webpack5) for upgrade guidance. Webpack 5 is now the default for all Next.js applications. If you did not have a custom webpack configuration, your application is already using webpack 5. If you do have a custom webpack configuration, you can refer to the [Next.js webpack 5 documentation](/docs/messages/webpack5) for upgrade guidance.
......
...@@ -8,7 +8,19 @@ There were no breaking changes between versions 9 and 10. ...@@ -8,7 +8,19 @@ There were no breaking changes between versions 9 and 10.
To upgrade to version 10, run the following command: To upgrade to version 10, run the following command:
```bash filename="Terminal" ```bash filename="Terminal"
npm install next@10 npm i next@10
```
```bash filename="Terminal"
yarn add next@10 yarn add next@10
``` ```
```bash filename="Terminal"
pnpm up next@10
```
```bash filename="Terminal"
bun add next@10
```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their corresponding versions.
...@@ -7,11 +7,23 @@ description: Upgrade your Next.js Application from Version 8 to Version 9. ...@@ -7,11 +7,23 @@ description: Upgrade your Next.js Application from Version 8 to Version 9.
To upgrade to version 9, run the following command: To upgrade to version 9, run the following command:
```bash filename="Terminal" ```bash filename="Terminal"
npm install next@9 npm i next@9
```
```bash filename="Terminal"
yarn add next@9 yarn add next@9
``` ```
```bash filename="Terminal"
pnpm up next@9
```
```bash filename="Terminal"
bun add next@9
```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their corresponding versions.
## Production Deployment on Vercel ## Production Deployment on Vercel
If you previously configured `routes` in your `vercel.json` file for dynamic routes, these rules can be removed when leveraging Next.js 9's new [Dynamic Routing feature](/docs/pages/building-your-application/routing/dynamic-routes). If you previously configured `routes` in your `vercel.json` file for dynamic routes, these rules can be removed when leveraging Next.js 9's new [Dynamic Routing feature](/docs/pages/building-your-application/routing/dynamic-routes).
......
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