id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 46 101 |
|---|---|---|
a32e123ba449-4 | </body>
</html>
)
}
Good to know: <NavigationEvents> is wrapped in a Suspense boundary becauseuseSearchParams() causes client-side rendering up to the closest Suspense boundary during static rendering. Learn more.
VersionChangesv13.0.0useRouter from next/navigation introduced. | https://nextjs.org/docs/app/api-reference/functions/use-router |
69e77b6c1730-0 | useSearchParamsuseSearchParams is a Client Component hook that lets you read the current URL's query string.
useSearchParams returns a read-only version of the URLSearchParams interface.
app/dashboard/search-bar.tsx 'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-1 | URLSearchParams.get(): Returns the first value associated with the search parameter. For example:
URLsearchParams.get("a")/dashboard?a=1'1'/dashboard?a=''/dashboard?b=3null/dashboard?a=1&a=2'1' - use getAll() to get all values
URLSearchParams.has(): Returns a boolean value indicating if the given parameter exists. For ... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-2 | If an application includes the /pages directory, useSearchParams will return ReadonlyURLSearchParams | null. The null value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use getServerSideProps
Behavior
Static Rendering
If a route is statically rend... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-3 | const search = searchParams.get('search')
// This will not be logged on the server when using static rendering
console.log(search)
return <>Search: {search}</>
}
app/dashboard/page.tsx import { Suspense } from 'react'
import SearchBar from './search-bar'
// This component passed as a fallback to the Suspens... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-4 | <SearchBar />
</Suspense>
</nav>
<h1>Dashboard</h1>
</>
)
}
Dynamic Rendering
If a route is dynamically rendered, useSearchParams will be available on the server during the initial server render of the Client Component.
Good to know: Setting the dynamic route segment config option to force-dyn... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-5 | console.log(search)
return <>Search: {search}</>
}
app/dashboard/page.tsx import SearchBar from './search-bar'
export const dynamic = 'force-dynamic'
export default function Page() {
return (
<>
<nav>
<SearchBar />
</nav>
<h1>Dashboard</h1>
</>
)
}
Server Components
Pages
T... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-6 | Instead, use the Page searchParams prop or the useSearchParams hook in a Client Component, which is re-rendered on the client with the latest searchParams.
Examples
Updating searchParams
You can use useRouter or Link to set new searchParams. After a navigation is performed, the current page.js will receive an updated s... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
69e77b6c1730-7 | return params.toString()
},
[searchParams]
)
return (
<>
<p>Sort By</p>
{/* using useRouter */}
<button
onClick={() => {
// <pathname>?sort=asc
router.push(pathname + '?' + createQueryString('sort', 'asc'))
}}
>
ASC
</button>
... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
1d47e4b5cb53-0 | useSelectedLayoutSegmentuseSelectedLayoutSegment is a Client Component hook that lets you read the active route segment one level below the Layout it is called from.
It is useful for navigation UI, such as tabs inside a parent layout that change style depending on the active child segment.
app/example-client-component.... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
1d47e4b5cb53-1 | Parameters
const segment = useSelectedLayoutSegment()
useSelectedLayoutSegment does not take any parameters.
Returns
useSelectedLayoutSegment returns a string of the active segment or null if one doesn't exist.
For example, given the Layouts and URLs below, the returned segment would be:
LayoutVisited URLReturned Segm... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
1d47e4b5cb53-2 | import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selecte... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
1d47e4b5cb53-3 | app/blog/layout.tsx // Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getFeature... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
75b763a886ee-0 | 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 |
75b763a886ee-1 | 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 |
f93830721c3d-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 |
0f1453ba6c2e-0 | assetPrefix
Attention: Deploying to Vercel automatically configures a global CDN for your Next.js project.
You do not need to manually setup an Asset Prefix.
Good to know: Next.js 9.5+ added support for a customizable Base Path, which is better
suited for hosting your application on a sub-path like /docs.
We do not sug... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
0f1453ba6c2e-1 | }
Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the /_next/ path (.next/static/ folder). For example, with the above configuration, the following request for a JS chunk:
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
Would instead... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
0f1453ba6c2e-2 | The exact configuration for uploading your files to a given CDN will depend on your CDN of choice. The only folder you need to host on your CDN is the contents of .next/static/, which should be uploaded as _next/static/ as the above URL request indicates. Do not upload the rest of your .next/ folder, as you should not ... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
254abb17941d-0 | 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 |
254abb17941d-1 | </>
)
}
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 |
427c3679ff87-0 | 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 |
709f6ebe1430-0 | devIndicators
When you edit your code, and Next.js is compiling the application, a compilation indicator appears in the bottom right corner of the page.
Good to know: This indicator is only present in development mode and will not appear when building and running the app in production mode.
In some cases this indicator... | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators |
709f6ebe1430-1 | devIndicators: {
buildActivity: false,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators |
b629fa59edba-0 | distDir
You can specify a name to use for a custom build directory to use instead of .next.
Open next.config.js and add the distDir config:
next.config.js module.exports = {
distDir: 'build',
}
Now if you run next build Next.js will use build instead of the default .next folder.
distDir should not leave your project ... | https://nextjs.org/docs/app/api-reference/next-config-js/distDir |
9a46273eda24-0 | env
Since the release of Next.js 9.4 we now have a more intuitive and ergonomic experience for adding environment variables. Give it a try!
Examples
With env
Good to know: environment variables specified in this way will always be included in the JavaScript bundle, prefixing the environment variable name with NEXT_PUBL... | https://nextjs.org/docs/app/api-reference/next-config-js/env |
9a46273eda24-1 | }
export default Page
Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.
For example, the following line:
return <h1>The value of customKey is: {process.env.customKey}</h1>
Will end up being:
ret... | https://nextjs.org/docs/app/api-reference/next-config-js/env |
7f0b58dfe772-0 | 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 |
7dd190f95594-0 | exportPathMap (Deprecated)
This feature is exclusive to next export and currently deprecated in favor of getStaticPaths with pages or generateStaticParams with app.
Examples
Static Export
exportPathMap allows you to specify a mapping of request paths to page destinations, to be used during export. Paths defined in expo... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
7dd190f95594-1 | '/about': { page: '/about' },
'/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } },
'/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } },
'/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } },
}
},
}
Good to know: the query field in exportPa... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
7dd190f95594-2 | exportPathMap is an async function that receives 2 arguments: the first one is defaultPathMap, which is the default map used by Next.js. The second argument is an object with:
dev - true when exportPathMap is being called in development. false when running next export. In development exportPathMap is used to define rou... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
7dd190f95594-3 | page: String - the page inside the pages directory to render
query: Object - the query object passed to getInitialProps when prerendering. Defaults to {}
The exported pathname can also be a filename (for example, /readme.md), but you may need to set the Content-Type header to text/html when serving its content if it is... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
7dd190f95594-4 | Terminal next export -o outdir
Warning: Using exportPathMap is deprecated and is overridden by getStaticPaths inside pages. We don't recommend using them together. | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
0234f97df5cb-0 | 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 |
5354c07a81e7-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 |
79cb28fc1d06-0 | headers
Headers allow you to set custom HTTP headers on the response to an incoming request on a given path.
To set custom HTTP headers you can use the headers key in next.config.js:
next.config.js module.exports = {
async headers() {
return [
{
source: '/about',
headers: [
{
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-1 | headers is an array of response header objects, with key and value properties.
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 object... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-2 | return [
{
source: '/:path*',
headers: [
{
key: 'x-hello',
value: 'there',
},
],
},
{
source: '/hello',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-3 | },
{
key: 'x-slug-:slug', // Matched parameters can be used in the key
value: 'my other custom header value',
},
],
},
]
},
}
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... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-4 | value: 'my other custom header value',
},
],
},
]
},
}
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 headers() {
retur... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-5 | next.config.js module.exports = {
async headers() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
headers: [
{
key: 'x-header',
value: 'value',
},
],
},
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-6 | 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/headers |
79cb28fc1d06-7 | value: 'hello',
},
],
},
// if the header `x-no-header` is not present,
// the `x-another-header` header will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-no-header',
},
],
heade... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-8 | key: 'page',
// the page value will not be available in the
// header key/values since value is provided and
// doesn't use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-9 | {
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
// if the host is `example.com`,
// this... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-10 | ],
},
]
},
}
Headers with basePath support
When leveraging basePath support with headers each source is automatically prefixed with the basePath unless you add basePath: false to the header:
next.config.js module.exports = {
basePath: '/docs',
async headers() {
return [
{
source: '/w... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-11 | },
]
},
}
Headers with i18n support
When leveraging i18n support with headers each source is automatically prefixed to handle the configured locales unless you add locale: false to the header. If locale: false is used you must prefix the source with a locale for it to be matched correctly.
next.config.js module.e... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-12 | source: '/nl/with-locale-manual',
locale: false,
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
locale: false,
headers: [
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-13 | value: 'world',
},
],
},
]
},
}
Cache-Control
You can set the Cache-Control header in your Next.js API Routes by using the res.setHeader method:
pages/api/user.js export default function handler(req, res) {
res.setHeader('Cache-Control', 's-maxage=86400')
res.status(200).json({ name: '... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-14 | Options
X-DNS-Prefetch-Control
This header controls DNS prefetching, allowing browsers to proactively perform domain name resolution on external links, images, CSS, JavaScript, and more. This prefetching is performed in the background, so the DNS is more likely to be resolved by the time the referenced items are needed... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-15 | {
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
}
X-XSS-Protection
This header stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although this protection is not necessary when sites implement a strong Content-Security-Policy disabling t... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-16 | {
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
}
Permissions-Policy
This header allows you to control which features and APIs can be used in the browser. It was previously named Feature-Policy. You can view the full list of permission options here.
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), ... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-17 | {
key: 'X-Content-Type-Options',
value: 'nosniff'
}
Referrer-Policy
This header controls how much information the browser includes when navigating from the current website (origin) to another. You can read about the different options here.
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin'
}
Content-S... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
79cb28fc1d06-18 | // add Content Security Policy directives using a template string.
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self';
child-src example.com;
style-src 'self' example.com;
font-src 'self';
`
When a directive uses a keyword such as self, wrap it in single quotes ''.
In the header's value, ... | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
011a76187391-0 | 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 |
c34ad0c51921-0 | images
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure next.config.js with the following:
next.config.js module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
This loaderFile must point t... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-1 | Contentful
Fastly
Gumlet
ImageEngine
Imgix
Thumbor
Supabase
Akamai
// Docs: https://techdocs.akamai.com/ivm/reference/test-images-on-demand
export default function akamaiLoader({ src, width, quality }) {
return `https://example.com/${src}?imwidth=${width}`
}
Cloudinary
// Demo: https://res.cloudinary.com/demo/image... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-2 | export default function cloudflareLoader({ src, width, quality }) {
const params = [`width=${width}`, `quality=${quality || 75}`, 'format=auto']
return `https://example.com/cdn-cgi/image/${params.join(',')}/${src}`
}
Contentful
// Docs: https://www.contentful.com/developers/docs/references/images-api/
export defau... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-3 | export default function fastlyLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('auto', 'webp')
url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
}
Gumlet
// Docs: https://docs.guml... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-4 | return url.href
}
ImageEngine
// Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives
export default function imageengineLoader({ src, width, quality }) {
const compression = 100 - (quality || 50)
const params = [`w_${width}`, `cmpr_${compression}`)]
return `https://example.com${src}?im... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-5 | params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
params.set('q', (quality || 50).toString())
return url.href
}
Thumbor
// Docs: https://thumbor.readthedocs.io/en/latest/
export default function thumborLoader({ src, width, quality }) {
const params = [`${width}x... | https://nextjs.org/docs/app/api-reference/next-config-js/images |
c34ad0c51921-6 | url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
} | https://nextjs.org/docs/app/api-reference/next-config-js/images |
6d334191be82-0 | 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 |
6d334191be82-1 | 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 |
ac33f8f65260-0 | mdxRsFor use with @next/mdx. Compile MDX files using the new Rust compiler.
next.config.js const withMDX = require('@next/mdx')()
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['ts', 'tsx', 'mdx'],
experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig) | https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs |
809104ae5dba-0 | onDemandEntries
Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development.
To change the defaults, open next.config.js and add the onDemandEntries config:
next.config.js module.exports = {
onDemandEntries: {
// period (in ms) where the se... | https://nextjs.org/docs/app/api-reference/next-config-js/onDemandEntries |
8b54fc9d6ab3-0 | 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 |
8b54fc9d6ab3-1 | 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 |
8b54fc9d6ab3-2 | 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 |
8b54fc9d6ab3-3 | 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 |
8b54fc9d6ab3-4 | 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 |
8b54fc9d6ab3-5 | },
},
}
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 |
8b54fc9d6ab3-6 | | '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 |
8b54fc9d6ab3-7 | 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 |
cf657690c5a2-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 |
cf657690c5a2-1 | experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig)For custom advanced configuration of Next.js, you can create a next.config.js or next.config.mjs file in the root of your project directory (next to package.json).next.config.js is a regular Node.js module, not a JSON file. It gets used by th... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
cf657690c5a2-2 | */
const nextConfig = {
/* config options here */
}
export default nextConfigYou can also use a function:next.config.mjs module.exports = (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}Since Next.js 12.... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
cf657690c5a2-3 | /* config options here */
}
return nextConfig
}phase is the current context in which the configuration is loaded. You can see the available phases. Phases can be imported from next/constants: const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = (phase, { defaultConfig }) => {
if (phas... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
cf657690c5a2-4 | return {
/* config options for all phases except development here */
}
}The commented lines are the place where you can put the configs allowed by next.config.js, which are defined in this file.However, none of the configs are required, and it's not necessary to understand what each config does. Instead, search f... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
cb9b6476e3d9-0 | poweredByHeader
By default Next.js will add the x-powered-by header. To opt-out of it, open next.config.js and disable the poweredByHeader config:
next.config.js module.exports = {
poweredByHeader: false,
} | https://nextjs.org/docs/app/api-reference/next-config-js/poweredByHeader |
619ac6f19618-0 | productionBrowserSourceMaps
Source Maps are enabled by default during development. During production builds, they are disabled to prevent you leaking your source on the client, unless you specifically opt-in with the configuration flag.
Next.js provides a configuration flag you can use to enable browser source map gene... | https://nextjs.org/docs/app/api-reference/next-config-js/productionBrowserSourceMaps |
7d62f05b7e19-0 | reactStrictMode
Good to know: Since Next.js 13.4, Strict Mode is true by default with app router, so the above configuration is only necessary for pages. You can still disable Strict Mode by setting reactStrictMode: false.
Suggested: We strongly suggest you enable Strict Mode in your Next.js application to better prepa... | https://nextjs.org/docs/app/api-reference/next-config-js/reactStrictMode |
7d62f05b7e19-1 | next.config.js module.exports = {
reactStrictMode: true,
}
If you or your team are not ready to use Strict Mode in your entire application, that's OK! You can incrementally migrate on a page-by-page basis using <React.StrictMode>. | https://nextjs.org/docs/app/api-reference/next-config-js/reactStrictMode |
b6efd1cc8e7e-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 |
b6efd1cc8e7e-1 | 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 |
b6efd1cc8e7e-2 | 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 |
b6efd1cc8e7e-3 | 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 |
b6efd1cc8e7e-4 | },
]
},
}
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 |
b6efd1cc8e7e-5 | 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 |
b6efd1cc8e7e-6 | 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 |
b6efd1cc8e7e-7 | ],
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 |
b6efd1cc8e7e-8 | // 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 |
b6efd1cc8e7e-9 | },
// 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 |
b6efd1cc8e7e-10 | 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 |
b6efd1cc8e7e-11 | {
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 |
b6efd1cc8e7e-12 | 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 |
b6efd1cc8e7e-13 | 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 |
467e2fc53597-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 |
467e2fc53597-1 | 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 |
467e2fc53597-2 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.