id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 46 101 |
|---|---|---|
4a5a91177da5-0 | draftModeThe draftMode function allows you to detect Draft Mode inside a Server Component.
app/page.js import { draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
return (
<main>
<h1>My Blog Post</h1>
<p>Draft Mode is currently {isEnabled ? 'Enabled'... | https://nextjs.org/docs/app/api-reference/functions/draft-mode |
3debed7a35b1-0 | fetchNext.js extends the native Web fetch() API to allow each request on the server to set its own persistent caching semantics.
In the browser, the cache option indicates how a fetch request will interact with the browser's HTTP cache. With this extension, cache indicates how a server-side fetch request will interact ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
3debed7a35b1-1 | // This request should be cached with a lifetime of 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, {
next: { revalidate: 10 },
})
return <div>...</div>
}
fetch(url, options)
Since Next.js extends the Web fetch() API, you can use ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
3debed7a35b1-2 | force-cache (default) - Next.js looks for a matching request in its HTTP cache.
If there is a match and it is fresh, it will be returned from the cache.
If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.
no-store - Next.js fet... | https://nextjs.org/docs/app/api-reference/functions/fetch |
3debed7a35b1-3 | Set the cache lifetime of a resource (in seconds).
false - Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time.
0 - Prevent the resource from being cached.
number - (in seconds) Specify the resource should have a cache lifetime of at most ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
3debed7a35b1-4 | Conflicting options such as { revalidate: 0, cache: 'force-cache' } or { revalidate: 10, cache: 'no-store' } will cause an error.
Version History
VersionChangesv13.0.0fetch introduced. | https://nextjs.org/docs/app/api-reference/functions/fetch |
b35f8327fbd0-0 | generateImageMetadataYou can use generateImageMetadata to generate different versions of one image or return multiple images for one route segment. This is useful for when you want to avoid hard-coding metadata values, such as for icons.
Parameters
generateImageMetadata function accepts the following parameters:
params... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
b35f8327fbd0-1 | Returns
The generateImageMetadata function should return an array of objects containing the image's metadata such as alt and size. In addition, each item must include an id value will be passed to the props of the image generating function.
Image Metadata ObjectTypeidstring (required)altstringsize{ width: number; heigh... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
b35f8327fbd0-2 | return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 88,
background: '#000',
color: '#fafafa',
}}
>
Icon ... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
b35f8327fbd0-3 | params,
}: {
params: { id: string }
}) {
const images = await getOGImages(params.id)
return images.map((image, idx) => ({
id: idx,
size: { width: 1200, height: 600 },
alt: image.text,
contentType: 'image/png',
}))
}
export default async function Image({
params,
id,
}: {
params: { id: s... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
b35f8327fbd0-4 | }
}
>
{text}
</div>
)
)
}
Version History
VersionChangesv13.3.0generateImageMetadata introduced. | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
1d048b70a39d-0 | Metadata Object and generateMetadata OptionsThis page covers all Config-based Metadata options with generateMetadata and the static metadata object.
layout.tsx / page.tsx import { Metadata } from 'next'
// either Static metadata
export const metadata: Metadata = {
title: '...',
}
// or Dynamic metadata
export asy... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-1 | title: '...',
description: '...',
}
export default function Page() {}
See the Metadata Fields for a complete list of supported options.
generateMetadata function
Dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments, can be set by export... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-2 | // read route params
const id = params.id
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-3 | RouteURLparamsapp/shop/[slug]/page.js/shop/1{ slug: '1' }app/shop/[tag]/[item]/page.js/shop/1/2{ tag: '1', item: '2' }app/shop/[...slug]/page.js/shop/1/2{ slug: ['1', '2'] }
searchParams - An object containing the current URL's search params. Examples:
URLsearchParams/shop?a=1{ a: '1' }/shop?a=1&b=2{ a: '1', b: '2' }/s... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-4 | generateMetadata should return a Metadata object containing one or more metadata fields.
Good to know:
If metadata doesn't depend on runtime information, it should be defined using the static metadata object rather than generateMetadata.
When rendering a route, Next.js will automatically deduplicate fetch requests for ... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-5 | }
<head> output <title>Next.js</title>
Template object
app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '...',
default: '...',
absolute: '...',
},
}
Default
title.default can be used to provide a fallback title to child route segments that don't def... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-6 | app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // a default is required when creating a template
},
}
app/about/page.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'About',
}
// Outpu... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-7 | title.template has no effect if a route has not defined a title or title.default.
Absolute
title.absolute can be used to provide a title that ignores title.template set in parent segments.
app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
},
}
a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-8 | title.absolute defines the default title for child segments. It ignores title.template from parent segments.
title.template defines a new title template for child segments.
page.js
If a page does not define its own title the closest parents resolved title will be used.
title (string) defines the routes title. It will a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-9 | generator: 'Next.js',
applicationName: 'Next.js',
referrer: 'origin-when-cross-origin',
keywords: ['Next.js', 'React', 'JavaScript'],
authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }],
colorScheme: 'dark',
creator: 'Jiachi Liu',
publisher: 'Sebastian Markbåge',
formatDetection: {
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-10 | <meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" />
<meta name="... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-11 | If not configured, metadataBase is automatically populated with a default value.
layout.js / page.js export const metadata = {
metadataBase: new URL('https://acme.com'),
alternates: {
canonical: '/',
languages: {
'en-US': '/en-US',
'de-DE': '/de-DE',
},
},
openGraph: {
images: '/og-i... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-12 | Good to know:
metadataBase is typically set in root app/layout.js to apply to URL-based metadata fields across all routes.
All URL-based metadata fields that require absolute URLs can be configured with a metadataBase option.
metadataBase can contain a subdomain e.g. https://app.acme.com or base path e.g. https://acme.... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-13 | Default value
If not configured, metadataBase has a default value
When VERCEL_URL is detected: https://${process.env.VERCEL_URL} otherwise it falls back to http://localhost:${process.env.PORT || 3000}.
When overriding the default, we recommend using environment variables to compute the URL. This allows configuring a UR... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-14 | metadataBase: new URL('https://acme.com'),
}
Any metadata fields that inherit the above metadataBase and set their own value will be resolved as follows:
metadata fieldResolved URL/https://acme.com./https://acme.compaymentshttps://acme.com/payments/paymentshttps://acme.com/payments./paymentshttps://acme.com/payments../... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-15 | width: 800,
height: 600,
},
{
url: 'https://nextjs.org/og-alt.png',
width: 1800,
height: 1600,
alt: 'My custom alt',
},
],
locale: 'en_US',
type: 'website',
},
}
<head> output <meta property="og:title" content="Next.js" />
<meta property="og:descri... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-16 | <meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<meta property="og:image:url" content="https://nextjs.org/og-alt.png" />
<meta property="og:image:width" content="1800" />
<meta property="og:image:height" content="1600" />
<meta property="og:image:alt" content="My custo... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-17 | authors: ['Seb', 'Josh'],
},
}
<head> output <meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2023-01-01T00:00:00.000Z" />
<meta property="article:a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-18 | export const metadata: Metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
}
<head> output <meta name="ro... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-19 | />
icons
Good to know: We recommend using the file-based Metadata API for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
layout.js / page.js export const metadata = {
icons: {
icon: '/icon.png',
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-20 | href="/apple-touch-icon-precomposed.png"
/>
layout.js / page.js export const metadata = {
icons: {
icon: [{ url: '/icon.png' }, new URL('/icon.png', 'https://example.com')],
shortcut: ['/shortcut-icon.png'],
apple: [
{ url: '/apple-icon.png' },
{ url: '/apple-icon-x3.png', sizes: '180x180', ty... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-21 | <link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
<link rel="icon" href="https://example.com/icon.png" />
<link
rel="apple-touch-icon"
href="/apple-icon-x3.png"
sizes="180x180"
type="image/png"
/>
Good to know: The msa... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-22 | layout.js / page.js export const metadata = {
themeColor: [
{ media: '(prefers-color-scheme: light)', color: 'cyan' },
{ media: '(prefers-color-scheme: dark)', color: 'black' },
],
}
<head> output <meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-23 | layout.js / page.js export const metadata = {
twitter: {
card: 'summary_large_image',
title: 'Next.js',
description: 'The React Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: ['https://nextjs.org/og.png'],
},
}
<head> ... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-24 | <meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:image" content="https://nextjs.org/og.png" />
layout.js / page.js export const metadata = {
twitter: {
card: 'app',
title: 'Next.js',
description: 'The React Fr... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-25 | ipad: 'twitter_app://ipad',
googleplay: 'twitter_app://googleplay',
},
url: {
iphone: 'https://iphone_url',
ipad: 'https://ipad_url',
},
},
},
}
<head> output <meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-26 | <meta name="twitter:image:alt" content="Next.js Logo" />
<meta name="twitter:app:name:iphone" content="twitter_app" />
<meta name="twitter:app:id:iphone" content="twitter_app://iphone" />
<meta name="twitter:app:id:ipad" content="twitter_app://ipad" />
<meta name="twitter:app:id:googleplay" content="twitter_app://googl... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-27 | <meta name="twitter:app:name:googleplay" content="twitter_app" />
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.
layout.js / page.js exp... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-28 | me: ['my-email', 'my-link'],
},
},
}
<head> output <meta name="google-site-verification" content="google" />
<meta name="y_key" content="yahoo" />
<meta name="yandex-verification" content="yandex" />
<meta name="me" content="my-email" />
<meta name="me" content="my-link" />
appleWebApp
layout.js / page.js export ... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-29 | {
url: '/assets/startup/apple-touch-startup-image-1536x2008.png',
media: '(device-width: 768px) and (device-height: 1024px)',
},
],
},
}
<head> output <meta
name="apple-itunes-app"
content="app-id=myAppStoreID, app-argument=myAppArgument"
/>
<meta name="apple-mobile-web-app-capable" cont... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-30 | href="/assets/startup/apple-touch-startup-image-1536x2008.png"
media="(device-width: 768px) and (device-height: 1024px)"
rel="apple-touch-startup-image"
/>
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
alternates
layout.js / page.js export const metadata = {
alternates: {
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-31 | types: {
'application/rss+xml': 'https://nextjs.org/rss',
},
},
}
<head> output <link rel="canonical" href="https://nextjs.org" />
<link rel="alternate" hreflang="en-US" href="https://nextjs.org/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://nextjs.org/de-DE" />
<link
rel="alternate"
med... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-32 | ios: {
url: 'https://nextjs.org/ios',
app_store_id: 'app_store_id',
},
android: {
package: 'com.example.android/package',
app_name: 'app_name_android',
},
web: {
url: 'https://nextjs.org/web',
should_fallback: true,
},
},
}
<head> output <meta property="al:ios:u... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-33 | <meta property="al:web:url" content="https://nextjs.org/web" />
<meta property="al:web:should_fallback" content="true" />
archives
Describes a collection of records, documents, or other materials of historical interest (source).
layout.js / page.js export const metadata = {
archives: ['https://nextjs.org/13'],
}
<hea... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-34 | bookmarks: ['https://nextjs.org/13'],
}
<head> output <link rel="bookmarks" href="https://nextjs.org/13" />
category
layout.js / page.js export const metadata = {
category: 'technology',
}
<head> output <meta name="category" content="technology" />
other
All metadata options should be covered using the built-in suppo... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-35 | MetadataRecommendation<meta http-equiv="...">Use appropriate HTTP Headers via redirect(), Middleware, Security Headers<base>Render the tag in the layout or page itself.<noscript>Render the tag in the layout or page itself.<style>Learn more about styling in Next.js.<script>Learn more about using scripts.<link rel="style... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-36 | app/preload-resources.tsx 'use client'
import ReactDOM from 'react-dom'
export function PreloadResources() {
ReactDOM.preload('...', { as: '...' })
ReactDOM.preconnect('...', { crossOrigin: '...' })
ReactDOM.prefetchDNS('...')
return null
}
<link rel="preload">
Start loading a resource early in the page r... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-37 | <link rel="dns-prefetch">
Attempt to resolve a domain name before resources get requested. MDN Docs.
ReactDOM.prefetchDNS(href: string)
<head> output <link rel="dns-prefetch" href="..." />
Good to know:
These methods are currently only supported in Client Components, which are still Server Side Rendered on initial pag... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-38 | metadata object
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Next.js',
}
generateMetadata function
Regular function
import type { Metadata } from 'next'
export function generateMetadata(): Metadata {
return {
title: 'Next.js',
}
}
Async function
import type { Metadat... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
1d048b70a39d-39 | return {
title: 'Next.js',
}
}
export default function Page({ params, searchParams }: Props) {}
With parent metadata
import type { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
return {... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
6ea27c9f4feb-0 | generateStaticParamsThe generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.
app/blog/[slug]/page.js // Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticP... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-1 | During next dev, generateStaticParams will be called when you navigate to a route.
During next build, generateStaticParams runs before the corresponding Layouts or Pages are generated.
During revalidation (ISR), generateStaticParams will not be called again.
generateStaticParams replaces the getStaticPaths function in ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-2 | Each property in the object is a dynamic segment to be filled in for the route.
The properties name is the segment's name, and the properties value is what that segment should be filled in with.
Example RoutegenerateStaticParams Return Type/product/[id]{ id: string }[]/products/[category]/[product]{ category: string, p... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-3 | // - /product/2
// - /product/3
export default function Page({ params }: { params: { id: string } }) {
const { id } = params
// ...
}
Multiple Dynamic Segments
app/products/[category]/[product]/page.tsx export function generateStaticParams() {
return [
{ category: 'a', product: '1' },
{ category: 'b', pro... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-4 | params,
}: {
params: { category: string; product: string }
}) {
const { category, product } = params
// ...
}
Catch-all Dynamic Segment
app/product/[...slug]/page.tsx export function generateStaticParams() {
return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }]
}
// Three versions of this ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-5 | // ...
}
Examples
Multiple Dynamic Segments in a Route
You can generate params for dynamic segments above the current layout or page, but not below. For example, given the app/products/[category]/[product] route:
app/products/[category]/[product]/page.js can generate params for both [category] and [product].
app/produc... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-6 | return products.map((product) => ({
category: product.category.slug,
product: product.id,
}))
}
export default function Page({
params,
}: {
params: { category: string; product: string }
}) {
// ...
}
Generate params from the top down
Generate the parent segments first and use the result to generate th... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-7 | // ...
}
A child route segment's generateStaticParams function is executed once for each segment a parent generateStaticParams generates.
The child generateStaticParams function can use the params returned from the parent generateStaticParams function to dynamically generate its own segments.
app/products/[category]/[p... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
6ea27c9f4feb-8 | }))
}
export default function Page({
params,
}: {
params: { category: string; product: string }
}) {
// ...
}
Good to know: When rendering a route, Next.js will automatically deduplicate fetch requests for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
b4a14755a81b-0 | headersThe headers function allows you to read the HTTP incoming request headers from a Server Component.
headers()
This API extends the Web Headers API. It is read-only, meaning you cannot set / delete the outgoing request headers.
app/page.tsx import { headers } from 'next/headers'
export default function Page() {
... | https://nextjs.org/docs/app/api-reference/functions/headers |
b4a14755a81b-1 | Headers.entries(): Returns an iterator allowing to go through all key/value pairs contained in this object.
Headers.forEach(): Executes a provided function once for each key/value pair in this Headers object.
Headers.get(): Returns a String sequence of all the values of a header within a Headers object with a given nam... | https://nextjs.org/docs/app/api-reference/functions/headers |
b4a14755a81b-2 | const authorization = headersInstance.get('authorization')
// Forward the authorization header
const res = await fetch('...', {
headers: { authorization },
})
return res.json()
}
export default async function UserPage() {
const user = await getUser()
return <h1>{user.name}</h1>
}
Version History
Versi... | https://nextjs.org/docs/app/api-reference/functions/headers |
9de461750099-0 | ImageResponseThe ImageResponse constructor allows you to generate dynamic images using JSX and CSS. This is useful for generating social media images such as Open Graph images, Twitter cards, and more.
The following options are available for ImageResponse:
import { ImageResponse } from 'next/server'
new ImageRespons... | https://nextjs.org/docs/app/api-reference/functions/image-response |
9de461750099-1 | status?: number = 200
statusText?: string
headers?: Record<string, string>
},
)
Supported CSS Properties
Please refer to Satori’s documentation for a list of supported HTML and CSS features.
Version History
VersionChangesv13.3.0ImageResponse can be imported from next/server.v13.0.0ImageResponse introduced via... | https://nextjs.org/docs/app/api-reference/functions/image-response |
66143d2debff-0 | NextRequestNextRequest extends the Web Request API with additional convenience methods.
cookies
Read or mutate the Set-Cookie header of the request.
set(name, value)
Given a name, set a cookie with the given value on the request.
// Given incoming request /home
// Set a cookie to hide the banner
// request will have a... | https://nextjs.org/docs/app/api-reference/functions/next-request |
66143d2debff-1 | request.cookies.get('show-banner')
getAll()
Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the request.
// Given incoming request /home
// [
// { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
// { name: 'experiments', value: 'winter-launch', Path... | https://nextjs.org/docs/app/api-reference/functions/next-request |
66143d2debff-2 | request.cookies.has('experiments')
clear()
Remove the Set-Cookie header from the request.
request.cookies.clear()
nextUrl
Extends the native URL API with additional convenience methods, including Next.js specific properties.
// Given a request to /home, pathname is /home
request.nextUrl.pathname
// Given a request to... | https://nextjs.org/docs/app/api-reference/functions/next-request |
db80150bc65b-0 | NextResponseNextResponse extends the Web Response API with additional convenience methods.
cookies
Read or mutate the Set-Cookie header of the response.
set(name, value)
Given a name, set a cookie with the given value on the response.
// Given incoming request /home
let response = NextResponse.next()
// Set a cookie t... | https://nextjs.org/docs/app/api-reference/functions/next-response |
db80150bc65b-1 | response.cookies.get('show-banner')
getAll()
Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the response.
// Given incoming request /home
let response = NextResponse.next()
// [
// { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
// { name: 'exper... | https://nextjs.org/docs/app/api-reference/functions/next-response |
db80150bc65b-2 | json()
Produce a response with the given JSON body.
app/api/route.ts import { NextResponse } from 'next/server'
export async function GET(request: Request) {
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
redirect()
Produce a response that redirects to a URL.
import { NextResponse ... | https://nextjs.org/docs/app/api-reference/functions/next-response |
db80150bc65b-3 | // Add ?from=/incoming-url to the /login URL
loginUrl.searchParams.set('from', request.nextUrl.pathname)
// And redirect to the new URL
return NextResponse.redirect(loginUrl)
rewrite()
Produce a response that rewrites (proxies) the given URL while preserving the original URL.
import { NextResponse } from 'next/server'... | https://nextjs.org/docs/app/api-reference/functions/next-response |
db80150bc65b-4 | import { NextResponse } from 'next/server'
// Given an incoming request...
const newHeaders = new Headers(request.headers)
// Add a new header
newHeaders.set('x-version', '123')
// And produce a response with the new headers
return NextResponse.next({
request: {
// New request headers
headers: newHeaders,
... | https://nextjs.org/docs/app/api-reference/functions/next-response |
9eeda12cf0af-0 | notFoundThe notFound function allows you to render the not-found file within a route segment as well as inject a <meta name="robots" content="noindex" /> tag.
notFound()
Invoking the notFound() function throws a NEXT_NOT_FOUND error and terminates rendering of the route segment in which it was thrown. Specifying a not-... | https://nextjs.org/docs/app/api-reference/functions/not-found |
9eeda12cf0af-1 | notFound()
}
// ...
}
Good to know: notFound() does not require you to use return notFound() due to using the TypeScript never type.
Version History
VersionChangesv13.0.0notFound introduced. | https://nextjs.org/docs/app/api-reference/functions/not-found |
eb3aba3a1e25-0 | redirectThe redirect function allows you to redirect the user to another URL. redirect can be used in Server Components, Client Components, Route Handlers, and Server Actions.
If you need to redirect to a 404, use the notFound function instead.
Parameters
The redirect function accepts two arguments:
redirect(path, typ... | https://nextjs.org/docs/app/api-reference/functions/redirect |
eb3aba3a1e25-1 | Returns
redirect does not return any value.
Example
Invoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.
app/team/[id]/page.js import { redirect } from 'next/navigation'
async function fetchTeam(id) {
const res = await fetch('https://...... | https://nextjs.org/docs/app/api-reference/functions/redirect |
ea4d089e49b4-0 | revalidatePathrevalidatePath allows you to revalidate data associated with a specific path. This is useful for scenarios where you want to update your cached data without waiting for a revalidation period to expire.
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidateP... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
ea4d089e49b4-1 | Good to know:
revalidatePath is available in both Node.js and Edge runtimes.
revalidatePath will revalidate all segments under a dynamic route segment. For example, if you have a dynamic segment /product/[id] and you call revalidatePath('/product/[id]'), then all segments under /product/[id] will be revalidated as requ... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
ea4d089e49b4-2 | Returns
revalidatePath does not return any value.
Examples
Node.js Runtime
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path') || '/'
... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
ea4d089e49b4-3 | revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
84313f942a21-0 | revalidateTagrevalidateTag allows you to revalidate data associated with a specific cache tag. This is useful for scenarios where you want to update your cached data without waiting for a revalidation period to expire.
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalida... | https://nextjs.org/docs/app/api-reference/functions/revalidateTag |
84313f942a21-1 | You can add tags to fetch as follows:
fetch(url, { next: { tags: [...] } });
Returns
revalidateTag does not return any value.
Examples
Node.js Runtime
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request: Next... | https://nextjs.org/docs/app/api-reference/functions/revalidateTag |
84313f942a21-2 | export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
} | https://nextjs.org/docs/app/api-reference/functions/revalidateTag |
cb9ff5bbd24c-0 | useParamsuseParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL.
app/example-client-component.tsx 'use client'
import { useParams } from 'next/navigation'
export default function ExampleClientComponent() {
const params = useParams()
// Route -> /shop/[tag... | https://nextjs.org/docs/app/api-reference/functions/use-params |
cb9ff5bbd24c-1 | Each property in the object is an active dynamic segment.
The properties name is the segment's name, and the properties value is what the segment is filled in with.
The properties value will either be a string or array of string's depending on the type of dynamic segment.
If the route contains no dynamic parameters, us... | https://nextjs.org/docs/app/api-reference/functions/use-params |
9085570e8c89-0 | usePathnameusePathname is a Client Component hook that lets you read the current URL's pathname.
app/example-client-component.tsx 'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p... | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
9085570e8c89-1 | Good to know:
Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.
Compatibility mode:
usePathname can return null when a fallback route is being rendered or when a pages directory page has been automatically static... | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
9085570e8c89-2 | import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// Do something here...
}, [pathname, searchParams])
}
VersionChangesv13.0.0usePathname introduced. | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
486dbdce1797-0 | useReportWebVitals
The useReportWebVitals hook allows you to report Core Web Vitals, and can be used in combination with your analytics service.
app/_components/web-vitals.js 'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
consol... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-1 | {children}
</body>
</html>
)
}
Since the useReportWebVitals hook requires the "use client" directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the WebVitals component.
useReportWebVitals
The metric object pa... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-2 | entries: An array of Performance Entries associated with the metric. These entries provide detailed information about the performance events related to the metric.
navigationType: Indicates the type of navigation that triggered the metric collection. Possible values include "navigate", "reload", "back_forward", and "pr... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-3 | Web Vitals
Web Vitals are a set of useful metrics that aim to capture the user
experience of a web page. The following web vitals are all included:
Time to First Byte (TTFB)
First Contentful Paint (FCP)
Largest Contentful Paint (LCP)
First Input Delay (FID)
Cumulative Layout Shift (CLS)
Interaction to Next Paint (INP)
... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-4 | }
case 'LCP': {
// handle LCP results
}
// ...
}
})
}
Usage on Vercel
Vercel Speed Insights are automatically configured on Vercel deployments, and don't require the use of useReportWebVitals. This hook is useful in local development, or if you're using a different analytics service.
Sen... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-5 | navigator.sendBeacon(url, body)
} else {
fetch(url, { body, method: 'POST', keepalive: true })
}
})
Good to know: If you use Google Analytics, using the
id value can allow you to construct metric distributions manually (to calculate percentiles,
etc.)
useReportWebVitals(metric => {
// Use `window.gtag` if yo... | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
486dbdce1797-6 | non_interaction: true, // avoids affecting bounce rate.
});
}
Read more about sending results to Google Analytics. | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals |
a32e123ba449-0 | useRouterThe useRouter hook allows you to programmatically change routes inside Client Components.
Recommendation: Use the <Link> component for navigation unless you have a specific requirement for using useRouter.
app/example-client-component.tsx 'use client'
import { useRouter } from 'next/navigation'
export defa... | https://nextjs.org/docs/app/api-reference/functions/use-router |
a32e123ba449-1 | router.refresh(): Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. useState) or browser state (e.g. scroll position).
router.pre... | https://nextjs.org/docs/app/api-reference/functions/use-router |
a32e123ba449-2 | next/link automatically prefetch routes as they become visible in the viewport.
refresh() could re-produce the same result if fetch requests are cached. Other dynamic functions like cookies and headers could also change the response.
Migrating from the pages directory:
The new useRouter hook should be imported from nex... | https://nextjs.org/docs/app/api-reference/functions/use-router |
a32e123ba449-3 | export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
// You can now use the current URL
// ...
}, [pathname, searchParams])
return null
}
Which can be imported... | https://nextjs.org/docs/app/api-reference/functions/use-router |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.