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() { const searchParams = useSearchParams() const search = searchParams.get('search') // URL -> `/dashboard?search=my-project` // `search` -> 'my-project' return <>Search: {search}</> } Parameters const searchParams = useSearchParams() useSearchParams does not take any parameters. Returns useSearchParams returns a read-only version of the URLSearchParams interface, which includes utility methods for reading the URL's query string: URLSearchParams.get(): Returns the first value associated with the search parameter. For example:
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 example: URLsearchParams.has("a")/dashboard?a=1true/dashboard?b=3false Learn more about other read-only methods of URLSearchParams, including the getAll(), keys(), values(), entries(), forEach(), and toString(). Good to know: useSearchParams is a Client Component hook and is not supported in Server Components to prevent stale values during partial rendering.
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 rendered, calling useSearchParams() will cause the tree up to the closest Suspense boundary to be client-side rendered. This allows a part of the page to be statically rendered while the dynamic part that uses searchParams is client-side rendered. You can reduce the portion of the route that is client-side rendered by wrapping the component that uses useSearchParams in a Suspense boundary. For example: app/dashboard/search-bar.tsx 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams = useSearchParams() const search = searchParams.get('search')
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 Suspense boundary // will be rendered in place of the search bar in the initial HTML. // When the value is available during React hydration the fallback // will be replaced with the `<SearchBar>` component. function SearchBarFallback() { return <>placeholder</> } export default function Page() { return ( <> <nav> <Suspense fallback={<SearchBarFallback />}> <SearchBar /> </Suspense> </nav>
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-dynamic can be used to force dynamic rendering. For example: app/dashboard/search-bar.tsx 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams = useSearchParams() const search = searchParams.get('search') // This will be logged on the server during the initial render // and on the client on subsequent navigations. console.log(search) return <>Search: {search}</> }
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 To access search params in Pages (Server Components), use the searchParams prop. Layouts Unlike Pages, Layouts (Server Components) do not receive the searchParams prop. This is because a shared layout is not re-rendered during navigation which could lead to stale searchParams between navigations. View detailed explanation.
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 searchParams prop. app/example-client-component.tsx export default function ExampleClientComponent() { const router = useRouter() const pathname = usePathname() const searchParams = useSearchParams()! // Get a new searchParams string by merging the current // searchParams with a provided key/value pair const createQueryString = useCallback( (name: string, value: string) => { const params = new URLSearchParams(searchParams) params.set(name, value) return params.toString() }, [searchParams] )
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> {/* using <Link> */} <Link href={ // <pathname>?sort=desc pathname + '?' + createQueryString('sort', 'desc') } > DESC </Link> </> ) } Version History VersionChangesv13.0.0useSearchParams introduced.
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.tsx 'use client' import { useSelectedLayoutSegment } from 'next/navigation' export default function ExampleClientComponent() { const segment = useSelectedLayoutSegment() return <p>Active segment: {segment}</p> } Good to know: Since useSelectedLayoutSegment is a Client Component hook, and Layouts are Server Components by default, useSelectedLayoutSegment is usually called via a Client Component that is imported into a Layout. useSelectedLayoutSegment only returns the segment one level down. To return all active segments, see useSelectedLayoutSegments Parameters const segment = useSelectedLayoutSegment()
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 Segmentapp/layout.js/nullapp/layout.js/dashboard'dashboard'app/dashboard/layout.js/dashboardnullapp/dashboard/layout.js/dashboard/settings'settings'app/dashboard/layout.js/dashboard/analytics'analytics'app/dashboard/layout.js/dashboard/analytics/monthly'analytics' Examples Creating an active link component You can use useSelectedLayoutSegment to create an active link component that changes style depending on the active segment. For example, a featured posts list in the sidebar of a blog: app/blog/blog-nav-link.tsx 'use client' import Link from 'next/link' import { useSelectedLayoutSegment } from 'next/navigation'
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 selected layout segment const segment = useSelectedLayoutSegment() const isActive = slug === segment return ( <Link href={`/blog/${slug}`} // Change style depending on whether the link is active style={{ fontWeight: isActive ? 'bold' : 'normal' }} > {children} </Link> ) } app/blog/layout.tsx // Import the Client Component into a parent Layout (Server Component)
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 getFeaturedPosts() return ( <div> {featuredPosts.map((post) => ( <div key={post.id}> <BlogNavLink slug={post.slug}>{post.title}</BlogNavLink> </div> ))} <div>{children}</div> </div> ) } Version History VersionChangesv13.0.0useSelectedLayoutSegment introduced.
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' 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
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 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
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 adopt app.
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 suggest you use a custom Asset Prefix for this use case. To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on. Open next.config.js and add the assetPrefix config: next.config.js const isProd = process.env.NODE_ENV === 'production' module.exports = { // Use the CDN in production and localhost for development. assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined, }
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 become: https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
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 expose your server code and other configuration to the public. While assetPrefix covers requests to _next/static, it does not influence the following paths: Files in the public folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself
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.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
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 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
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 = { compress: false, }
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 can be misplaced on your page, for example, when conflicting with a chat launcher. To change its position, open next.config.js and set the buildActivityPosition in the devIndicators object to bottom-right (default), bottom-left, top-right or top-left:next.config.js module.exports = { devIndicators: { buildActivityPosition: 'bottom-right', }, }In some cases this indicator might not be useful for you. To remove it, open next.config.js and disable the buildActivity config in devIndicators object:next.config.js module.exports = { devIndicators: { buildActivity: false,
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 directory. For example, ../build is an invalid directory.
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_PUBLIC_ only has an effect when specifying them through the environment or .env files. To add environment variables to the JavaScript bundle, open next.config.js and add the env config: next.config.js module.exports = { env: { customKey: 'my-value', }, } Now you can access process.env.customKey in your code. For example: function Page() { return <h1>The value of customKey is: {process.env.customKey}</h1> } export default Page
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: return <h1>The value of customKey is: {'my-value'}</h1>
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 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
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 exportPathMap will also be available when using next dev. Let's start with an example, to create a custom exportPathMap for an app with the following pages: pages/index.js pages/about.js pages/post.js Open next.config.js and add the following exportPathMap config: next.config.js module.exports = { exportPathMap: async function ( defaultPathMap, { dev, dir, outDir, distDir, buildId } ) { return { '/': { page: '/' }, '/about': { page: '/about' },
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 exportPathMap cannot be used with automatically statically optimized pages or getStaticProps pages as they are rendered to HTML files at build-time and additional query information cannot be provided during next export. The pages will then be exported as HTML files, for example, /about will become /about.html.
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 routes. dir - Absolute path to the project directory outDir - Absolute path to the out/ directory (configurable with -o). When dev is true the value of outDir will be null. distDir - Absolute path to the .next/ directory (configurable with the distDir config) buildId - The generated build id The returned object is a map of pages where the key is the pathname and the value is an object that accepts the following fields: page: String - the page inside the pages directory to render
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 different than .html. Adding a trailing slash It is possible to configure Next.js to export pages as index.html files and require trailing slashes, /about becomes /about/index.html and is routable via /about/. This was the default behavior prior to Next.js 9. To switch back and add a trailing slash, open next.config.js and enable the trailingSlash config: next.config.js module.exports = { trailingSlash: true, } Customizing the output directory next export will use out as the default output directory, you can customize this using the -o argument, like so:
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.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
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: [ { key: 'x-custom-header', value: 'my custom header value', }, { key: 'x-another-custom-header', value: 'my other custom header value', }, ], }, ] }, } headers is an async function that expects an array to be returned holding objects with source and headers properties: source is the incoming request path pattern. headers is an array of response header objects, with key and value properties.
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 objects with the type, key and value properties. missing is an array of missing objects with the type, key and value properties. Headers are checked before the filesystem which includes pages and /public files. Header Overriding Behavior If two headers match the same path and set the same header key, the last header key will override the first. Using the below headers, the path /hello will result in the header x-hello being world due to the last header value set being world. next.config.js module.exports = { async headers() { return [ { source: '/:path*',
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', }, ], }, ] }, } Path Matching Path matches are allowed, for example /blog/:slug will match /blog/hello-world (no nested paths): next.config.js module.exports = { async headers() { return [ { source: '/blog/:slug', headers: [ { key: 'x-slug', value: ':slug', // Matched parameters can be used in the value }, {
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/hello-world: next.config.js module.exports = { async headers() { return [ { source: '/blog/:slug*', headers: [ { key: 'x-slug', value: ':slug*', // Matched parameters can be used in the value }, { key: 'x-slug-:slug*', // Matched parameters can be used in the key value: 'my other custom header value', },
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() { return [ { source: '/blog/:post(\\d{1,})', headers: [ { key: 'x-post', value: ':post', }, ], }, ] }, } 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:
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', }, ], }, ] }, } Header, Cookie, and Query Matching To only apply a header 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 header 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/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 the destination with :paramName. next.config.js module.exports = { async headers() { return [ // if the header `x-add-header` is present, // the `x-another-header` header will be applied { source: '/:path*', has: [ { type: 'header', key: 'x-add-header', }, ], headers: [ { key: 'x-another-header', value: 'hello', }, ],
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', }, ], headers: [ { key: 'x-another-header', value: 'hello', }, ], }, // if the source, query, and cookie are matched, // the `x-authorized` header will be applied { source: '/specific/:path*', has: [ { type: 'query', key: 'page', // the page value will not be available in the
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', value: 'true', }, ], headers: [ { key: 'x-authorized', value: ':authorized', }, ], }, // if the header `x-authorized` is present and // contains a matching value, the `x-another-header` will be applied { source: '/:path*', has: [ { type: 'header', key: 'x-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 header will be applied { source: '/:path*', has: [ { type: 'host', value: 'example.com', }, ], headers: [ { key: 'x-another-header', value: ':authorized', }, ], }, ] }, } Headers with basePath support
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: '/with-basePath', // becomes /docs/with-basePath headers: [ { key: 'x-hello', value: 'world', }, ], }, { source: '/without-basePath', // is not modified since basePath: false is set headers: [ { key: 'x-hello', value: 'world', }, ], basePath: false, }, ] }, } Headers with i18n support
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.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en', }, async headers() { return [ { source: '/with-locale', // automatically handles all locales headers: [ { key: 'x-hello', value: 'world', }, ], }, { // does not handle locales automatically since locale: false is set source: '/nl/with-locale-manual',
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: [ { key: 'x-hello', value: 'world', }, ], }, { // this gets converted to /(en|fr|de)/(.*) so will not match the top-level // `/` or `/fr` routes like /:path* would source: '/(.*)', headers: [ { key: 'x-hello', value: 'world', }, ], },
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: 'John Doe' }) } You cannot set Cache-Control headers in next.config.js file as these will be overwritten in production to ensure that API Routes and static assets are cached effectively. If you need to revalidate the cache of a page that has been statically generated, you can do so by setting the revalidate prop in the page's getStaticProps function. Options X-DNS-Prefetch-Control
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. This reduces latency when the user clicks a link. { key: 'X-DNS-Prefetch-Control', value: 'on' } Strict-Transport-Security This header informs browsers it should only be accessed using HTTPS, instead of using HTTP. Using the configuration below, all present and future subdomains will use HTTPS for a max-age of 2 years. This blocks access to pages or subdomains that can only be served over HTTP. If you're deploying to Vercel, this header is not necessary as it's automatically added to all deployments unless you declare headers in your next.config.js. {
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 the use of inline JavaScript ('unsafe-inline'), it can still provide protection for older web browsers that don't support CSP. { key: 'X-XSS-Protection', value: '1; mode=block' } X-Frame-Options This header indicates whether the site should be allowed to be displayed within an iframe. This can prevent against clickjacking attacks. This header has been superseded by CSP's frame-ancestors option, which has better support in modern browsers. { key: 'X-Frame-Options',
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=(), geolocation=(), browsing-topics=()' } X-Content-Type-Options This header prevents the browser from attempting to guess the type of content if the Content-Type header is not explicitly set. This can prevent XSS exploits for websites that allow users to upload and share files. For example, a user trying to download an image, but having it treated as a different Content-Type like an executable, which could be malicious. This header also applies to downloading browser extensions. The only valid value for this header is nosniff. {
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-Security-Policy This header helps prevent cross-site scripting (XSS), clickjacking and other code injection attacks. Content Security Policy (CSP) can specify allowed origins for content including scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more. You can read about the many different CSP options here. You can add Content Security Policy directives using a template string. // Before defining your Security Headers // add Content Security Policy directives using a template string.
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, replace the new line with a space. { key: 'Content-Security-Policy', value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim() } Version History VersionChangesv13.3.0missing added.v10.2.0has added.v9.5.0Headers added.
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 = { httpAgentOptions: { keepAlive: false, }, }
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 to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example: export default function myImageLoader({ src, width, quality }) { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } Alternatively, you can use the loader prop to pass the function to each instance of next/image. Example Loader Configuration Akamai Cloudinary Cloudflare Contentful Fastly Gumlet ImageEngine Imgix Thumbor
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/upload/w_300,c_limit,q_auto/turtles.jpg export default function cloudinaryLoader({ src, width, quality }) { const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`] return `https://example.com/${params.join(',')}${src}` } Cloudflare // Docs: https://developers.cloudflare.com/images/url-format export default function cloudflareLoader({ src, width, quality }) {
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 default function contentfulLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('fm', 'webp') url.searchParams.set('w', width.toString()) url.searchParams.set('q', (quality || 75).toString()) return url.href } Fastly // Docs: https://developer.fastly.com/reference/io/ export default function fastlyLoader({ src, width, quality }) {
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.gumlet.com/reference/image-transform-size export default function gumletLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('format', 'auto') url.searchParams.set('w', width.toString()) url.searchParams.set('q', (quality || 75).toString()) return url.href } ImageEngine
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}?imgeng=/${params.join('/')` } Imgix // Demo: https://static.imgix.net/daisy.png?format=auto&fit=max&w=300 export default function imgixLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) const params = url.searchParams params.set('auto', params.getAll('auto').join(',') || 'format') params.set('fit', params.get('fit') || 'max')
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}x0`, `filters:quality(${quality || 75})`] return `https://example.com${params.join('/')}${src}` } Supabase // Docs: https://supabase.com/docs/guides/storage/image-transformations#nextjs-loader export default function supabaseLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('width', width.toString())
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: 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
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 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
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 server will keep pages in the buffer maxInactiveAge: 25 * 1000, // number of pages that should be kept simultaneously without being disposed pagesBufferLength: 2, }, }
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 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
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 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
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 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
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 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
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.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
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 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
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 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
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?: 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
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', 'tsx', 'mdx'], experimental: { mdxRs: true, }, }
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 the Next.js server and build phases, and it's not included in the browser build.Take a look at the following next.config.js example:next.config.js /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } module.exports = nextConfigIf you need ECMAScript modules, you can use next.config.mjs:next.config.mjs /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */
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.1.0, you can use an async function:next.config.js module.exports = async (phase, { defaultConfig }) => { /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } return nextConfig
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 (phase === PHASE_DEVELOPMENT_SERVER) { return { /* development only config options here */ } } return { /* config options for all phases except development here */ }
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 for the features you need to enable or modify in this section and they will show you what to do. Avoid using new JavaScript features not available in your target Node.js version. next.config.js will not be parsed by Webpack, Babel or TypeScript.
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 generation during the production build: next.config.js module.exports = { productionBrowserSourceMaps: true, } When the productionBrowserSourceMaps option is enabled, the source maps will be output in the same directory as the JavaScript files. Next.js will automatically serve these files when requested. Adding source maps can increase next build time Increases memory usage during next build
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 prepare your application for the future of React. React's Strict Mode is a development mode only feature for highlighting potential problems in an application. It helps to identify unsafe lifecycles, legacy API usage, and a number of other features. The Next.js runtime is Strict Mode-compliant. To opt-in to Strict Mode, configure the following option in your next.config.js: next.config.js module.exports = { reactStrictMode: true, }
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, }, ] }, } 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
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 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
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 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
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 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
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,})', 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
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, 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
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 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
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-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
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: '/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
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', }, ] }, } 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
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 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
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', 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
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 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
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 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
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. 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
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: [{ 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