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... | 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> ... | 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 Fr... | 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" />
<... | 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://googl... | 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 exp... | 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 ... | 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" cont... | 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: {
... | 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"
med... | 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:u... | 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'],
}
<hea... | 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 suppo... | 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="style... | 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 r... | 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 pag... | 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 { Metadat... | 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 {... | 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 { revalida... | 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: Next... | 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) => {
consol... | 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 pa... | 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 "pr... | 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)
... | 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.
Sen... | 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 yo... | 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... | 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... | 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... | 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... | 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 cook... | 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 Rout... | 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'
impor... | 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'
... | 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
useSelectedLayoutSegme... | 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 t... | 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: 'exper... | 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 ... | 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'... | 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 = {
httpAgentOpt... | 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... | 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.... | 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:... | 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 hav... | 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... | 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 specifyi... | 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... | 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... | 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)/some... | 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 ... | 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',
... | 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
// co... | 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... | 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... | 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 {
... | 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... | 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
},
{
// d... | 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 /... | 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.expor... | 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 yo... | 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 E... | 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 publi... | 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 b... | 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: ... | 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 und... | 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'... | 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 ad... | 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,
... | 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... | 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 Middlew... | 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 pa... | 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,})',
destina... | 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, c... | 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 ... | 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-redirec... | 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: ... | 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',
},
... | 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 ... | 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',
destinati... | 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 ... | 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 = {
... | 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 /... | 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... | 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 fi... | 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 necessa... | 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 fo... | 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 out... | 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.con... | 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 ... | 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 ... | 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?: str... | 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... | 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', 't... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.