text
stringlengths 49
1.09k
| source
stringclasses 119
values | id
stringlengths 14
15
|
---|---|---|
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="(prefers-color-scheme: dark)" content="black" />
manifest
A web application manifest, as defined in the Web Application Manifest specification.
layout.js / page.js export const metadata = {
manifest: 'https://nextjs.org/manifest.json',
}
<head> output <link rel="manifest" href="https://nextjs.org/manifest.json" />
twitter
Learn more about the Twitter Card markup reference.
layout.js / page.js export const metadata = { | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-22 |
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> output <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" /> | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-23 |
<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 Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: {
url: 'https://nextjs.org/og.png',
alt: 'Next.js Logo',
},
app: {
name: 'twitter_app',
id: {
iphone: 'twitter_app://iphone',
ipad: 'twitter_app://ipad', | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-24 |
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" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:card" content="app" />
<meta name="twitter:image" content="https://nextjs.org/og.png" />
<meta name="twitter:image:alt" content="Next.js Logo" /> | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-25 |
<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://googleplay" />
<meta name="twitter:app:url:iphone" content="https://iphone_url" />
<meta name="twitter:app:url:ipad" content="https://ipad_url" />
<meta name="twitter:app:name:ipad" content="twitter_app" />
<meta name="twitter:app:name:googleplay" content="twitter_app" />
viewport | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-26 |
<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 export const metadata = {
viewport: {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
},
}
<head> output <meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
verification
layout.js / page.js export const metadata = {
verification: {
google: 'google',
yandex: 'yandex',
yahoo: 'yahoo',
other: {
me: ['my-email', 'my-link'],
},
}, | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-27 |
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 const metadata = {
itunes: {
appId: 'myAppStoreID',
appArgument: 'myAppArgument',
},
appleWebApp: {
title: 'Apple Web App',
statusBarStyle: 'black-translucent',
startupImage: [
'/assets/startup/apple-touch-startup-image-768x1004.png',
{ | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-28 |
{
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" content="yes" />
<meta name="apple-mobile-web-app-title" content="Apple Web App" />
<link
href="/assets/startup/apple-touch-startup-image-768x1004.png"
rel="apple-touch-startup-image"
/>
<link
href="/assets/startup/apple-touch-startup-image-1536x2008.png" | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-29 |
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: {
canonical: 'https://nextjs.org',
languages: {
'en-US': 'https://nextjs.org/en-US',
'de-DE': 'https://nextjs.org/de-DE',
},
media: {
'only screen and (max-width: 600px)': 'https://nextjs.org/mobile',
},
types: {
'application/rss+xml': 'https://nextjs.org/rss', | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-30 |
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"
media="only screen and (max-width: 600px)"
href="https://nextjs.org/mobile"
/>
<link
rel="alternate"
type="application/rss+xml"
href="https://nextjs.org/rss"
/>
appLinks
layout.js / page.js export const metadata = {
appLinks: {
ios: {
url: 'https://nextjs.org/ios', | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-31 |
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:url" content="https://nextjs.org/ios" />
<meta property="al:ios:app_store_id" content="app_store_id" />
<meta property="al:android:package" content="com.example.android/package" />
<meta property="al:android:app_name" content="app_name_android" />
<meta property="al:web:url" content="https://nextjs.org/web" /> | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-32 |
<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'],
}
<head> output <link rel="archives" href="https://nextjs.org/13" />
assets
layout.js / page.js export const metadata = {
assets: ['https://nextjs.org/assets'],
}
<head> output <link rel="assets" href="https://nextjs.org/assets" />
bookmarks
layout.js / page.js export const metadata = {
bookmarks: ['https://nextjs.org/13'],
} | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-33 |
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 support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the other option to render any custom metadata tag.
layout.js / page.js export const metadata = {
other: {
custom: 'meta',
},
}
<head> output <meta name="custom" content="meta" />
Unsupported Metadata
The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself. | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-34 |
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="stylesheet" />import stylesheets directly in the layout or page itself.<link rel="preload />Use ReactDOM preload method<link rel="preconnect" />Use ReactDOM preconnect method<link rel="dns-prefetch" />Use ReactDOM prefetchDNS method
Resource hints
The <link> element has a number of rel keywords that can be used to hint to the browser that a external resource is likely to be needed. The browser uses this information to apply preloading optimizations depending on the keyword.
While the Metadata API doesn't directly support these hints, you can use new ReactDOM methods to safely insert them into the <head> of the document. | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-35 |
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 rendering (browser) lifecycle. MDN Docs.
ReactDOM.preload(href: string, options: { as: string })
<head> output <link rel="preload" href="..." as="..." />
<link rel="preconnect">
Preemptively initiate a connection to an origin. MDN Docs.
ReactDOM.preconnect(href: string, options?: { crossOrigin?: string })
<head> output <link rel="preconnect" href="..." crossorigin />
<link rel="dns-prefetch"> | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-36 |
<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 page load.
Next.js in-built features such as next/font, next/image and next/script automatically handle relevant resource hints.
React 18.3 does not yet include type definitions for ReactDOM.preload, ReactDOM.preconnect, and ReactDOM.preconnectDNS. You can use // @ts-ignore as a temporary solution to avoid type errors.
Types
You can add type safety to your metadata by using the Metadata type. If you are using the built-in TypeScript plugin in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
metadata object | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-37 |
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 { Metadata } from 'next'
export async function generateMetadata(): Promise<Metadata> {
return {
title: 'Next.js',
}
}
With segment props
import type { Metadata } from 'next'
type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export function generateMetadata({ params, searchParams }: Props): Metadata {
return {
title: 'Next.js', | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-38 |
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 {
title: 'Next.js',
}
}
JavaScript Projects
For JavaScript projects, you can use JSDoc to add type safety.
/** @type {import("next").Metadata} */
export const metadata = {
title: 'Next.js',
}
Version History
VersionChangesv13.2.0metadata and generateMetadata introduced. | https://nextjs.org/docs/app/api-reference/functions/generate-metadata | 196df85b10c4-39 |
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 { revalidateTag } from 'next/cache'
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
Good to know:
revalidateTag is available in both Node.js and Edge runtimes.
Parameters
revalidateTag(tag: string): void;
tag: A string representing the cache tag associated with the data you want to revalidate.
You can add tags to fetch as follows: | https://nextjs.org/docs/app/api-reference/functions/revalidateTag | 773b10a2c8d9-0 |
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: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
Edge Runtime
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
export const runtime = 'edge'
export async function GET(request: NextRequest) { | https://nextjs.org/docs/app/api-reference/functions/revalidateTag | 773b10a2c8d9-1 |
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 | 773b10a2c8d9-2 |
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) => {
console.log(metric)
})
}app/layout.js import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
} | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-0 |
{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 passed as the hook's argument consists of a number of properties:
id: Unique identifier for the metric in the context of the current page load
name: The name of the performance metric. Possible values include names of Web Vitals metrics (TTFB, FCP, LCP, FID, CLS) specific to a web application.
delta: The difference between the current value and the previous value of the metric. The value is typically in milliseconds and represents the change in the metric's value over time. | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-1 |
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 "prerender".
rating: A qualitative rating of the metric value, providing an assessment of the performance. Possible values are "good", "needs-improvement", and "poor". The rating is typically determined by comparing the metric value against predefined thresholds that indicate acceptable or suboptimal performance.
value: The actual value or duration of the performance entry, typically in milliseconds. The value provides a quantitative measure of the performance aspect being tracked by the metric. The source of the value depends on the specific metric being measured and can come from various Performance APIs.
Web Vitals
Web Vitals are a set of useful metrics that aim to capture the user | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-2 |
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)
You can handle all the results of these metrics using the name property.
app/components/web-vitals.tsx 'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-3 |
}
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.
Sending results to external systems
You can send results to any endpoint to measure and track
real user performance on your site. For example:
useReportWebVitals((metric) => {
const body = JSON.stringify(metric)
const url = 'https://example.com/analytics'
// Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body)
} else { | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-4 |
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 you initialized Google Analytics as this example:
// https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js
window.gtag('event', metric.name, {
value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), // values must be integers
event_label: metric.id, // id unique to current page load
non_interaction: true, // avoids affecting bounce rate.
});
} | https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals | 69272406201d-5 |
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 | 69272406201d-6 |
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 `Set-Cookie:show-banner=false;path=/home` header
request.cookies.set('show-banner', 'false')
get(name)
Given a cookie name, return the value of the cookie. If the cookie is not found, undefined is returned. If multiple cookies are found, the first one is returned.
// Given incoming request /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')
getAll() | https://nextjs.org/docs/app/api-reference/functions/next-request | 83f03255d776-0 |
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: '/home' },
// ]
request.cookies.getAll('experiments')
// Alternatively, get all cookies for the request
request.cookies.getAll()
delete(name)
Given a cookie name, delete the cookie from the request.
// Returns true for deleted, false is nothing is deleted
request.cookies.delete('experiments')
has(name)
Given a cookie name, return true if the cookie exists on the request.
// Returns true if cookie exists, false if it does not
request.cookies.has('experiments')
clear() | https://nextjs.org/docs/app/api-reference/functions/next-request | 83f03255d776-1 |
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 /home?name=lee, searchParams is { 'name': 'lee' }
request.nextUrl.searchParams
Version History
VersionChangesv13.0.0useSearchParams introduced. | https://nextjs.org/docs/app/api-reference/functions/next-request | 83f03255d776-2 |
cookiesThe cookies function allows you to read the HTTP incoming request cookies from a Server Component or write outgoing request cookies in a Server Action or Route Handler.
Good to know: cookies() is a Dynamic Function whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering at request time.
cookies().get(name)
A method that takes a cookie name and returns an object with name and value. If a cookie with name isn't found, it returns undefined. If multiple cookies match, it will only return the first match.
app/page.js import { cookies } from 'next/headers'
export default function Page() {
const cookieStore = cookies()
const theme = cookieStore.get('theme')
return '...'
}
cookies().getAll() | https://nextjs.org/docs/app/api-reference/functions/cookies | d6585901e528-0 |
return '...'
}
cookies().getAll()
A method that is similar to get, but returns a list of all the cookies with a matching name. If name is unspecified, it returns all the available cookies.
app/page.js import { cookies } from 'next/headers'
export default function Page() {
const cookieStore = cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
cookies().has(name)
A method that takes a cookie name and returns a boolean based on if the cookie exists (true) or not (false).
app/page.js import { cookies } from 'next/headers'
export default function Page() {
const cookiesList = cookies() | https://nextjs.org/docs/app/api-reference/functions/cookies | d6585901e528-1 |
export default function Page() {
const cookiesList = cookies()
const hasCookie = cookiesList.has('theme')
return '...'
}
cookies().set(name, value, options)
A method that takes a cookie name, value, and options and sets the outgoing request cookie.
Good to know: .set() is only available in a Server Action or Route Handler.
app/actions.js 'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().set('name', 'lee')
// or
cookies().set('name', 'lee', { secure: true })
// or
cookies().set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
Deleting cookies | https://nextjs.org/docs/app/api-reference/functions/cookies | d6585901e528-2 |
httpOnly: true,
path: '/',
})
}
Deleting cookies
To "delete" a cookie, you must set a new cookie with the same name and an empty value. You can also set the maxAge to 0 to expire the cookie immediately.
Good to know: .set() is only available in a Server Action or Route Handler.
app/actions.js 'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().set({
name: 'name',
value: '',
expires: new Date('2016-10-05'),
path: '/', // For all paths
})
}
You can only set cookies that belong to the same domain from which .set() is called. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to update. | https://nextjs.org/docs/app/api-reference/functions/cookies | d6585901e528-3 |
Version History
VersionChangesv13.0.0cookies introduced. | https://nextjs.org/docs/app/api-reference/functions/cookies | d6585901e528-4 |
useSelectedLayoutSegmentsuseSelectedLayoutSegments is a Client Component hook that lets you read the active route segments below the Layout it is called from.
It is useful for creating UI in parent Layouts that need knowledge of active child segments such as breadcrumbs.
app/example-client-component.tsx 'use client'
import { useSelectedLayoutSegments } from 'next/navigation'
export default function ExampleClientComponent() {
const segments = useSelectedLayoutSegments()
return (
<ul>
{segments.map((segment, index) => (
<li key={index}>{segment}</li>
))}
</ul>
)
}
Good to know:
Since useSelectedLayoutSegments is a Client Component hook, and Layouts are Server Components by default, useSelectedLayoutSegments is usually called via a Client Component that is imported into a Layout. | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments | c25fb76d9190-0 |
The returned segments include Route Groups, which you might not want to be included in your UI. You can use the filter() array method to remove items that start with a bracket.
Parameters
const segments = useSelectedLayoutSegments()
useSelectedLayoutSegments does not take any parameters.
Returns
useSelectedLayoutSegments returns an array of strings containing the active segments one level down from the layout the hook was called from. Or an empty array if none exist.
For example, given the Layouts and URLs below, the returned segments would be:
LayoutVisited URLReturned Segmentsapp/layout.js/[]app/layout.js/dashboard['dashboard']app/layout.js/dashboard/settings['dashboard', 'settings']app/dashboard/layout.js/dashboard[]app/dashboard/layout.js/dashboard/settings['settings']
Version History
VersionChangesv13.0.0useSelectedLayoutSegments introduced. | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments | c25fb76d9190-1 |
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 to hide the banner
response.cookies.set('show-banner', 'false')
// Response will have a `Set-Cookie:show-banner=false;path=/home` header
return response
get(name)
Given a cookie name, return the value of the cookie. If the cookie is not found, undefined is returned. If multiple cookies are found, the first one is returned.
// Given incoming request /home
let response = NextResponse.next()
// { name: 'show-banner', value: 'false', Path: '/home' }
response.cookies.get('show-banner')
getAll() | https://nextjs.org/docs/app/api-reference/functions/next-response | 5c0d7304f3f5-0 |
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: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
response.cookies.getAll('experiments')
// Alternatively, get all cookies for the response
response.cookies.getAll()
delete(name)
Given a cookie name, delete the cookie from the response.
// Given incoming request /home
let response = NextResponse.next()
// Returns true for deleted, false is nothing is deleted
response.cookies.delete('experiments')
json()
Produce a response with the given JSON body. | https://nextjs.org/docs/app/api-reference/functions/next-response | 5c0d7304f3f5-1 |
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 } from 'next/server'
return NextResponse.redirect(new URL('/new', request.url))
The URL can be created and modified before being used in the NextResponse.redirect() method. For example, you can use the request.nextUrl property to get the current URL, and then modify it to redirect to a different URL.
import { NextResponse } from 'next/server'
// Given an incoming request...
const loginUrl = new URL('/login', request.url)
// Add ?from=/incoming-url to the /login URL | https://nextjs.org/docs/app/api-reference/functions/next-response | 5c0d7304f3f5-2 |
// 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'
// Incoming request: /about, browser shows /about
// Rewritten request: /proxy, browser shows /about
return NextResponse.rewrite(new URL('/proxy', request.url))
next()
The next() method is useful for Middleware, as it allows you to return early and continue routing.
import { NextResponse } from 'next/server'
return NextResponse.next()
You can also forward headers when producing the response:
import { NextResponse } from 'next/server'
// Given an incoming request... | https://nextjs.org/docs/app/api-reference/functions/next-response | 5c0d7304f3f5-3 |
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 | 5c0d7304f3f5-4 |
httpAgentOptions
In Node.js versions prior to 18, Next.js automatically polyfills fetch() with node-fetch and enables HTTP Keep-Alive by default.
To disable HTTP Keep-Alive for all fetch() calls on the server-side, open next.config.js and add the httpAgentOptions config:
next.config.js module.exports = {
httpAgentOptions: {
keepAlive: false,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/httpAgentOptions | 62aabf5c6e55-0 |
rewrites
Rewrites allow you to map an incoming request path to a different destination path.
Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, redirects will reroute to a new page and show the URL changes.
To use rewrites you can use the rewrites key in next.config.js:
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
Rewrites are applied to client-side routing, a <Link href="/about"> will have the rewrite applied in the above example.
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:
source: String - is the incoming request path pattern. | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-0 |
source: String - is the incoming request path pattern.
destination: String is the path you want to route to.
basePath: false or undefined - if false the basePath won't be included when matching, can be used for external rewrites only.
locale: false or undefined - whether the locale should not be included when matching.
has is an array of has objects with the type, key and value properties.
missing is an array of missing objects with the type, key and value properties.
When the rewrites function returns an array, rewrites are applied after checking the filesystem (pages and /public files) and before dynamic routes. When the rewrites function returns an object of arrays with a specific shape, this behavior can be changed and more finely controlled, as of v10.1 of Next.js:
next.config.js module.exports = {
async rewrites() {
return {
beforeFiles: [ | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-1 |
async rewrites() {
return {
beforeFiles: [
// These rewrites are checked after headers/redirects
// and before all files including _next/public files which
// allows overriding page files
{
source: '/some-page',
destination: '/somewhere-else',
has: [{ type: 'query', key: 'overrideMe' }],
},
],
afterFiles: [
// These rewrites are checked after pages/public files
// are checked but before dynamic routes
{
source: '/non-existent',
destination: '/somewhere-else',
},
],
fallback: [
// These rewrites are checked after both pages/public files
// and dynamic routes are checked
{
source: '/:path*', | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-2 |
// and dynamic routes are checked
{
source: '/:path*',
destination: `https://my-old-site.com/:path*`,
},
],
}
},
}
Good to know: rewrites in beforeFiles do not check the filesystem/dynamic routes immediately after matching a source, they continue until all beforeFiles have been checked.
The order Next.js routes are checked is:
headers are checked/applied
redirects are checked/applied
beforeFiles rewrites are checked/applied
static files from the public directory, _next/static files, and non-dynamic pages are checked/served
afterFiles rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-3 |
fallback rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use fallback: true/'blocking' in getStaticPaths, the fallback rewrites defined in your next.config.js will not be run.
Rewrite parameters
When using parameters in a rewrite the parameters will be passed in the query by default when none of the parameters are used in the destination.
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/old-about/:path*',
destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
},
]
},
}
If a parameter is used in the destination none of the parameters will be automatically passed in the query.
next.config.js module.exports = {
async rewrites() {
return [
{ | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-4 |
async rewrites() {
return [
{
source: '/docs/:path*',
destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
},
]
},
}
You can still pass the parameters manually in the query if one is already used in the destination by specifying the query in the destination.
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/:first/:second',
destination: '/:first?second=:second',
// Since the :first parameter is used in the destination the :second parameter
// will not automatically be added in the query although we can manually add it
// as shown above
},
]
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-5 |
// as shown above
},
]
},
}
Good to know: Static pages from Automatic Static Optimization or prerendering params from rewrites will be parsed on the client after hydration and provided in the query.
Path Matching
Path matches are allowed, for example /blog/:slug will match /blog/hello-world (no nested paths):
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug',
destination: '/news/:slug', // Matched parameters can be used in the destination
},
]
},
}
Wildcard Path Matching
To match a wildcard path you can use * after a parameter, for example /blog/:slug* will match /blog/a/b/c/d/hello-world:
next.config.js module.exports = {
async rewrites() {
return [
{ | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-6 |
async rewrites() {
return [
{
source: '/blog/:slug*',
destination: '/news/:slug*', // Matched parameters can be used in the destination
},
]
},
}
Regex Path Matching
To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\\d{1,}) will match /blog/123 but not /blog/abc:
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/old-blog/:post(\\d{1,})',
destination: '/blog/:post', // Matched parameters can be used in the destination
},
]
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-7 |
},
]
},
}
The following characters (, ), {, }, :, *, +, ? are used for regex path matching, so when used in the source as non-special values they must be escaped by adding \\ before them:
next.config.js module.exports = {
async rewrites() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
destination: '/en-us/:slug',
},
]
},
}
Header, Cookie, and Query Matching
To only match a rewrite when header, cookie, or query values also match the has field or don't match the missing field can be used. Both the source and all has items must match and all missing items must not match for the rewrite to be applied.
has and missing items can have the following fields: | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-8 |
has and missing items can have the following fields:
type: String - must be either header, cookie, host, or query.
key: String - the key from the selected type to match against.
value: String or undefined - the value to check for, if undefined any value will match. A regex like string can be used to capture a specific part of the value, e.g. if the value first-(?<paramName>.*) is used for first-second then second will be usable in the destination with :paramName.
next.config.js module.exports = {
async rewrites() {
return [
// if the header `x-rewrite-me` is present,
// this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-rewrite-me',
},
], | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-9 |
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the header `x-rewrite-me` is not present,
// this rewrite will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this rewrite will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't
// use a named capture group e.g. (?<page>home) | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-10 |
// use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
destination: '/:path*/home',
},
// if the header `x-authorized` is present and
// contains a matching value, this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`,
// this rewrite will be applied
{
source: '/:path*',
has: [ | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-11 |
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
destination: '/another-page',
},
]
},
}
Rewriting to an external URL
Examples
Incremental adoption of Next.js
Using Multiple Zones
Rewrites allow you to rewrite to an external url. This is especially useful for incrementally adopting Next.js. The following is an example rewrite for redirecting the /blog route of your main app to an external site.
next.config.js module.exports = {
async rewrites() {
return [
{
source: '/blog',
destination: 'https://example.com/blog',
},
{
source: '/blog/:slug', | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-12 |
},
{
source: '/blog/:slug',
destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination
},
]
},
}
If you're using trailingSlash: true, you also need to insert a trailing slash in the source parameter. If the destination server is also expecting a trailing slash it should be included in the destination parameter as well.
next.config.js module.exports = {
trailingSlash: true,
async rewrites() {
return [
{
source: '/blog/',
destination: 'https://example.com/blog/',
},
{
source: '/blog/:path*/',
destination: 'https://example.com/blog/:path*/',
},
]
},
}
Incremental adoption of Next.js | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-13 |
},
]
},
}
Incremental adoption of Next.js
You can also have Next.js fall back to proxying to an existing website after checking all Next.js routes.
This way you don't have to change the rewrites configuration when migrating more pages to Next.js
next.config.js module.exports = {
async rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
},
],
}
},
}
Rewrites with basePath support
When leveraging basePath support with rewrites each source and destination is automatically prefixed with the basePath unless you add basePath: false to the rewrite:
next.config.js module.exports = {
basePath: '/docs',
async rewrites() {
return [
{ | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-14 |
async rewrites() {
return [
{
source: '/with-basePath', // automatically becomes /docs/with-basePath
destination: '/another', // automatically becomes /docs/another
},
{
// does not add /docs to /without-basePath since basePath: false is set
// Note: this can not be used for internal rewrites e.g. `destination: '/another'`
source: '/without-basePath',
destination: 'https://example.com',
basePath: false,
},
]
},
}
Rewrites with i18n support
When leveraging i18n support with rewrites each source and destination is automatically prefixed to handle the configured locales unless you add locale: false to the rewrite. If locale: false is used you must prefix the source and destination with a locale for it to be matched correctly. | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-15 |
next.config.js module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async rewrites() {
return [
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
destination: '/en/another',
locale: false,
},
{
// it's possible to match all locales even when locale: false is set | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-16 |
{
// it's possible to match all locales even when locale: false is set
source: '/:locale/api-alias/:path*',
destination: '/api/:path*',
locale: false,
},
{
// this gets converted to /(en|fr|de)/(.*) so will not match the top-level
// `/` or `/fr` routes like /:path* would
source: '/(.*)',
destination: '/another',
},
]
},
}
Version History
VersionChangesv13.3.0missing added.v10.2.0has added.v9.5.0Headers added. | https://nextjs.org/docs/app/api-reference/next-config-js/rewrites | 3d98a9482851-17 |
basePath
To deploy a Next.js application under a sub-path of a domain you can use the basePath config option.
basePath allows you to set a path prefix for the application. For example, to use /docs instead of '' (an empty string, the default), open next.config.js and add the basePath config:
next.config.js module.exports = {
basePath: '/docs',
}
Good to know: This value must be set at build time and cannot be changed without re-building as the value is inlined in the client-side bundles.
Links
When linking to other pages using next/link and next/router the basePath will be automatically applied.
For example, using /about will automatically become /docs/about when basePath is set to /docs.
export default function HomePage() {
return (
<>
<Link href="/about">About Page</Link>
</>
)
}
Output html: | https://nextjs.org/docs/app/api-reference/next-config-js/basePath | 2e26ac457135-0 |
</>
)
}
Output html:
<a href="/docs/about">About Page</a>
This makes sure that you don't have to change all links in your application when changing the basePath value.
Images
When using the next/image component, you will need to add the basePath in front of src.
For example, using /docs/me.png will properly serve your image when basePath is set to /docs.
import Image from 'next/image'
function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src="/docs/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
<p>Welcome to my homepage!</p>
</>
)
}
export default Home | https://nextjs.org/docs/app/api-reference/next-config-js/basePath | 2e26ac457135-1 |
eslint
When ESLint is detected in your project, Next.js fails your production build (next build) when errors are present.
If you'd like Next.js to produce production code even when your application has ESLint errors, you can disable the built-in linting step completely. This is not recommended unless you already have ESLint configured to run in a separate part of your workflow (for example, in CI or a pre-commit hook).
Open next.config.js and enable the ignoreDuringBuilds option in the eslint config:
next.config.js module.exports = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/eslint | 03fbf5ececda-0 |
Runtime Config
Good to know: This feature is considered legacy and does not work with Automatic Static Optimization, Output File Tracing, or React Server Components. Please use environment variables instead to avoid initialization overhead.
To add runtime configuration to your app, open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
next.config.js module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
Place any server-only runtime config under serverRuntimeConfig.
Anything accessible to both client and server-side code should be under publicRuntimeConfig. | https://nextjs.org/docs/app/api-reference/next-config-js/runtime-configuration | e8a1354e8ffc-0 |
Anything accessible to both client and server-side code should be under publicRuntimeConfig.
A page that relies on publicRuntimeConfig must use getInitialProps or getServerSideProps or your application must have a Custom App with getInitialProps to opt-out of Automatic Static Optimization. Runtime configuration won't be available to any page (or component in a page) without being server-side rendered.
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
import Image from 'next/image'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<Image | https://nextjs.org/docs/app/api-reference/next-config-js/runtime-configuration | e8a1354e8ffc-1 |
function MyImage() {
return (
<div>
<Image
src={`${publicRuntimeConfig.staticFolder}/logo.png`}
alt="logo"
layout="fill"
/>
</div>
)
}
export default MyImage | https://nextjs.org/docs/app/api-reference/next-config-js/runtime-configuration | e8a1354e8ffc-2 |
incrementalCacheHandlerPathIn Next.js, the default cache handler uses the filesystem cache. This requires no configuration, however, you can customize the cache handler by using the incrementalCacheHandlerPath field in next.config.js.
next.config.js module.exports = {
experimental: {
incrementalCacheHandlerPath: require.resolve('./cache-handler.js'),
},
}
Here's an example of a custom cache handler:
cache-handler.js const cache = new Map()
module.exports = class CacheHandler {
constructor(options) {
this.options = options
this.cache = {}
}
async get(key) {
return cache.get(key)
}
async set(key, data) {
cache.set(key, {
value: data,
lastModified: Date.now(),
})
}
}
API Reference | https://nextjs.org/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath | 4a1968ce53c9-0 |
lastModified: Date.now(),
})
}
}
API Reference
The cache handler can implement the following methods: get, set, and revalidateTag.
get()
ParameterTypeDescriptionkeystringThe key to the cached value.
Returns the cached value or null if not found.
set()
ParameterTypeDescriptionkeystringThe key to store the data under.dataData or nullThe data to be cached.
Returns Promise<void>.
revalidateTag()
ParameterTypeDescriptiontagstringThe cache tag to revalidate.
Returns Promise<void>. Learn more about revalidating data or the revalidateTag() function. | https://nextjs.org/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath | 4a1968ce53c9-1 |
transpilePackages
Next.js can automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (node_modules). This replaces the next-transpile-modules package.
next.config.js /** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['@acme/ui', 'lodash-es'],
}
module.exports = nextConfig
Version History
VersionChangesv13.0.0transpilePackages added. | https://nextjs.org/docs/app/api-reference/next-config-js/transpilePackages | cb09ebc216f5-0 |
generateEtags
Next.js will generate etags for every page by default. You may want to disable etag generation for HTML pages depending on your cache strategy.
Open next.config.js and disable the generateEtags option:
next.config.js module.exports = {
generateEtags: false,
} | https://nextjs.org/docs/app/api-reference/next-config-js/generateEtags | ce073d2687f8-0 |
appDir
Good to know: This option is no longer needed as of Next.js 13.4. The App Router is now stable.
The App Router (app directory) enables support for layouts, Server Components, streaming, and colocated data fetching.
Using the app directory will automatically enable React Strict Mode. Learn how to incrementally adopt app. | https://nextjs.org/docs/app/api-reference/next-config-js/appDir | 9d6d783ecaa9-0 |
redirects
Redirects allow you to redirect an incoming request path to a different destination path.
To use redirects you can use the redirects key in next.config.js:
next.config.js module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
redirects is an async function that expects an array to be returned holding objects with source, destination, and permanent properties:
source is the incoming request path pattern.
destination is the path you want to route to.
permanent true or false - if true will use the 308 status code which instructs clients/search engines to cache the redirect forever, if false will use the 307 status code which is temporary and is not cached. | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-0 |
Why does Next.js use 307 and 308? Traditionally a 302 was used for a temporary redirect, and a 301 for a permanent redirect, but many browsers changed the request method of the redirect to GET, regardless of the original method. For example, if the browser made a request to POST /v1/users which returned status code 302 with location /v2/users, the subsequent request might be GET /v2/users instead of the expected POST /v2/users. Next.js uses the 307 temporary redirect, and 308 permanent redirect status codes to explicitly preserve the request method used.
basePath: false or undefined - if false the basePath won't be included when matching, can be used for external redirects only.
locale: false or undefined - whether the locale should not be included when matching.
has is an array of has objects with the type, key and value properties. | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-1 |
has is an array of has objects with the type, key and value properties.
missing is an array of missing objects with the type, key and value properties.
Redirects are checked before the filesystem which includes pages and /public files.
Redirects are not applied to client-side routing (Link, router.push), unless Middleware is present and matches the path.
When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration:
{
source: '/old-blog/:path*',
destination: '/blog/:path*',
permanent: false
}
When /old-blog/post-1?hello=world is requested, the client will be redirected to /blog/post-1?hello=world.
Path Matching
Path matches are allowed, for example /old-blog/:slug will match /old-blog/hello-world (no nested paths): | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-2 |
next.config.js module.exports = {
async redirects() {
return [
{
source: '/old-blog/:slug',
destination: '/news/:slug', // Matched parameters can be used in the destination
permanent: true,
},
]
},
}
Wildcard Path Matching
To match a wildcard path you can use * after a parameter, for example /blog/:slug* will match /blog/a/b/c/d/hello-world:
next.config.js module.exports = {
async redirects() {
return [
{
source: '/blog/:slug*',
destination: '/news/:slug*', // Matched parameters can be used in the destination
permanent: true,
},
]
},
}
Regex Path Matching | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-3 |
},
]
},
}
Regex Path Matching
To match a regex path you can wrap the regex in parentheses after a parameter, for example /post/:slug(\\d{1,}) will match /post/123 but not /post/abc:
next.config.js module.exports = {
async redirects() {
return [
{
source: '/post/:slug(\\d{1,})',
destination: '/news/:slug', // Matched parameters can be used in the destination
permanent: false,
},
]
},
}
The following characters (, ), {, }, :, *, +, ? are used for regex path matching, so when used in the source as non-special values they must be escaped by adding \\ before them:
next.config.js module.exports = {
async redirects() {
return [
{ | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-4 |
async redirects() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
destination: '/en-us/:slug',
permanent: false,
},
]
},
}
Header, Cookie, and Query Matching
To only match a redirect when header, cookie, or query values also match the has field or don't match the missing field can be used. Both the source and all has items must match and all missing items must not match for the redirect to be applied.
has and missing items can have the following fields:
type: String - must be either header, cookie, host, or query.
key: String - the key from the selected type to match against. | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-5 |
key: String - the key from the selected type to match against.
value: String or undefined - the value to check for, if undefined any value will match. A regex like string can be used to capture a specific part of the value, e.g. if the value first-(?<paramName>.*) is used for first-second then second will be usable in the destination with :paramName.
next.config.js module.exports = {
async redirects() {
return [
// if the header `x-redirect-me` is present,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'header',
key: 'x-redirect-me',
},
],
permanent: false,
destination: '/another-page',
}, | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-6 |
],
permanent: false,
destination: '/another-page',
},
// if the header `x-dont-redirect` is present,
// this redirect will NOT be applied
{
source: '/:path((?!another-page$).*)',
missing: [
{
type: 'header',
key: 'x-do-not-redirect',
},
],
permanent: false,
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this redirect will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-7 |
// destination since value is provided and doesn't
// use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
permanent: false,
destination: '/another/:path*',
},
// if the header `x-authorized` is present and
// contains a matching value, this redirect will be applied
{
source: '/',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
permanent: false,
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`, | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-8 |
},
// if the host is `example.com`,
// this redirect will be applied
{
source: '/:path((?!another-page$).*)',
has: [
{
type: 'host',
value: 'example.com',
},
],
permanent: false,
destination: '/another-page',
},
]
},
}
Redirects with basePath support
When leveraging basePath support with redirects each source and destination is automatically prefixed with the basePath unless you add basePath: false to the redirect:
next.config.js module.exports = {
basePath: '/docs',
async redirects() {
return [
{
source: '/with-basePath', // automatically becomes /docs/with-basePath
destination: '/another', // automatically becomes /docs/another
permanent: false,
}, | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-9 |
permanent: false,
},
{
// does not add /docs since basePath: false is set
source: '/without-basePath',
destination: 'https://example.com',
basePath: false,
permanent: false,
},
]
},
}
Redirects with i18n support
When leveraging i18n support with redirects each source and destination is automatically prefixed to handle the configured locales unless you add locale: false to the redirect. If locale: false is used you must prefix the source and destination with a locale for it to be matched correctly.
next.config.js module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async redirects() {
return [
{
source: '/with-locale', // automatically handles all locales | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-10 |
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
permanent: false,
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
permanent: false,
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
destination: '/en/another',
locale: false,
permanent: false,
},
// it's possible to match all locales even when locale: false is set
{
source: '/:locale/page',
destination: '/en/newpage',
permanent: false,
locale: false,
}
{ | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-11 |
permanent: false,
locale: false,
}
{
// this gets converted to /(en|fr|de)/(.*) so will not match the top-level
// `/` or `/fr` routes like /:path* would
source: '/(.*)',
destination: '/another',
permanent: false,
},
]
},
}
In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the statusCode property instead of the permanent property, but not both. To to ensure IE11 compatibility, a Refresh header is automatically added for the 308 status code.
Other Redirects
Inside API Routes, you can use res.redirect().
Inside getStaticProps and getServerSideProps, you can redirect specific pages at request-time.
Version History | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-12 |
Version History
VersionChangesv13.3.0missing added.v10.2.0has added.v9.5.0redirects added. | https://nextjs.org/docs/app/api-reference/next-config-js/redirects | 4265e09b0ffb-13 |
compress
Next.js provides gzip compression to compress rendered content and static files. In general you will want to enable compression on a HTTP proxy like nginx, to offload load from the Node.js process.
To disable compression, open next.config.js and disable the compress config:
next.config.js module.exports = {
compress: false,
} | https://nextjs.org/docs/app/api-reference/next-config-js/compress | 5e7e5b9024d6-0 |
serverComponentsExternalPackagesDependencies used inside Server Components and Route Handlers will automatically be bundled by Next.js.
If a dependency is using Node.js specific features, you can choose to opt-out specific dependencies from the Server Components bundling and use native Node.js require.
next.config.js /** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponentsExternalPackages: ['@acme/ui'],
},
}
module.exports = nextConfig
Next.js includes a short list of popular packages that currently are working on compatibility and automatically opt-ed out:
@aws-sdk/client-s3
@aws-sdk/s3-presigned-post
@blockfrost/blockfrost-js
@jpg-store/lucid-cardano
@mikro-orm/core
@mikro-orm/knex
@prisma/client
@sentry/nextjs
@sentry/node
@swc/core
argon2 | https://nextjs.org/docs/app/api-reference/next-config-js/serverComponentsExternalPackages | 7f5d0c6408a3-0 |
@sentry/nextjs
@sentry/node
@swc/core
argon2
autoprefixer
aws-crt
bcrypt
better-sqlite3
canvas
cpu-features
cypress
eslint
express
firebase-admin
jest
jsdom
lodash
mdx-bundler
mongodb
mongoose
next-mdx-remote
next-seo
payload
pg
playwright
postcss
prettier
prisma
puppeteer
rimraf
sharp
shiki
sqlite3
tailwindcss
ts-node
typescript
vscode-oniguruma
webpack | https://nextjs.org/docs/app/api-reference/next-config-js/serverComponentsExternalPackages | 7f5d0c6408a3-1 |
output
During a build, Next.js will automatically trace each page and its dependencies to determine all of the files that are needed for deploying a production version of your application.
This feature helps reduce the size of deployments drastically. Previously, when deploying with Docker you would need to have all files from your package's dependencies installed to run next start. Starting with Next.js 12, you can leverage Output File Tracing in the .next/ directory to only include the necessary files.
Furthermore, this removes the need for the deprecated serverless target which can cause various issues and also creates unnecessary duplication.
How it Works
During next build, Next.js will use @vercel/nft to statically analyze import, require, and fs usage to determine all files that a page might load.
Next.js' production server is also traced for its needed files and output at .next/next-server.js.nft.json which can be leveraged in production. | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-0 |
To leverage the .nft.json files emitted to the .next output directory, you can read the list of files in each trace that are relative to the .nft.json file and then copy them to your deployment location.
Automatically Copying Traced Files
Next.js can automatically create a standalone folder that copies only the necessary files for a production deployment including select files in node_modules.
To leverage this automatic copying you can enable it in your next.config.js:
next.config.js module.exports = {
output: 'standalone',
}
This will create a folder at .next/standalone which can then be deployed on its own without installing node_modules. | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-1 |
Additionally, a minimal server.js file is also output which can be used instead of next start. This minimal server does not copy the public or .next/static folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the standalone/public and standalone/.next/static folders manually, after which server.js file will serve these automatically.
Good to know:
next.config.js is read during next build and serialized into the server.js output file. If the legacy serverRuntimeConfig or publicRuntimeConfig options are being used, the values will be specific to values at build time.
If your project uses Image Optimization with the default loader, you must install sharp as a dependency:
If your project needs alternative port or hostname for listening, you can define PORT and HOSTNAME environment variables, before running server.js. For example, PORT=3000 HOSTNAME=localhost node server.js.
Terminal npm i sharp
Terminal yarn add sharp
Terminal pnpm add sharp | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-2 |
Terminal npm i sharp
Terminal yarn add sharp
Terminal pnpm add sharp
Caveats
While tracing in monorepo setups, the project directory is used for tracing by default. For next build packages/web-app, packages/web-app would be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can set experimental.outputFileTracingRoot in your next.config.js.
packages/web-app/next.config.js module.exports = {
experimental: {
// this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'),
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-3 |
outputFileTracingRoot: path.join(__dirname, '../../'),
},
}
There are some cases in which Next.js might fail to include required files, or might incorrectly include unused files. In those cases, you can leverage experimental.outputFileTracingExcludes and experimental.outputFileTracingIncludes respectively in next.config.js. Each config accepts an object with minimatch globs for the key to match specific pages and a value of an array with globs relative to the project's root to either include or exclude in the trace.
next.config.js module.exports = {
experimental: {
outputFileTracingExcludes: {
'/api/hello': ['./un-necessary-folder/**/*'],
},
outputFileTracingIncludes: {
'/api/another': ['./necessary-folder/**/*'],
},
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-4 |
},
},
}
Currently, Next.js does not do anything with the emitted .nft.json files. The files must be read by your deployment platform, for example Vercel, to create a minimal deployment. In a future release, a new command is planned to utilize these .nft.json files.
Experimental turbotrace
Tracing dependencies can be slow because it requires very complex computations and analysis. We created turbotrace in Rust as a faster and smarter alternative to the JavaScript implementation.
To enable it, you can add the following configuration to your next.config.js:
next.config.js module.exports = {
experimental: {
turbotrace: {
// control the log level of the turbotrace, default is `error`
logLevel?:
| 'bug'
| 'fatal'
| 'error'
| 'warning'
| 'hint' | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-5 |
| 'error'
| 'warning'
| 'hint'
| 'note'
| 'suggestions'
| 'info',
// control if the log of turbotrace should contain the details of the analysis, default is `false`
logDetail?: boolean
// show all log messages without limit
// turbotrace only show 1 log message for each categories by default
logAll?: boolean
// control the context directory of the turbotrace
// files outside of the context directory will not be traced
// set the `experimental.outputFileTracingRoot` has the same effect
// if the `experimental.outputFileTracingRoot` and this option are both set, the `experimental.turbotrace.contextDirectory` will be used
contextDirectory?: string | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-6 |
contextDirectory?: string
// if there is `process.cwd()` expression in your code, you can set this option to tell `turbotrace` the value of `process.cwd()` while tracing.
// for example the require(process.cwd() + '/package.json') will be traced as require('/path/to/cwd/package.json')
processCwd?: string
// control the maximum memory usage of the `turbotrace`, in `MB`, default is `6000`.
memoryLimit?: number
},
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/output | 455ad70a2ba9-7 |
generateBuildId
Next.js uses a constant id generated at build time to identify which version of your application is being served. This can cause problems in multi-server deployments when next build is run on every server. In order to keep a consistent build id between builds you can provide your own build id.
Open next.config.js and add the generateBuildId function:
next.config.js module.exports = {
generateBuildId: async () => {
// You can, for example, get the latest git commit hash here
return 'my-build-id'
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/generateBuildId | 81123947bf4c-0 |
pageExtensions
By default, Next.js accepts files with the following extensions: .tsx, .ts, .jsx, .js. This can be modified to allow other extensions like markdown (.md, .mdx).next.config.js const withMDX = require('@next/mdx')()
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['ts', 'tsx', 'mdx'],
experimental: {
mdxRs: true,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-0 |