first commit
Some checks failed
Test examples / Test Examples (20) (push) Has been cancelled
Test examples / Test Examples (22) (push) Has been cancelled
Lock Threads / action (push) Has been cancelled
Trigger Release / start (push) Has been cancelled
Stale issue handler / stale (push) Has been cancelled
Update Font Data / create-pull-request (push) Has been cancelled
build-and-deploy / deploy-target (push) Has been cancelled
build-and-deploy / build (push) Has been cancelled
build-and-deploy / stable - aarch64-unknown-linux-musl - node@16 (push) Has been cancelled
build-and-deploy / stable - x86_64-unknown-linux-musl - node@16 (push) Has been cancelled
build-and-deploy / stable - aarch64-unknown-linux-gnu - node@16 (push) Has been cancelled
build-and-deploy / stable - x86_64-unknown-linux-gnu - node@16 (push) Has been cancelled
build-and-deploy / stable - aarch64-pc-windows-msvc - node@16 (push) Has been cancelled
build-and-deploy / stable - x86_64-pc-windows-msvc - node@16 (push) Has been cancelled
build-and-deploy / stable - aarch64-apple-darwin - node@16 (push) Has been cancelled
build-and-deploy / stable - x86_64-apple-darwin - node@16 (push) Has been cancelled
build-and-deploy / build-wasm (nodejs) (push) Has been cancelled
build-and-deploy / build-wasm (web) (push) Has been cancelled
build-and-deploy / Deploy preview tarball (push) Has been cancelled
build-and-deploy / Potentially publish release (push) Has been cancelled
build-and-deploy / publish-turbopack-npm-packages (push) Has been cancelled
build-and-deploy / Deploy examples (push) Has been cancelled
build-and-deploy / thank you, build (push) Has been cancelled
build-and-deploy / Upload Turbopack Bytesize metrics to Datadog (push) Has been cancelled
Rspack Next.js development integration tests / Rspack integration tests (push) Has been cancelled
Rspack Next.js production integration tests / Rspack integration tests (push) Has been cancelled
Turbopack Next.js development integration tests / Next.js integration tests (push) Has been cancelled
Turbopack Next.js production integration tests / Next.js integration tests (push) Has been cancelled
Update Rspack test manifest / Update and upload Rspack development test manifest (push) Has been cancelled
Update Rspack test manifest / Update and upload Rspack production test manifest (push) Has been cancelled
Upload bundler test manifests to areweturboyet.com / Upload test results (push) Has been cancelled
Update React / create-pull-request (push) Has been cancelled
test-e2e-project-reset-cron / reset-test-project (push) Has been cancelled
Notify about the top 15 issues/PRs/feature requests (most reacted) in the last 90 days / run (push) Has been cancelled

This commit is contained in:
Arian Tron
2026-03-10 19:37:31 +03:30
commit 61f56f997c
27684 changed files with 2784175 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
---
title: 404.js Cannot Have getInitialProps
description: This document provides an understanding of the "404.js Cannot Have getInitialProps" error in Next.js and offers solutions to fix it.
---
## Why This Error Occurred
The "404.js Cannot Have `getInitialProps`" error usually occurs when either `getInitialProps` or `getServerSideProps` is used in your `404.js` page. The `404.js` page in Next.js is designed to be static to ensure consistent performance.
## Possible Ways to Fix It
Adding `getInitialProps` or `getServerSideProps` to your `404.js` page will cause it to be rendered on the server-side.
To fix this error, you should remove `getInitialProps` from your `404.js` page. Additionally, ensure that no Higher-Order Components (HOCs) used in the `404.js` page are attaching `getInitialProps`.
If your `404.js` page requires data fetching, we recommend incrementally adopting the App Router and the [`not-found`](/docs/app/api-reference/file-conventions/not-found) file, which does support fetching data before displaying the 404 page.
## Useful Links
- [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) - Learn more about how Next.js automatically optimizes your pages for better performance.
- [`not-found`](/docs/app/api-reference/file-conventions/not-found)

View File

@@ -0,0 +1,32 @@
---
title: Addressing "API Routes Response Size Limited to 4MB" Error in Next.js
description: This document explains the "API Routes Response Size Limited to 4MB" error in Next.js and guides developers on how to modify response size limits.
---
## Why This Error Occurred
The "API Routes Response Size Limited to 4MB" error arises when your API Route is trying to send a response larger than the allowed size of `4MB`. API Routes in Next.js are designed to deliver quick responses and are not built to support the transmission of large amounts of data.
## Possible Ways to Fix It
If you are not utilizing Next.js in a serverless environment, and you're fully aware of the performance implications, you can disable this limit in your API Route. Here is how you can set `responseLimit` to `false`:
```js filename="pages/api/example.js"
export const config = {
api: {
responseLimit: false,
},
}
```
Alternatively, `responseLimit` can also accept a numeric value (in bytes) or any string format supported by the `bytes` module. This can be a value like `1000`, `'500kb'`, or `'3mb'`. This value will set the maximum response size before a warning is displayed. For example, to set the limit to 8MB:
```js filename="pages/api/example.js"
export const config = {
api: {
responseLimit: '8mb',
},
}
```
> **Note**: Increasing the response limit can have significant impacts on performance and should only be done after careful consideration.

View File

@@ -0,0 +1,23 @@
---
title: Understanding "API Routes in Static Export" Warning in Next.js
description: This document explains the "API Routes in Static Export" warning in Next.js and offers steps to resolve it.
---
## Why This Warning Occurred
The "API Routes in Static Export" warning is typically raised when an `exportPathMap` path is matched to an API route while trying to statically export a Next.js application via the `next export` command. This command disables API routes as it is designed for a static-only setup.
Running `next export` is not necessary to make your application static. Pages in your application that do not have server-side data dependencies will be automatically statically optimized when you run `next build`. This includes pages powered by `getStaticProps`.
## Possible Ways to Fix It
To resolve this issue, you have two main options:
1. Use the `next build` command instead of `next export` if you're deploying your application on platforms that don't require `next export`. For example, [Vercel](https://vercel.com) is a popular hosting platform for Next.js applications that supports this feature.
2. If you still need to use `next export`, make sure to remove any paths that use API routes from your `exportPathMap` in your `next.config.js` file.
3. Consider [incrementally adopting the App Router](/docs/app/guides/migrating/app-router-migration), which supports [Route Handlers](/docs/app/api-reference/file-conventions/route). These "API Routes" can be used to create endpoints that can be statically exported in your application.
## Useful Links
- [Static HTML export](/docs/pages/guides/static-exports) - Learn more about how you can create a static HTML export of your Next.js application.
- [Route Handlers](/docs/app/api-reference/file-conventions/route) - Learn more about how you can use Route Handlers to create endpoints that can be statically exported in your application.

View File

@@ -0,0 +1,56 @@
---
title: Addressing "App Container Deprecated" Error in Next.js
description: This document guides developers on how to resolve the "App Container Deprecated" error in Next.js by updating their custom App component.
---
## Why This Error Occurred
The "App Container Deprecated" error usually occurs when you are using the `<Container>` component in your custom `<App>` (`pages/_app.js`). Prior to version `9.0.4` of Next.js, the `<Container>` component was used to handle scrolling to hashes.
From version `9.0.4` onwards, this functionality was moved up the component tree, rendering the `<Container>` component unnecessary in your custom `<App>`.
## Possible Ways to Fix It
To resolve this issue, you need to remove the `<Container>` component from your custom `<App>` (`pages/_app.js`).
**Before**
```jsx filename="pages/_app.js"
import React from 'react'
import App, { Container } from 'next/app'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} />
</Container>
)
}
}
export default MyApp
```
**After**
```jsx filename="pages/_app.js"
import React from 'react'
import App from 'next/app'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
```
After making this change, your custom `<App>` should work as expected without the `<Container>` component.
## Useful Links
- [Custom App](/docs/pages/building-your-application/routing/custom-app)

View File

@@ -0,0 +1,45 @@
---
title: Handling "Dynamic href is not Supported in the App Router" Error in Next.js
description: This document describes the dynamic href is not supported in the App Router error in Next.js and provides a solution to fix it.
---
## Why This Error Occurred
The "Dynamic `href` is not supported in the App Router" error happens when you try to use a dynamic `href` with `next/link` in the `app` directory.
The new client-side router in Next.js does not use a mapping of dynamic routes to URLs, but rather it leverages the URL directly. This means it doesn't support dynamic `href` use.
## Possible Ways to Fix It
You need to replace the dynamic `href` with a direct path in the `next/link` component. Here's a before and after comparison of what your code should look like:
**Before**
```jsx
<Link
href={{
pathname: '/route/[slug]',
query: { slug: '1' },
}}
>
link
</Link>
```
Or
```jsx
<Link href="/route/[slug]?slug=1">link</Link>
```
**After**
```jsx
<Link href="/route/1">link</Link>
```
In the revised code, the dynamic part of the `href` (`[slug]`) is replaced directly with the actual value (`1`), which simplifies the `href` and makes it a direct path.
## Useful Links
- [`next/link` documentation](/docs/app/api-reference/components/link#href-required) - Learn more about the usage of `next/link` in Next.js.

View File

@@ -0,0 +1,23 @@
---
title: Resolving "app/ Static to Dynamic Error" in Next.js
description: This document explains the "app/ Static to Dynamic Error" in Next.js and provides potential solutions to resolve it.
---
## Why This Error Occurred
The "`app/` Static to Dynamic Error" happens when one of your routes in the `app/` directory is initially generated statically at build time, but during runtime it attempts to use dynamic server values (such as `cookies` or `headers`) either for a fallback path or while a path is being revalidated.
Currently, Next.js does not support switching between static and dynamic types during runtime, so the system throws an error.
## Possible Ways to Fix It
To resolve this issue, you have two main options:
1. Prevent the conditional use of dynamic server values that may cause the static/dynamic mode of the page to differ between build time and runtime. This ensures consistency in the rendering mode of your page.
2. Leverage the `dynamic` export to control the handling of your page. If you want to ensure your page is always handled statically, regardless of the usage of dynamic server values, you can use `export const dynamic = 'force-static'`. Conversely, if you prefer your page to always be dynamic, you can use `export const dynamic = 'force-dynamic'`, and your page won't attempt to be statically generated.
## Useful Links
- [Prerendering and Dynamic Rendering](/docs/app/getting-started/caching#how-rendering-works) - Learn more about the differences between prerendering and dynamic rendering in Next.js.
- [Request-time APIs](/docs/app/glossary#request-time-apis) - Understand more about the usage of dynamic server functions in your Next.js application.

View File

@@ -0,0 +1,17 @@
---
title: Resolving "Babel and `next/font` Conflict" in Next.js
description: This document explains the "Babel and `next/font` Conflict" in Next.js and provides a solution to resolve this issue.
---
## Why This Error Occurred
The "Babel and `next/font` Conflict" error arises when you attempt to use `next/font` in conjunction with a custom Babel configuration in your Next.js application. When you have a custom Babel config, you opt out of the Next.js Compiler, which is a requirement for using `next/font`.
## Possible Ways to Fix It
To address this issue, you should remove your custom Babel configuration (e.g. `.babelrc`) and instead make use of the Next.js Compiler. This ensures compatibility between your Babel configuration and `next/font`.
## Useful Links
- [Next.js Compiler](/docs/architecture/nextjs-compiler) - Learn more about the Next.js Compiler and how it benefits your application.
- [Customizing Babel Config](/docs/pages/guides/babel) - Understand more about how to customize your Babel configuration in a Next.js application, and the implications of doing so.

287
errors/blocking-route.mdx Normal file
View File

@@ -0,0 +1,287 @@
---
title: Uncached data was accessed outside of `<Suspense>`
---
## Why This Error Occurred
When the `cacheComponents` feature is enabled, Next.js expects a parent `Suspense` boundary around any component that awaits data that should be accessed on every user request. The purpose of this requirement is so that Next.js can provide a useful fallback while this data is accessed and rendered.
While some data is inherently only available when a user request is being handled, such as request headers, Next.js assumes that by default any asynchronous data is expected to be accessed each time a user request is being handled unless you specifically cache it using `"use cache"`.
The proper fix for this specific error depends on what data you are accessing and how you want your Next.js app to behave.
## Possible Ways to Fix It
### Accessing Data
When you access data using `fetch`, a database client, or any other module which does asynchronous IO, Next.js interprets your intent as expecting the data to load on every user request.
If you are expecting this data to be used while fully or partially prerendering a page you must cache is using `"use cache"`.
Before:
```jsx filename="app/page.js"
async function getRecentArticles() {
return db.query(...)
}
export default async function Page() {
const articles = await getRecentArticles(token);
return <ArticleList articles={articles}>
}
```
After:
```jsx filename="app/page.js"
import { cacheTag, cacheLife } from 'next/cache'
async function getRecentArticles() {
"use cache"
// This cache can be revalidated by webhook or server action
// when you call revalidateTag("articles")
cacheTag("articles")
// This cache will revalidate after an hour even if no explicit
// revalidate instruction was received
cacheLife('hours')
return db.query(...)
}
export default async function Page() {
const articles = await getRecentArticles(token);
return <ArticleList articles={articles}>
}
```
If this data should be accessed on every user request you must provide a fallback UI using `Suspense` from React. Where you put this Suspense boundary in your application should be informed by the kind of fallback UI you want to render. It can be immediately above the component accessing this data or even in your Root Layout.
Before:
```jsx filename="app/page.js"
async function getLatestTransactions() {
return db.query(...)
}
export default async function Page() {
const transactions = await getLatestTransactions(token);
return <TransactionList transactions={transactions}>
}
```
After:
```jsx filename="app/page.js"
import { Suspense } from 'react'
async function TransactionList() {
const transactions = await db.query(...)
return ...
}
function TransactionSkeleton() {
return <ul>...</ul>
}
export default async function Page() {
return (
<Suspense fallback={<TransactionSkeleton />}>
<TransactionList/>
</Suspense>
)
}
```
### Headers
If you are accessing request headers using `headers()`, `cookies()`, or `draftMode()`. Consider whether you can move the use of these APIs deeper into your existing component tree.
Before:
```jsx filename="app/inbox.js"
export async function Inbox({ token }) {
const email = await getEmail(token)
return (
<ul>
{email.map((e) => (
<EmailRow key={e.id} />
))}
</ul>
)
}
```
```jsx filename="app/page.js"
import { cookies } from 'next/headers'
import { Inbox } from './inbox'
export default async function Page() {
const token = (await cookies()).get('token')
return (
<Suspense fallback="loading your inbox...">
<Inbox token={token}>
</Suspense>
)
}
```
After:
```jsx filename="app/inbox.js"
import { cookies } from 'next/headers'
export async function Inbox() {
const token = (await cookies()).get('token')
const email = await getEmail(token)
return (
<ul>
{email.map((e) => (
<EmailRow key={e.id} />
))}
</ul>
)
}
```
```jsx filename="app/page.js"
import { Inbox } from './inbox'
export default async function Page() {
return (
<Suspense fallback="loading your inbox...">
<Inbox>
</Suspense>
)
}
```
Alternatively you can add a Suspense boundary above the component that is accessing Request headers.
### Params and SearchParams
Layout `params`, and Page `params` and `searchParams` props are promises. If you await them in the Layout or Page component you might be accessing these props higher than is actually required. Try passing these props to deeper components as a promise and awaiting them closer to where the actual param or searchParam is required
Before:
```jsx filename="app/map.js"
export async function Map({ lat, lng }) {
const mapData = await fetch(`https://...?lat=${lat}&lng=${lng}`)
return drawMap(mapData)
}
```
```jsx filename="app/page.js"
import { cookies } from 'next/headers'
import { Map } from './map'
export default async function Page({ searchParams }) {
const { lat, lng } = await searchParams;
return (
<Suspense fallback="loading your inbox...">
<Map lat={lat} lng={lng}>
</Suspense>
)
}
```
After:
```jsx filename="app/map.js"
export async function Map({ coords }) {
const { lat, lng } = await coords
const mapData = await fetch(`https://...?lat=${lat}&lng=${lng}`)
return drawMap(mapData)
}
```
```jsx filename="app/page.js"
import { cookies } from 'next/headers'
import { Map } from './map'
export default async function Page({ searchParams }) {
const coords = searchParams.then(sp => ({ lat: sp.lat, lng: sp.lng }))
return (
<Suspense fallback="loading your inbox...">
<Map coord={coords}>
</Suspense>
)
}
```
Alternatively you can add a Suspense boundary above the component that is accessing `params` or `searchParams` so Next.js understands what UI should be used when while waiting for this request data to be accessed.
#### `generateStaticParams`
For Layout and Page `params`, you can use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) to provide sample values for build-time validation, which allows you to await params directly without Suspense.
```jsx filename="app/blog/[slug]/page.js"
export async function generateStaticParams() {
return [{ slug: 'hello-world' }]
}
export default async function Page({ params }) {
const { slug } = await params // Valid with generateStaticParams
return <div>Blog post: {slug}</div>
}
```
Note that validation is path-dependent. Runtime parameters may trigger conditional branches accessing runtime APIs without Suspense, or dynamic content without Suspense or `use cache`, resulting in errors. See [Dynamic Routes with Cache Components](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components).
### Short-lived Caches
`"use cache"` allows you to describe a [`cacheLife()`](/docs/app/api-reference/functions/cacheLife) that might be too short to be practical to prerender. The utility of doing this is that it can still describe a non-zero caching time for the client router cache to reuse the cache entry in the browser and it can also be useful for protecting upstream APIs while experiencing high request traffic.
If you expected the `"use cache"` entry to be prerenderable try describing a slightly longer `cacheLife()`.
Before:
```jsx filename="app/page.js"
import { cacheLife } from 'next/cache'
async function getDashboard() {
"use cache"
// This cache will revalidate after 1 second. It is so short
// Next.js won't prerender it on the server but the client router
// can reuse the result for up to 30 seconds unless the user manually refreshes
cacheLife('seconds')
return db.query(...)
}
export default async function Page() {
const data = await getDashboard(token);
return <Dashboard data={data}>
}
```
After:
```jsx filename="app/page.js"
import { cacheLife } from 'next/cache'
async function getDashboard() {
"use cache"
// This cache will revalidate after 1 minute. It's long enough that
// Next.js will still produce a fully or partially prerendered page
cacheLife('minutes')
return db.query(...)
}
export default async function Page() {
const data = await getDashboard(token);
return <Dashboard data={data}>
}
```
Alternatively you can add a Suspense boundary above the component that is accessing this short-lived cached data so Next.js understands what UI should be used while accessing this data on a user request.
## Useful Links
- [`Suspense` React API](https://react.dev/reference/react/Suspense)
- [`headers` function](/docs/app/api-reference/functions/headers)
- [`cookies` function](/docs/app/api-reference/functions/cookies)
- [`draftMode` function](/docs/app/api-reference/functions/draft-mode)
- [`connection` function](/docs/app/api-reference/functions/connection)
- [`cacheLife` function](/docs/app/api-reference/functions/cacheLife)
- [`cacheTag` function](/docs/app/api-reference/functions/cacheTag)

View File

@@ -0,0 +1,35 @@
---
title: Handling "Build Directory Not Writeable" Error in Next.js
description: This document explains the "Build Directory Not Writeable" error in Next.js and provides a solution to resolve this issue.
---
## Why This Error Occurred
The "Build Directory Not Writeable" error usually occurs when the file system does not permit writing to the designated directory. A common scenario for this error is when you initiate a [custom server](/docs/pages/guides/custom-server) in development mode on a production server.
These production servers often disallow writing to the filesystem after your application is built, causing this error.
## Possible Ways to Fix It
If you're deploying a custom server with a server file (let's assume it's named `server.js`), you should modify the scripts key in your `package.json` to the following:
```json filename="package.json"
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
Ensure that your custom server starts Next.js in production mode when `NODE_ENV` is set to `production`:
```js filename="server.js"
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
```
## Useful Links
- [Custom Server documentation + examples](/docs/pages/guides/custom-server) - Learn more about how to effectively set up and manage an ejected server in Next.js.

View File

@@ -0,0 +1,21 @@
---
title: Resolving "Built-in CSS Support Disabled" Error in Next.js
description: This document provides a comprehensive explanation of the "Built-in CSS Support Disabled" error in Next.js and suggests ways to fix it.
---
## Why This Error Occurred
The "Built-in CSS Support Disabled" error typically occurs when a custom CSS configuration is added in the `next.config.js` file. This action deactivates the built-in CSS/SCSS support to avoid conflicts in configuration.
If you have added a legacy plugin like `@zeit/next-css` in your `next.config.js` file, you may encounter this error message.
## Possible Ways to Fix It
If you want to use the built-in CSS/SCSS support, you need to remove any custom CSS configuration or plugins such as `@zeit/next-css` or `@zeit/next-sass` in your `next.config.js` file. We recommend this approach.
On the other hand, if you choose not to use the built-in support, you can safely ignore this warning.
## Useful Links
- [Built-in CSS Support docs](/docs/app/getting-started/css) - Learn more about the built-in CSS/SCSS support in Next.js and how to use it effectively.
- [Custom webpack config docs](/docs/pages/api-reference/config/next-config-js/webpack) - Get more information on customizing your webpack configuration in Next.js.

View File

@@ -0,0 +1,25 @@
---
title: Resolving "Built-in next/font" Error in Next.js
description: This document offers a detailed guide on fixing the "Built-in `next/font`" error in Next.js, which typically occurs when you're still using the `@next/font` package in Next.js 13.2 and later.
---
`next/font` will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance.
## Why This Error Occurred
The "Built-in `next/font`" error is triggered when the `@next/font` package is still installed and used in your Next.js application.
From version 13.2 onward, **`next/font` has been built into Next.js**, making the `@next/font` package redundant. The `@next/font` package will be completely removed in Next.js 14.
## Possible Ways to Fix It
To resolve this issue, you need to uninstall `@next/font` and replace all `@next/font` imports with `next/font` in your project. This can be done automatically using the `built-in-next-font` codemod:
```sh filename="Terminal"
npx @next/codemod built-in-next-font .
```
## Useful Links
- [Codemods](/docs/app/guides/upgrading/codemods) - Understand more about codemods and how they can help automate large-scale codebase refactors.
- [Optimizing Fonts](/docs/app/api-reference/components/font) - Learn how to optimize fonts in your Next.js applications for improved performance.

View File

@@ -0,0 +1,30 @@
---
title: Caches Bypassed in Development Mode
---
## Disabling Caches in Development Mode
While running Next.js in development mode with `next dev` an initial page load or client navigation was handled with a `cache-control: no-store` header. The most common reason for this is that you have your web browser's DevTools open with "Disable Cache" enabled. Another common reason is you performed a hard refresh (Cmd + Shift + R / Ctrl + Shift + R).
Disabling caches while in development mode affects the debugging experience of Cache Components. Read on to understand more about how Next.js handles caches in development mode and what changes when they are intentionally disabled.
## Understanding Cache handling in Development Mode
In development mode, Next.js ensures that Cache Components render in the right environment to allow for React DevTools to highlight which components are part of the available for prerendering statically before any user request, which are available when prefetching segments at runtime before a navigation occurs, and finally which are dynamic and will only be fetched on user navigation.
This behavior has a small cost when a cold cache is encountered. Rather than streaming immediately Next.js will wait to fill this cache before streaming the response. As you navigate around you App in development mode these caches will fill and most navigations to cached content should feel instant once warm.
However if you instruct Next.js to skip all server caches using something like the "Disable Cache" option in your browser's DevTools, this behavior would be detrimental since every cache will be considered cold on every request leading to blocking navigations. Instead Next.js prints a warning that this particular request is not suitable for debugging Cache Components and then renders fresh results as fast as possible.
## Should you use "Disable Cache"?
Chrome, in particular, defaults all network request to "Disable Cache" when DevTools is open. For Next.js this is not recommended because it is overly aggressive in what is not cached and can provide a false impression of page performance that doesn't represent realistic usage of a web app.
However there are times when disabling a server caches can be useful. For instance if you know some upstream data system has updated but these updates are not connected to your local dev environment through features like `revalidateTag`.
If you must turn on "Disable Cache" to force a refresh we recommend that you disable the option once you've achieved your goal.
## Useful Links
- [`revalidateTag` function](/docs/app/api-reference/functions/revalidateTag)
- [`"use cache"` directive](/docs/app/api-reference/directives/use-cache)

View File

@@ -0,0 +1,17 @@
---
title: Cannot output to /public
---
## Why This Error Occurred
Either you set `distDir` to `public` in your `next.config.js` or during `next export` you tried to export to the `public` directory.
This is not allowed because `public` is used by Next.js to serve static assets.
## Possible Ways to Fix It
Use a different `distDir` or export to a different folder.
## Useful Links
- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder)

View File

@@ -0,0 +1,17 @@
---
title: Cannot output to /static
---
## Why This Error Occurred
Either you set `distDir` to `static` in your `next.config.js` or during `next export` you tried to export to the `static` directory.
This is not allowed because `static` is used by Next.js to serve static assets.
## Possible Ways to Fix It
Use a different `distDir` or export to a different folder.
## Useful Links
- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder)

View File

@@ -0,0 +1,15 @@
---
title: Can't Override Next Props
---
## Why This Error Occurred
In your `pages/_app.js` you returned an object from `getInitialProps` that contained a `router` or `Component` value. These property names are used by Next.js and can not be overwritten.
## Possible Ways to Fix It
Look in your \_app.js component's `getInitialProps` function and make sure neither of these property names are present in the object returned.
## Useful Links
- [The issue this was reported in: #6480](https://github.com/vercel/next.js/issues/6480)

View File

@@ -0,0 +1,15 @@
---
title: 'Circular structure in `getInitialProps` result'
---
## Why This Error Occurred
`getInitialProps` is serialized to JSON using `JSON.stringify` and sent to the client side for hydrating the page.
However, the result returned from `getInitialProps` can't be serialized when it has a circular structure.
## Possible Ways to Fix It
Circular structures are not supported, so the way to fix this error is removing the circular structure from the object that is returned from `getInitialProps`.
For example, the `req` instance exposed is a circular object and can not be serialized, instead the specific fields such as relevant headers on the instance should be passed specifically.

View File

@@ -0,0 +1,57 @@
---
title: React Class component rendered in a Server Component
---
## Why This Error Occurred
You are rendering a React Class Component in a Server Component, `React.Component` and `React.PureComponent` only works in Client Components.
## Possible Ways to Fix It
Use a Function Component.
### Before
```jsx filename="app/page.js"
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
}
}
```
### After
```jsx filename="app/page.js"
export default function Page() {
return <p>Hello world</p>
}
```
Mark the component rendering the React Class Component as a Client Component by adding `'use client'` at the top of the file.
### Before
```jsx filename="app/page.js"
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
}
}
```
### After
```jsx filename="app/page.js"
'use client'
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
}
}
```
## Useful Links
- [Server Components](/docs/app/getting-started/server-and-client-components)

View File

@@ -0,0 +1,16 @@
---
title: Client-side Exception Occurred
---
## Why This Error Occurred
In your production application a client-side error occurred that was not caught by an error boundary. Additional information should be visible in the console tab of your browser.
## Possible Ways to Fix It
Add error boundaries in your React tree to gracefully handle client-side errors and render a fallback view when they occur.
## Useful Links
- [Error Boundaries Documentation](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [Custom Error Page Documentation](/docs/pages/building-your-application/routing/custom-error#more-advanced-error-page-customizing)

View File

@@ -0,0 +1,24 @@
---
title: Invalid webpack resolve alias
---
## Why This Error Occurred
When overriding `config.resolve.alias` incorrectly in `next.config.js` webpack will throw an error because private-next-pages is not defined.
## Possible Ways to Fix It
This is not a bug in Next.js, it's related to the user adding a custom webpack(config) config to next.config.js and overriding internals by not applying Next.js' aliases. Solution would be:
```js filename="next.config.js"
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
// your aliases
}
}
```
## Useful Links
- [Related issue](https://github.com/vercel/next.js/issues/6681)

View File

@@ -0,0 +1,33 @@
---
title: Conflicting Public File and Page File
---
## Why This Error Occurred
One of your public files has the same path as a page file which is not supported. Since only one resource can reside at the URL both public files and page files must be unique.
## Possible Ways to Fix It
Rename either the public file or page file that is causing the conflict.
Example conflict between public file and page file
```bash filename="Folder structure"
public/
hello
pages/
hello.js
```
Non-conflicting public file and page file
```bash filename="Folder structure"
public/
hello.txt
pages/
hello.js
```
## Useful Links
- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder)

View File

@@ -0,0 +1,69 @@
---
title: Conflicting SSG Paths
---
## Why This Error Occurred
You returned **conflicting paths** in your `getStaticPaths` function for one of your pages. All page paths must be unique and duplicates are not allowed.
## Possible Ways to Fix It
Remove any conflicting paths shown in the error message and only return them from one `getStaticPaths`.
Example conflicting paths:
```jsx filename="pages/hello/world.js"
export default function Hello() {
return 'hello world!'
}
```
```jsx filename="pages/[...catchAll].js"
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
paths: [
'/hello/world', // <-- this conflicts with the /hello/world.js page, remove to resolve error
'/another',
],
fallback: false,
})
export default function CatchAllPage() {
return 'Catch-all page'
}
```
Example conflicting paths:
```jsx filename="pages/blog/[slug].js"
export const getStaticPaths = () => ({
paths: ['/blog/conflicting', '/blog/another'],
fallback: false,
})
export default function Blog() {
return 'Blog!'
}
```
```jsx filename="pages/[...catchAll].js"
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
paths: [
// this conflicts with the /blog/conflicting path above, remove to resolve error
'/blog/conflicting',
'/another',
],
fallback: false,
})
export default function CatchAll() {
return 'Catch-all page'
}
```
## Useful Links
- [`getStaticPaths` Documentation](/docs/pages/building-your-application/data-fetching/get-static-paths)

View File

@@ -0,0 +1,32 @@
---
title: createContext in a Server Component
---
## Why This Error Occurred
You are using `createContext` in a Server Component but it only works in Client Components.
## Possible Ways to Fix It
Mark the component using `createContext` as a Client Component by adding `'use client'` at the top of the file.
### Before
```jsx filename="app/example-component.js"
import { createContext } from 'react'
const Context = createContext()
```
### After
```jsx filename="app/example-component.js"
'use client'
import { createContext } from 'react'
const Context = createContext()
```
## Useful Links
- [Server and Client Components Composition Patterns](/docs/app/getting-started/server-and-client-components#examples)

55
errors/css-global.mdx Normal file
View File

@@ -0,0 +1,55 @@
---
title: 'Global CSS Must Be in Your Custom `<App>`'
---
## Why This Error Occurred
An attempt to import Global CSS from a file outside of [`pages/_app.js`](/docs/pages/building-your-application/routing/custom-app) was made.
Global CSS cannot be used in files other than your [custom `_app.js` file](/docs/pages/building-your-application/routing/custom-app) due to ordering problems and side-effects.
## Possible Ways to Fix It
There are two possible ways to fix this error:
- Move all global CSS imports to your [`pages/_app.js` file](/docs/pages/building-your-application/routing/custom-app).
- If you do not wish your stylesheet to be global, update it to use [CSS Modules](/docs/app/getting-started/css). This will allow you to import the stylesheet and scope the styles to a specific component.
### Example
Consider the stylesheet named [`styles.css`](/docs/app/getting-started/css)
```css filename="styles.css"
body {
font-family:
'SF Pro Text', 'SF Pro Icons', 'Helvetica Neue', 'Helvetica', 'Arial',
sans-serif;
padding: 20px 20px 60px;
max-width: 680px;
margin: 0 auto;
}
```
**Global CSS**:
Create a [`pages/_app.js` file](/docs/pages/building-your-application/routing/custom-app) if not already present. Then import the `styles.css` file:
```jsx filename="pages/_app.js"
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
**CSS Modules**:
Rename the `styles.css` file to `styles.module.css`. Then import the file in the component or page where you want to use the styles.
```jsx filename="pages/index.js"
import styles from '../../styles.module.css'
export default function Home() {
return <div className={styles.container}>Hello World</div>
}
```

View File

@@ -0,0 +1,25 @@
---
title: CSS Modules Imported by a Dependency
---
## Why This Error Occurred
One of your dependencies (`node_modules`) imports a CSS Modules file.
This normally happens when a package's source files are accidentally consumed,
instead of the built package.
## Possible Ways to Fix It
Reach out to the maintainer and ask for them to publish a compiled version of
their dependency.
Compiled dependencies do not have references to CSS Module files, or any other
files that require bundler-specific integrations.
The dependency should also provide instructions about what CSS needs to be
imported by you, in your application.
If this is **first-party code**, try [including monorepo packages in the compilation pipeline](/docs/architecture/nextjs-compiler#module-transpilation).
> **Good to know**: This limitation does not exist when using the App Router.

29
errors/css-npm.mdx Normal file
View File

@@ -0,0 +1,29 @@
---
title: CSS Imported by a Dependency
---
## Why This Error Occurred
One of your dependencies (`node_modules`) imports a CSS file.
This normally happens when a package's source files are accidentally consumed,
instead of the built package.
## Possible Ways to Fix It
Reach out to the maintainer and ask for them to publish a compiled version of
their dependency.
Compiled dependencies do not have references to CSS files, or any other files
that require bundler-specific integrations.
The dependency should also provide instructions about what CSS needs to be
imported by you, in your application.
Importing CSS files within `node_modules` cannot be supported because we cannot
know the correct behavior:
- Should the file be consumed as Global CSS or CSS Modules?
- If Global, in what order does the file need to be injected?
- If Modules, what are the emitted class names? As-is, camel-case, snake case?
- Etc.

View File

@@ -0,0 +1,48 @@
---
title: Images cannot be imported into your custom document.
---
## Why This Error Occurred
An attempt to import an image file into [`pages/_document.js`](/docs/pages/building-your-application/routing/custom-document) was made.
Custom documents aren't compiled for the browser and images statically imported like this will not be displayed.
## Possible Ways to Fix It
If your image needs to be displayed on every page you can relocate it to your [`pages/_app.js`](/docs/pages/building-your-application/routing/custom-app) file.
### Example
```jsx filename="pages/_app.js"
import yourImage from 'path/to/your/image'
import Image from 'next/image'
function MyApp({ Component, pageProps }) {
return (
<>
<Image src={yourImage} alt="your_image_description" />
<Component {...pageProps} />
</>
)
}
export default MyApp
```
If your application is not using image imports with `next/image`, you can disable the built-in loader with the following `next.config.js`:
```js filename="next.config.js"
module.exports = {
images: {
disableStaticImages: true,
},
}
```
## Useful Links
- [Custom `Document`](/docs/pages/building-your-application/routing/custom-document)
- [Custom `App`](/docs/pages/building-your-application/routing/custom-app)
- [Static File Serving](/docs/pages/api-reference/file-conventions/public-folder)
- [Disable Static Image Imports](/docs/pages/api-reference/components/image#disablestaticimages)

View File

@@ -0,0 +1,16 @@
---
title: 'Custom `_error` without /404'
---
## Why This Error Occurred
You added a custom `/_error` page without adding a custom `/404` page. Adding a custom `/_error` typically opts your application out of having the automatic static optimization applied to the 404 page.
## Possible Ways to Fix It
Add a `pages/404.js` with the 404 page you would like to show.
## Useful Links
- [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization)
- [404 Page](/docs/pages/building-your-application/routing/custom-error#404-page)

View File

@@ -0,0 +1,37 @@
---
title: Deleting Query Parameters In Proxies
---
## Why This Error Occurred
In previous versions of Next.js, we were merging query parameters with the incoming request for rewrites happening in proxies, to match the behavior of static rewrites declared in the config. This forced Next.js users to use empty query parameters values to delete keys.
We are changing this behavior to allow extra flexibility and a more streamlined experience for users. So from now on, query parameters will not be merged and thus the warning.
```ts filename="proxy.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function proxy(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.searchParams.delete('key') // <-- this is now possible!
return NextResponse.rewrite(nextUrl)
}
```
## Possible Ways to Fix It
If you are relying on the old behavior, please add the query parameters manually to the rewritten URL. Using `request.nextUrl` would do that automatically for you.
```ts filename="proxy.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function proxy(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.pathname = '/dest'
return NextResponse.rewrite(nextUrl)
}
```
This warning will be removed in the next version of Next.js.

View File

@@ -0,0 +1,64 @@
---
title: Entire page deopted into client-side rendering
---
## Why This Error Occurred
During prerendering, the entire page was deopted into client-side rendering by `useSearchParams` as there was no [Suspense boundary](/docs/app/api-reference/functions/use-search-params#prerendering) that caught it.
If a route is prerendered, calling `useSearchParams()` will cause the tree up to the closest [Suspense boundary](/docs/app/api-reference/functions/use-search-params#prerendering) to be client-side rendered.
This allows a part of the page to be prerendered while the dynamic part that uses `searchParams` can be client-side rendered.
## Possible Ways to Fix It
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 if `app/dashboard/search-bar.tsx` uses `useSearchParams` wrap the component in a [Suspense boundary](/docs/app/api-reference/functions/use-search-params#prerendering) as shown in `app/dashboard/page.tsx`.
```tsx filename="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 not be logged on the server during prerendering
console.log(search)
return <>Search: {search}</>
}
```
```tsx filename="app/dashboard/page.tsx"
import { Suspense } from 'react'
import SearchBar from './search-bar'
// This component passed as 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>
<h1>Dashboard</h1>
</>
)
}
```
## Useful Links
- [`useSearchParams` prerendering documentation](/docs/app/api-reference/functions/use-search-params#prerendering)

View File

@@ -0,0 +1,71 @@
---
title: '`deploymentId` contains invalid characters'
---
## Why This Error Occurred
The `deploymentId` in your `next.config.js` contains characters that are not allowed. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\_) are permitted.
## Possible Ways to Fix It
### Option 1: Remove Invalid Characters
Remove or replace any characters that are not alphanumeric, hyphens, or underscores:
```js
// ✅ Correct
module.exports = {
deploymentId: 'my-deployment-123', // Only alphanumeric, hyphens, underscores
}
// ❌ Incorrect
module.exports = {
deploymentId: 'my deployment 123', // Contains spaces
deploymentId: 'my.deployment.123', // Contains dots
deploymentId: 'my/deployment/123', // Contains slashes
deploymentId: 'my@deployment#123', // Contains special characters
}
```
### Option 2: Sanitize the Deployment ID
If you're generating the ID from environment variables or other sources, sanitize it to remove invalid characters:
```js
// next.config.js
const rawId = process.env.DEPLOYMENT_ID || 'default-id'
// Remove all characters that are not alphanumeric, hyphens, or underscores
const sanitizedId = rawId.replace(/[^a-zA-Z0-9_-]/g, '')
module.exports = {
deploymentId: sanitizedId,
}
```
### Option 3: Use a Valid Format
Common valid formats include:
```js
// next.config.js
module.exports = {
// Using hyphens
deploymentId: 'my-deployment-id',
// Using underscores
deploymentId: 'my_deployment_id',
// Alphanumeric only
deploymentId: 'mydeployment123',
// Mixed format
deploymentId: 'my-deployment_123',
}
```
## Additional Information
- The deployment ID is used for skew protection and asset versioning
- Invalid characters can cause issues with URL encoding and routing
- Keep the ID URL-friendly by using only the allowed character set
- The validation ensures compatibility across different systems and environments

View File

@@ -0,0 +1,33 @@
---
title: '`deploymentId` must be a string'
---
## Why This Error Occurred
The `deploymentId` option in your `next.config.js` must be a string value.
## Possible Ways to Fix It
Ensure your `deploymentId` is a string:
```js
// ✅ Correct
module.exports = {
deploymentId: 'my-deployment-123',
}
// ✅ Using environment variables
module.exports = {
deploymentId: process.env.GIT_HASH || 'default-id',
}
// ❌ Incorrect
module.exports = {
deploymentId: 12345, // Must be a string, not a number
}
```
The `deploymentId` can be:
- A string: `deploymentId: 'my-deployment-123'`
- `undefined` (will use `NEXT_DEPLOYMENT_ID` environment variable if set)

View File

@@ -0,0 +1,20 @@
---
title: config.analytics is deprecated
---
## Why This Error Occurred
The Core Web Vitals of your Next.js application could be tracked and sent to any backend of your choice.
Earlier version of Next.js enable tracking by specifying `analyticsId` into your `next.config.js` file.
This configuration mechanism will be removed in nextjs@15, as it could be elegantly replaced with `useReportWebVitals` built-in hook.
## Possible Ways to Fix It
To remove this warning, you must remove `analyticsId` from your `next.config.js` file.
To keep tracking your Core Web Vitals, you could:
- use `useReportWebVitals` hook as explained [here](/docs/app/api-reference/functions/use-report-web-vitals) and send the metrics to any backend of your choice.
- [install and use](https://vercel.com/docs/speed-insights/quickstart) `@vercel/speed-insights` package into your application

View File

@@ -0,0 +1,15 @@
---
title: Deprecated target config
---
## Why This Error Occurred
Starting in Next.js 13, the `target` property in `next.config.js` has been removed.
## Possible Ways to Fix It
For serverless targets, please use the Output File Tracing or deploy your application somewhere where it can be leveraged automatically, like [Vercel](https://vercel.com).
## Useful Links
- [Output File Tracing Documentation](/docs/pages/api-reference/config/next-config-js/output)

View File

@@ -0,0 +1,21 @@
---
title: '`Head` or `NextScript` attribute `crossOrigin` is deprecated'
---
## Why This Error Occurred
This option has been moved to `next.config.js`.
## Possible Ways to Fix It
Add the config option:
```js filename="next.config.js"
module.exports = {
crossOrigin: 'anonymous',
}
```
## Useful Links
- [The issue this was reported in: #5674](https://github.com/vercel/next.js/issues/5674)

35
errors/duplicate-sass.mdx Normal file
View File

@@ -0,0 +1,35 @@
---
title: Duplicate Sass Dependencies
---
## Why This Error Occurred
Your project has a direct dependency on both `sass` and `node-sass`, two
different packages that both compile Sass files!
Next.js will only use one of these, so it is suggested that you remove one or the
other.
## Possible Ways to Fix It
The `sass` package is a modern implementation of Sass in JavaScript that
supports all the new features and does not require any native dependencies.
Since `sass` is now the canonical implementation, we suggest removing the older
`node-sass` package, which should speed up your builds and project install time.
**Via npm**
```bash filename="Terminal"
npm uninstall node-sass
```
**Via Yarn**
```bash filename="Terminal"
yarn remove node-sass
```
## Useful Links
- [`sass` package documentation](https://github.com/sass/dart-sass)

View File

@@ -0,0 +1,67 @@
---
title: DynamicServerError - Dynamic Server Usage
---
## Why This Message Occurred
You attempted to use a Next.js function that depends on Async Context (such as `headers` or `cookies` from `next/headers`) but it was not bound to the same call stack as the function that ran it (e.g., calling `cookies()` inside of a `setTimeout` or `setInterval`).
While generating static pages, Next.js will throw a `DynamicServerError` if it detects usage of a dynamic function, and catch it to automatically opt the page into dynamic rendering. However, when it's uncaught, it will result in this build-time error.
## What is Async Context?
[Async Context](https://github.com/tc39/proposal-async-context) is a way to pass data within the same call stack, even through asynchronous operations. This is very useful in Next.js, where functions like cookies or headers might be called from anywhere within a React component tree or other functions during React rendering.
## Scenarios that can cause this to happen
- The function was called inside of a `setTimeout` or `setInterval`, causing the value to be read outside of the call stack that the context was bound to.
- The function was called after an async operation, but the promise wasn't awaited. This can cause the function to be called after the async operation has completed, resulting in a new execution context and loss of the original async context.
### Example of Incorrect Usage
```jsx filename="app/page.js"
import { cookies } from 'next/headers'
async function getCookieData() {
return new Promise((resolve) =>
setTimeout(async () => {
// cookies will be called outside of the async context, causing a build-time error
const cookieStore = await cookies()
resolve(cookieStore.getAll())
}, 1000)
)
}
export default async function Page() {
const cookieData = await getCookieData()
return <div>Hello World</div>
}
```
## Possible Ways to Fix It
**Manage Execution Contexts Correctly:** JavaScript operations like `setTimeout`, `setInterval`, event handlers, and Promises create new execution contexts. You need to maintain the async context when using these operations. Some strategies include:
- Invoke the function that depends on the async context outside of the function that creates a new execution context.
- Ensure that you await Promises that invoke a function that depends on async context, otherwise the function may be called after the async operation has completed.
### Example of Correct Usage
```jsx filename="app/page.js"
import { cookies } from 'next/headers'
async function getCookieData() {
const cookieStore = await cookies()
const cookieData = cookieStore.getAll()
return new Promise((resolve) =>
setTimeout(() => {
resolve(cookieData)
}, 1000)
)
}
export default async function Page() {
const cookieData = await getCookieData()
return <div>Hello World</div>
}
```

View File

@@ -0,0 +1,47 @@
---
title: Dynamic code evaluation is not available in Proxy
---
## Why This Error Occurred
`eval()`, `new Function()` or compiling WASM binaries dynamically is not allowed in Proxy.
Specifically, the following APIs are not supported:
- `eval()`
- `new Function()`
- `WebAssembly.compile`
- `WebAssembly.instantiate` with [a buffer parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code)
## Possible Ways to Fix It
You can bundle your WASM binaries using `import`:
```ts filename="proxy.ts"
import { NextResponse } from 'next/server'
import squareWasm from './square.wasm?module'
export default async function proxy() {
const m = await WebAssembly.instantiate(squareWasm)
const answer = m.exports.square(9)
const response = NextResponse.next()
response.headers.set('x-square', answer.toString())
return response
}
```
In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by tree-shaking.
You can relax the check to allow specific files with your Proxy [configuration](/docs/pages/api-reference/edge#unsupported-apis):
```ts filename="pages/api/example.ts"
export const config = {
unstable_allowDynamic: [
'/lib/utilities.js', // allows a single file
'**/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
],
}
```
`unstable_allowDynamic` is a glob, or an array of globs, ignoring dynamic code evaluation for specific files. The globs are relative to your application root folder.
Be warned that if these statements are executed on the Edge, _they will throw and cause a runtime error_.

View File

@@ -0,0 +1,21 @@
---
title: 'Detected `next.config.js`, no exported configuration found'
---
## Why This Warning Occurred
There is no object exported from next.config.js or the object is empty.
## Possible Ways to Fix It
Check if you correctly export configuration in `next.config.js` file:
```js filename="next.config.js"
module.exports = {
/* config options here */
}
```
## Useful Links
- [Introduction to next.config.js](/docs/pages/api-reference/config/next-config-js)

View File

@@ -0,0 +1,78 @@
---
title: Empty generateStaticParams with Cache Components
---
## Why This Error Occurred
You're using [Cache Components](https://nextjs.org/docs/app/getting-started/caching) in your Next.js application, and one of your `generateStaticParams` functions returned an empty array, which causes a build error.
When Cache Components is enabled, Next.js performs build-time validation to ensure your routes can be properly prerendered without runtime dynamic access errors. If `generateStaticParams` returns an empty array, Next.js cannot validate that your route won't access dynamic values (like `await cookies()`, `await headers()`, or `await searchParams`) at runtime, which would cause errors.
This strict requirement ensures:
- Build-time validation catches potential runtime errors early
- All routes using Cache Components have at least one static variant to validate against
- You don't accidentally deploy routes that will fail at runtime
## Possible Ways to Fix It
### Option 1: Return at least one static param
Modify your `generateStaticParams` function to return at least one set of parameters. This is the most common fix and allows build-time validation to work properly.
```tsx filename="app/blog/[slug]/page.tsx"
// This will cause an error with Cache Components
export async function generateStaticParams() {
return [] // Empty array not allowed
}
// Return at least one sample param
export async function generateStaticParams() {
return [{ slug: 'hello-world' }, { slug: 'getting-started' }]
}
```
These samples serve dual purposes:
1. **Build-time validation**: Verify your route structure is safe
2. **Prerendering**: Generate instant-loading pages for popular routes
The build process only validates code paths that execute with your sample params. If runtime parameters trigger conditional logic that renders branches accessing runtime APIs (like `cookies()`) without Suspense, or dynamic content without Suspense or `use cache`, those will cause runtime errors.
### Option 2: Use a placeholder param
If you don't know actual values at build time, you can use a placeholder for validation. However, this defeats the purpose of build-time validation and should be avoided:
```tsx filename="app/blog/[slug]/page.tsx"
export async function generateStaticParams() {
// Placeholder only validates one code path
return [{ slug: '__placeholder__' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// Handle placeholder case
if (slug === '__placeholder__') {
notFound()
}
// Real params may trigger code paths
// that access dynamic APIs incorrectly, causing
// runtime errors that cannot be caught by error boundaries
const post = await getPost(slug)
return <div>{post.title}</div>
}
```
Using placeholders provides minimal build-time validation and increases the risk of runtime errors for actual parameter values.
## Useful Links
- [Cache Components Documentation](https://nextjs.org/docs/app/getting-started/caching)
- [generateStaticParams API Reference](https://nextjs.org/docs/app/api-reference/functions/generate-static-params)
- [Dynamic Routes with Cache Components](/docs/app/api-reference/file-conventions/dynamic-routes#with-cache-components)

View File

@@ -0,0 +1,15 @@
---
title: 'Empty Object Returned From `getInitialProps`'
---
## Why This Error Occurred
In one of your page components you added a `getInitialProps` that returned an empty object. This de-optimizes automatic static optimization. If you **meant** to do this and understand the **consequences** you can ignore this message as it is only shown in development.
## Possible Ways to Fix It
Look for any page's using `getInitialProps` that return an empty object `{}`. You might also need to update higher order components (HOCs) to only add `getInitialProps` if they are present on the passed component.
## Useful Links
- [Automatic Static Optimization Documentation](/docs/pages/building-your-application/rendering/automatic-static-optimization)

View File

@@ -0,0 +1,11 @@
---
title: 'The key `<your key>` under "env" in `next.config.js` is not allowed.'
---
## Why This Error Occurred
Next.js configures internal variables for replacement itself. `NEXT_RUNTIME` along with variables starting with `__` or `NODE_` are currently internal, for this reason they are not allowed as values for `env` in `next.config.js`
## Possible Ways to Fix It
Rename the specified key so that it does not start with `__` or `NODE_`, or pick another name for `NEXT_RUNTIME`.

View File

@@ -0,0 +1,22 @@
---
title: Env Loading Disabled
---
## Why This Error Occurred
In your project you have `dotenv` listed as a `dependency` or a `devDependency` which opts-out of Next.js' automatic loading to prevent creating a conflict with any existing `dotenv` behavior in your project.
This is also disabled if a `package.json` isn't able to found in your project somehow.
## Possible Ways to Fix It
Update to the latest version of Next.js (>= v9.4.1) where this support is enabled regardless of `dotenv` being installed.
Remove `dotenv` from your `devDependencies` or `dependencies` and allow Next.js to load your `dotenv` files for you.
## Useful Links
- [dotenv](https://npmjs.com/package/dotenv)
- [dotenv-expand](https://npmjs.com/package/dotenv-expand)
- [Environment Variables](https://en.wikipedia.org/wiki/Environment_variable)
- [Next.js Environment Variables Docs](/docs/pages/guides/environment-variables)

View File

@@ -0,0 +1,29 @@
---
title: 'Experimental `appDir: true`'
---
## Why This Error Occurred
Your project contains a directory named `app/`. Since Next.js 13, this is a [reserved name](/blog/next-13#new-app-directory-beta).
## Possible Ways to Fix It
To use the new app directory and its features, please add `appDir: true` to your configuration in `next.config.js` under `experimental`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
},
}
module.exports = nextConfig
```
If you do not want to use the new `app/` directory features yet, but have a directory named `app/`, rename the directory to something else.
## Useful Links
- [Next.js 13 App directory](/blog/next-13#new-app-directory-beta)
- [App directory documentation](/docs/app/getting-started)

View File

@@ -0,0 +1,9 @@
---
title: '`next/jest` Experimental'
---
## Why This Message Occurred
You are using `next/jest` which is currently an experimental feature of Next.js. In a future version of Next.js `next/jest` will be marked as stable.
If you have any feedback about the transformer you can share it on this discussion: https://github.com/vercel/next.js/discussions/31152.

View File

@@ -0,0 +1,54 @@
---
title: Re-exporting all exports from a page is disallowed
---
## Why This Error Occurred
The following export can potentially break Next.js' compilation of pages:
```jsx filename="pages/example.js"
export * from '...'
```
This is because Node.js code may be leaked to the browser build, causing an error. For example, the following two pages:
```jsx filename="pages/example-a.js"
import fs from 'fs'
export default function A() {
return <main />
}
export function getStaticProps() {
fs
return { props: {} }
}
```
```jsx filename="pages/example-b.js"
export * from './example-a'
```
Would cause the following error:
```txt
Module not found: Can't resolve 'fs' in './pages/example-b.js'
```
## Possible Ways to Fix It
Update your page to re-export the default component only:
```jsx filename="pages/example-a.js"
export { default } from './example-b'
```
If the other page uses `getServerSideProps` or `getStaticProps`, you can re-export those individually too:
```jsx filename="pages/example-a.js"
export { default, getServerSideProps } from './example-b'
// or
export { default, getStaticProps } from './example-b'
// or
export { default, getStaticProps, getStaticPaths } from './example-b/[dynamic]'
```

View File

@@ -0,0 +1,26 @@
---
title: Export with Image Optimization API
---
## Why This Error Occurred
You configured `output: 'export'` (or ran `next export`) while importing the `next/image` component using the default `loader` configuration.
However, the default `loader` relies on the Image Optimization API which is not available for exported applications.
This is because Next.js optimizes images on-demand, as users request them (not at build time).
## Possible Ways to Fix It
- Use [`next start`](/docs/pages/api-reference/cli/next#next-start-options) to run a server, which includes the Image Optimization API.
- Use any provider which supports Image Optimization (such as [Vercel](https://vercel.com)).
- [Configure `loader`](/docs/pages/api-reference/components/image#loader) in `next.config.js`.
- [Configure `unoptimized`](/docs/pages/api-reference/components/image#unoptimized) in `next.config.js`.
## Useful Links
- [Deployment Documentation](/docs/pages/getting-started/deploying)
- [Image Optimization Documentation](/docs/pages/api-reference/components/image)
- [`output: 'export'` Documentation](/docs/pages/guides/static-exports)
- [`next/image` Documentation](/docs/pages/api-reference/components/image)
- [Vercel Documentation](https://vercel.com/docs/concepts/next.js/image-optimization)

View File

@@ -0,0 +1,22 @@
---
title: Export Custom Routes
---
## Why This Error Occurred
In your `next.config.js` you defined `rewrites`, `redirects`, or `headers` along with `output: 'export'` (or you ran `next export`).
These configs do not apply when exporting your Next.js application manually.
## Possible Ways to Fix It
- Remove `rewrites`, `redirects`, and `headers` from your `next.config.js` to disable these features or
- Remove `output: 'export'` (or `next export`) in favor of [`next start`](/docs/pages/api-reference/cli/next#next-start-options) to run a production server
## Useful Links
- [Deployment Documentation](/docs/pages/getting-started/deploying)
- [`output: 'export'` Documentation](/docs/pages/guides/static-exports)
- [Rewrites Documentation](/docs/pages/api-reference/config/next-config-js/rewrites)
- [Redirects Documentation](/docs/pages/api-reference/config/next-config-js/redirects)
- [Headers Documentation](/docs/pages/api-reference/config/next-config-js/headers)

18
errors/export-no-i18n.mdx Normal file
View File

@@ -0,0 +1,18 @@
---
title: Export Internationalization (i18n)
---
## Why This Error Occurred
In your `next.config.js` you defined `i18n`, along with `output: 'export'` (or you ran `next export`).
## Possible Ways to Fix It
- Remove `i18n` from your `next.config.js` to disable Internationalization or
- Remove `output: 'export'` (or `next export`) in favor of [`next start`](/docs/pages/api-reference/cli/next#next-start-options) to run a production server
## Useful Links
- [Deployment Documentation](/docs/pages/getting-started/deploying)
- [`output: 'export'` Documentation](/docs/pages/guides/static-exports)
- [Internationalized Routing](/docs/pages/guides/internationalization)

View File

@@ -0,0 +1,28 @@
---
title: The provided export path doesn't match the page.
---
## Why This Error Occurred
An `exportPathMap` path was improperly matched to a dynamically routed page.
This would result in the page missing its URL parameters.
## Possible Ways to Fix It
Change your `exportPathMap` function in `next.config.js` to have a path that matches the dynamically routed page.
```js filename="next.config.js"
module.exports = {
exportPathMap: function () {
return {
'/': { page: '/' },
// '/blog/nextjs': { page: '/blog/[post]/comment/[id]' }, // wrong
'/blog/nextjs/comment/1': { page: '/blog/[post]/comment/[id]' }, // correct
}
},
}
```
## Useful Links
- [exportPathMap](/docs/pages/api-reference/config/next-config-js/exportPathMap) documentation

View File

@@ -0,0 +1,36 @@
---
title: SWC Failed to Load
---
## Why This Message Occurred
Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScript/TypeScript. This new compiler is up to 17x faster than Babel when compiling individual files and up to 5x faster Fast Refresh.
SWC requires a binary to be downloaded that is compatible with your system. In some cases this binary may fail to load either from failing to download or an incompatibility with your architecture.
## Possible Ways to Fix It
When on an M1 Mac and switching from a Node.js version without M1 support to one with, e.g. v14 to v16, you may need a different swc dependency which can require re-installing `node_modules` (`npm i --force` or `yarn install --force`).
On Windows make sure you have Microsoft Visual C++ Redistributable installed. https://docs.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist
Alternatively, you might need to allow optional packages to be installed by your package manager (remove `--no-optional` flag) for the package to download correctly.
In some cases your package manager (e.g. `npm`) might have generated a lockfile that only includes `optionalDependencies` specific to the platform it was generated on, preventing the `optionalDependency` needed for CI from being installed.
This can be fixed by removing the lockfile and regenerating it with a newer version of your package manager `npm i -g npm@latest`.
If SWC continues to fail to load you can opt-out by disabling `swcMinify` in your `next.config.js` or by adding a `.babelrc` to your project with the following content:
```json filename=".babelrc"
{
"presets": ["next/babel"]
}
```
Be sure to report the issue on [the feedback thread](https://github.com/vercel/next.js/discussions/30468) so that we can investigate it further.
## Useful Links
- [SWC Feedback Thread](https://github.com/vercel/next.js/discussions/30468)
- [SWC Disabled Document](/docs/messages/swc-disabled)

View File

@@ -0,0 +1,20 @@
---
title: 'Failed to fetch `devPagesManifest`'
---
## Why This Error Occurred
The network request to load `_devPagesManifest.json` did not succeed.
The dev pages manifest file is used by `next/link` to retrieve the list of pages to be (pre-)loaded by Next.js.
If it fails, Next.js cannot properly navigate and link between pages.
## Possible Ways to Fix It
- Make sure your browser developer tools, extensions, and any other network tools aren't blocking that request.
- If you're running your Next.js application through a proxy, nginx, or other network layer, make sure links like `/_next/*` are configured to be allowed.
## Useful Links
- [Original GitHub Issue Thread](https://github.com/vercel/next.js/issues/16874)
- [GitHub Issue Thread With Reproduction](https://github.com/vercel/next.js/issues/38047)

View File

@@ -0,0 +1,22 @@
---
title: Failed to find Server Action
---
## Why This Message Occurred
For security purposes, Next.js creates encrypted, non-deterministic keys (IDs) to allow for the client to reference and call the [Server Action](/docs/app/getting-started/mutating-data). These keys are periodically recalculated between builds for enhanced security.
When self-hosting your Next.js application across multiple servers, each server instance may end up with a different encryption key, leading to potential inconsistencies.
## Possible Ways to Fix It
To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key.
The key must be a base64-encoded value with a valid AES key length (16, 24, or 32 bytes). Set this variable at **build time**—the key is embedded in the build output and used automatically at runtime.
If you are deploying your Next.js application to Vercel, you can use the feature [Skew Protection](https://vercel.com/docs/deployments/skew-protection) to ensure assets and functions from the previous version are still available, even after a new version is deployed.
## Useful Links
- [Server Actions - Security](/docs/app/guides/data-security)
- [Overwriting encryption keys (advanced)](/docs/app/guides/data-security#overwriting-encryption-keys-advanced)

View File

@@ -0,0 +1,21 @@
---
title: Fast Refresh had to perform full reload
---
## Why This Error Occurred
Fast Refresh had to perform a full reload when you edited a file. It may be because:
- The file you're editing might have other exports in addition to a React component.
- Your React component is an anonymous function.
- The component name is in camelCase and not PascalCase, for example `textField` instead of `TextField`.
## Possible Ways to Fix It
- Move your other exports to a separate file.
- Use a named function for your React component.
- Rename your component name to pascal case.
## Useful Links
- [Fast Refresh documentation](/docs/architecture/fast-refresh)

View File

@@ -0,0 +1,33 @@
---
title: '`future.webpack5` has been moved to `webpack5`'
---
## Why This Error Occurred
The `future.webpack5` option has been moved to `webpack5` in `next.config.js`.
## Possible Ways to Fix It
If you had the value `true` you can remove the option as webpack 5 is now the default for all Next.js apps unless opted out.
If you had the value `false` you can update `next.config.js`:
Change `future.webpack5` to `webpack5`.
Current `next.config.js`:
```js filename="next.config.js"
module.exports = {
future: {
webpack5: false,
},
}
```
Updated `next.config.js`:
```js filename="next.config.js"
module.exports = {
webpack5: false,
}
```

View File

@@ -0,0 +1,11 @@
---
title: '`generateBuildId` did not return a string'
---
## Why This Error Occurred
The most common cause for this issue is a custom `next.config.js` with the `generateBuildId` method defined, but it does not return a string.
## Possible Ways to Fix It
Always return a string from generateBuildId.

View File

@@ -0,0 +1,41 @@
---
title: '`getInitialProps` was defined as an instance method'
---
## Why This Error Occurred
`getInitialProps` must be a static method in order to be called by next.js.
## Possible Ways to Fix It
Use the static keyword.
```jsx filename="pages/example.js"
export default class YourEntryComponent extends React.Component {
static getInitialProps() {
return {}
}
render() {
return 'foo'
}
}
```
or
```jsx filename="pages/example.js"
const YourEntryComponent = function () {
return 'foo'
}
YourEntryComponent.getInitialProps = () => {
return {}
}
export default YourEntryComponent
```
## Useful Links
- [Fetching data and component lifecycle](/docs/pages/api-reference/functions/get-initial-props)

View File

@@ -0,0 +1,17 @@
---
title: '`getInitialProps` Export Warning'
---
## Why This Warning Occurred
You attempted to statically export your application via `output: 'export'` or `next export`, however, one or more of your pages uses `getInitialProps`.
Next.js discourages you to use `getInitialProps` in this scenario.
## Possible Ways to Fix It
Use `getStaticProps` instead for proper SSG support.
## Useful Links
- [`getStaticProps` Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)

View File

@@ -0,0 +1,42 @@
---
title: Google Font Display
---
> Enforce font-display behavior with Google Fonts.
## Why This Error Occurred
For a Google Font, the font-display descriptor was either missing or set to `auto`, `block`, or `fallback`, which are not recommended.
## Possible Ways to Fix It
For most cases, the best font display strategy for custom fonts is `optional`.
```jsx filename="pages/index.js"
import Head from 'next/head'
export default function IndexPage() {
return (
<div>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Krona+One&display=optional"
rel="stylesheet"
/>
</Head>
</div>
)
}
```
Specifying `display=optional` minimizes the risk of invisible text or layout shift. If swapping to the custom font after it has loaded is important to you, then use `display=swap` instead.
### When Not To Use It
If you want to specifically display a font using an `auto`, `block`, or `fallback` strategy, then you can disable this rule.
## Useful Links
- [Controlling Font Performance with font-display](https://developer.chrome.com/blog/font-display/)
- [Google Fonts API Docs](https://developers.google.com/fonts/docs/css2#use_font-display)
- [CSS `font-display` property](https://www.w3.org/TR/css-fonts-4/#font-display-desc)

View File

@@ -0,0 +1,27 @@
---
title: Google Font Preconnect
---
> **Note**: Next.js automatically adds `<link rel="preconnect" />` after version `12.0.1`.
> Ensure `preconnect` is used with Google Fonts.
## Why This Error Occurred
A preconnect resource hint was not used with a request to the Google Fonts domain. Adding `preconnect` is recommended to initiate an early connection to the origin.
## Possible Ways to Fix It
Add `rel="preconnect"` to the Google Font domain `<link>` tag:
```jsx filename="pages/_document.js"
<link rel="preconnect" href="https://fonts.gstatic.com" />
```
> **Note**: a **separate** link with `dns-prefetch` can be used as a fallback for browsers that don't support `preconnect` although this is not required.
## Useful Links
- [Preconnect to required origins](https://web.dev/uses-rel-preconnect/)
- [Preconnect and dns-prefetch](https://web.dev/preconnect-and-dns-prefetch/#resolve-domain-name-early-with-reldns-prefetch)
- [Next.js Font Optimization](/docs/pages/api-reference/components/font)

View File

@@ -0,0 +1,32 @@
---
title: 'Missing specified subset for a `next/font/google` font'
---
## Why This Error Occurred
Preload is enabled for a font that is missing a specified subset.
## Possible Ways to Fix It
### Specify which subsets to preload for that font.
```js filename="example.js"
const inter = Inter({ subsets: ['latin'] })
```
> **Note**: previously it was possible to specify default subsets in your `next.config.js` with the `experimental.fontLoaders` option, but this is no longer supported.
### Disable preloading for that font
If it's not possible to preload your intended subset you can disable preloading.
```js filename="example.js"
const notoSansJapanese = Noto_Sans_JP({
weight: '400',
preload: false,
})
```
## Useful Links
- [Specifying a subset](/docs/pages/api-reference/components/font#specifying-a-subset)

View File

@@ -0,0 +1,15 @@
---
title: Redirect During getStaticProps Prerendering
---
## Why This Error Occurred
The `redirect` value was returned from `getStaticProps` during prerendering which is invalid.
## Possible Ways to Fix It
Remove any paths that result in a redirect from being prerendered in `getStaticPaths` and enable `fallback: true` to handle redirecting for these pages.
## Useful Links
- [Data Fetching Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)

View File

@@ -0,0 +1,49 @@
---
title: '`getStaticProps` / `getServerSideProps` can not be attached to the page component'
---
## Why This Error Occurred
On one of your page's components you attached either `getStaticProps`, `getStaticPaths`, or `getServerSideProps` as a member instead of as a separate export.
These methods can not be attached in the same way as `getInitialProps` and must be their own export
## Possible Ways to Fix It
Move the method to it's own export from your page.
**Before**
```jsx filename="pages/index.js"
function Page(props) {
return <p>hello world</p>
}
Page.getStaticProps = () => ({
props: {
hello: 'world',
},
})
export default Page
```
**After**
```jsx filename="pages/index.js"
function Page(props) {
return <p>hello world</p>
}
export default Page
export const getStaticProps = () => ({
props: {
hello: 'world',
},
})
```
## Useful Links
- [Data Fetching Docs](/docs/pages/building-your-application/data-fetching)

52
errors/gssp-export.mdx Normal file
View File

@@ -0,0 +1,52 @@
---
title: '`getServerSideProps` Export Error'
---
## Why This Error Occurred
You attempted to statically export your application via `output: 'export'` or `next export`, however, one or more of your pages uses `getServerSideProps`.
It is not possible to use `getServerSideProps` without a server, so you'll need to use `next start` when self hosting or deploy to a provider like [Vercel](https://vercel.com).
## Possible Ways to Fix It
1. If you'd like to keep your application static, you can use `getStaticProps` instead of `getServerSideProps`.
2. If you want to use server-side rendering, update your build command and remove `output: 'export'` and remove `next export`. For example, in your `package.json`:
```diff
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"scripts": {
"dev": "next dev",
- "build": "next build && next export",
+ "build": "next build",
"start": "next start"
}
}
```
```diff
--- a/next.config.js
+++ b/next.config.js
@@ -1,4 +1,4 @@
{
module.exports = {
reactStrictMode: true,
- output: "export",
}
}
```
> **Note**:
>
> - Removing export does not mean your entire application is no longer static.
> - Pages that use `getStaticProps` or [no lifecycle](/docs/pages/building-your-application/rendering/automatic-static-optimization) **will still be static**!
## Useful Links
- [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization)
- [`getStaticProps` documentation](/docs/pages/building-your-application/data-fetching/get-static-props)
- [`exportPathMap` documentation](/docs/pages/api-reference/config/next-config-js/exportPathMap)

View File

@@ -0,0 +1,18 @@
---
title: 'Mixed `notFound` and `redirect`'
---
## Why This Error Occurred
In one of your page's `getStaticProps` or `getServerSideProps` `notFound` and `redirect` values were both returned.
These values can not both be returned at the same time and one or the other needs to be returned at a time.
## Possible Ways to Fix It
Make sure only `notFound` **or** `redirect` is being returned on your page's `getStaticProps` or `getServerSideProps`
## Useful Links
- [`getStaticProps` Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)
- [`getServerSideProps` Documentation](/docs/pages/building-your-application/data-fetching/get-server-side-props)

View File

@@ -0,0 +1,21 @@
---
title: 'Must not access ServerResponse after `getServerSideProps` resolves'
---
## Why This Error Occurred
`getServerSideProps()` surfaces a `ServerResponse` object through the `res` property of its `context` arg. This object is not intended to be accessed or changed after `getServerSideProps()` resolves.
This is because the framework tries to optimize when items like headers or status codes are flushed to the browser. If they are changed after `getServerSideProps()` completes, we can't guarantee that the changes will work.
For this reason, accessing the object after this time is disallowed.
## Possible Ways to Fix It
You can fix this error by moving any access of the `res` object into `getServerSideProps()` itself or any functions that run before `getServerSideProps()` returns.
If youre using a custom server and running into this problem due to session proxy like `next-session` or `express-session`, try installing the proxy in the server instead of `getServerSideProps()`.
## Useful Links
- [Data Fetching Docs](/docs/pages/building-your-application/data-fetching)

12
errors/head-build-id.mdx Normal file
View File

@@ -0,0 +1,12 @@
---
title: 'Failed to load `BUILD_ID` from Server'
---
## Why This Error Occurred
The deployment was generated incorrectly or the server was overloaded at the time of the request.
## Possible Ways to Fix It
Please make sure you are using the latest version of the `@vercel/next` builder in your `vercel.json`.
If this error persists, please file a bug report.

View File

@@ -0,0 +1,56 @@
---
title: '`href` Interpolation Failed'
---
## Why This Error Occurred
Somewhere you are utilizing the `next/link` component, `Router#push`, or `Router#replace` with `href` interpolation to build dynamic routes but did not provide all of the needed dynamic route params to properly interpolate the `href`.
> **Note**: this error will only show when the `next/link` component is clicked not when only rendered.
**Invalid `href` interpolation**
```jsx filename="blog-link.js"
import Link from 'next/link'
export default function BlogLink() {
return (
<Link
href={{
pathname: '/blog/[post]/[comment]',
query: { post: 'post-1' },
}}
>
<a>Invalid link</a>
</Link>
)
}
```
**Valid `href` interpolation**
```jsx filename="blog-link.js"
import Link from 'next/link'
export default function BlogLink() {
return (
<Link
href={{
pathname: '/blog/[post]/[comment]',
query: { post: 'post-1', comment: 'comment-1' },
}}
>
<a>Valid link</a>
</Link>
)
}
```
## Possible Ways to Fix It
Look for any usage of the `next/link` component, `Router#push`, or `Router#replace` and make sure that the provided `href` has all needed dynamic params in the query.
## Useful Links
- [Routing section in Documentation](/docs/pages/building-your-application/routing)
- [Dynamic routing section in Documentation](/docs/pages/building-your-application/routing/dynamic-routes)

View File

@@ -0,0 +1,11 @@
---
title: '`ignored-compiler-options`'
---
## Why This Error Occurred
Options under the `compiler` key in `next.config.js` only apply to the new Rust based compiler and will be ignored if Babel is used instead. This message will appear if Next.js detects a Babel configuration file while `compiler` options are configured in `next.config.js`
## Useful Links
- [Next.js Compiler](/docs/architecture/nextjs-compiler)

View File

@@ -0,0 +1,21 @@
---
title: ESM packages need to be imported
---
## Why This Error Occurred
Packages in node_modules that are published as EcmaScript Module, need to be `import`ed via `import ... from 'package'` or `import('package')`.
You get this error when using a different way to reference the package, e. g. `require()`.
## Possible Ways to Fix It
1. Use `import` or `import()` to reference the package instead. (Recommended)
2. If you are already using `import`, make sure that this is not changed by a transpiler, e. g. TypeScript or Babel.
3. Switch to loose mode (`experimental.esmExternals: 'loose'`), which tries to automatically correct this error.
## Useful Links
- [Node.js ESM require docs](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html#esm_require)

19
errors/import-next.mdx Normal file
View File

@@ -0,0 +1,19 @@
---
title: 'Invalid `next` Import'
---
## Why This Error Occurred
Somewhere in your application, you imported `next` directly which is only meant to be used with legacy custom servers.
You should not import `next` inside of pages or components.
## Possible Ways to Fix It
Ensure any usage of `import next from "next"` is specific to custom server usage and isn't included in your pages or components.
Also ensure any type imports are kept inside of TypeScript files e.g. ensure `import { PageConfig } from 'next'` isn't used in JavaScript files.
## Useful Links
- [Custom Server Documentation](/docs/pages/guides/custom-server)

View File

@@ -0,0 +1,22 @@
---
title: 'Improper webpack `devtool` used in development mode'
---
## Why This Error Occurred
Next.js chooses the most optimal `devtool` for use with webpack. Changing the `devtool` in development mode will cause severe performance regressions with your application.
## Possible Ways to Fix It
Please remove the custom `devtool` override or only apply it to production builds in your `next.config.js`.
```js filename="next.config.js"
module.exports = {
webpack: (config, options) => {
if (!options.dev) {
config.devtool = options.isServer ? false : 'your-custom-devtool'
}
return config
},
}
```

View File

@@ -0,0 +1,50 @@
---
title: 'Incompatible `href` and `as` values'
---
## Why This Error Occurred
Somewhere you are utilizing the `next/link` component, `Router#push`, or `Router#replace` with a dynamic route in your `href` that has an incompatible `as` value. The `as` value is incompatible when the path doesn't provide only the expected parameters for the dynamic route.
> **Note**: this error will only show when the `next/link` component is clicked not when only rendered.
**Incompatible `href` and `as`**
```jsx filename="pages/blog.js"
import Link from 'next/link'
export default function Page(props) {
return (
<>
<Link href="/[post]" as="/post-1/comments">
<a>Invalid link</a>
</Link>
</>
)
}
```
**Compatible `href` and `as`**
```jsx filename="pages/blog.js"
import Link from 'next/link'
export default function Page(props) {
return (
<>
<Link href="/[post]" as="/post-1">
<a>Valid link</a>
</Link>
</>
)
}
```
## Possible Ways to Fix It
Look for any usage of the `next/link` component, `Router#push`, or `Router#replace` and make sure that the provided `href` and `as` values are compatible
## Useful Links
- [Routing section in Documentation](/docs/pages/building-your-application/routing)
- [Dynamic routing section in Documentation](/docs/pages/building-your-application/routing/dynamic-routes)

View File

@@ -0,0 +1,30 @@
---
title: Inline script id
---
> Enforce `id` attribute on `next/script` components with inline content.
## Why This Error Occurred
`next/script` components with inline content require an `id` attribute to be defined to track and optimize the script.
## Possible Ways to Fix It
Add an `id` attribute to the `next/script` component.
```jsx filename="pages/_app.js"
import Script from 'next/script'
export default function App({ Component, pageProps }) {
return (
<>
<Script id="my-script">{`console.log('Hello world!');`}</Script>
<Component {...pageProps} />
</>
)
}
```
## Useful links
- [Docs for Next.js Script component](/docs/pages/guides/scripts)

21
errors/install-sass.mdx Normal file
View File

@@ -0,0 +1,21 @@
---
title: 'Install `sass` to Use Built-In Sass Support'
---
## Why This Error Occurred
Using Next.js' [built-in Sass support](/docs/pages/guides/sass) requires that you bring your own version of Sass.
## Possible Ways to Fix It
Please install the `sass` package in your project.
```bash filename="Terminal"
npm i sass
# or
yarn add sass
```
## Useful Links
- [Sass Support in Documentation](/docs/pages/guides/sass)

39
errors/install-sharp.mdx Normal file
View File

@@ -0,0 +1,39 @@
---
title: 'Install `sharp` to Use Built-In Image Optimization'
---
## Why This Error Occurred
Using Next.js' built-in [Image Optimization](/docs/pages/api-reference/components/image) requires [sharp](https://www.npmjs.com/package/sharp) as a dependency.
You are seeing this error because your OS was unable to [install sharp](https://sharp.pixelplumbing.com/install) properly, either using pre-built binaries or building from source.
## Possible Ways to Fix It
Option 1: Use a different version of Node.js and try to install `sharp` again.
```bash filename="Terminal"
npm i sharp
```
```bash filename="Terminal"
yarn add sharp
```
```bash filename="Terminal"
pnpm add sharp
```
```bash filename="Terminal"
bun add sharp
```
Option 2: Try installing the wasm variant of `sharp` by running `npm install --cpu=wasm32 sharp`.
Option 3: If using macOS, ensure XCode Build Tools are installed and try to install `sharp` again.
For example, see [macOS Catalina instructions](https://github.com/nodejs/node-gyp/blob/66c0f0446749caa591ad841cd029b6d5b5c8da42/macOS_Catalina.md).
Option 4: Use a different OS and try to install `sharp` again.
For example, if you're using Windows, try using [WSL](https://docs.microsoft.com/en-us/windows/wsl/about) (Windows Subsystem for Linux).

View File

@@ -0,0 +1,34 @@
---
title: Invalid API Route Status/Body Response
---
## Why This Error Occurred
In one of your API routes a 204 or 304 status code was used as well as sending a response body.
This is invalid as a 204 or 304 status code dictates no response body should be present.
## Possible Ways to Fix It
Send an empty body when using a 204 or 304 status code or use a different status code while sending a response body.
Before
```js filename="pages/api/example.js"
export default function handler(req, res) {
res.status(204).send('invalid body')
}
```
After
```js filename="pages/api/example.js"
export default function handler(req, res) {
res.status(204).end()
}
```
## Useful Links
- [204 status code documentation](https://developer.mozilla.org/docs/Web/HTTP/Status/204)
- [304 status code documentation](https://developer.mozilla.org/docs/Web/HTTP/Status/304)

View File

@@ -0,0 +1,19 @@
---
title: 'Invalid `assetPrefix`'
---
## Why This Error Occurred
The value of `assetPrefix` in `next.config.js` is set to something that is not a `string`.
## Possible Ways to Fix It
Ensure that `assetPrefix` is a `string`.
Example:
```js filename="next.config.js"
module.exports = {
assetPrefix: '/',
}
```

View File

@@ -0,0 +1,33 @@
---
title: 'Invalid options type in a `next/dynamic` call'
---
## Why This Error Occurred
You have an invalid options type in a `next/dynamic` call. The options must be an object literal.
## Possible Ways to Fix It
**Before**
```jsx filename="example.js"
import dynamic from 'next/dynamic'
const options = { loading: () => <p>...</p>, ssr: false }
const DynamicComponent = dynamic(() => import('../components/hello'), options)
```
**After**
```jsx filename="example.js"
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/hello'), {
loading: () => <p>...</p>,
ssr: false,
})
```
## Useful Links
- [Dynamic Import](/docs/pages/guides/lazy-loading)

View File

@@ -0,0 +1,33 @@
---
title: 'Invalid Usage of `suspense` Option of `next/dynamic`'
---
## Why This Error Occurred
- You are using `{ suspense: true }` with React version older than 18.
- You are using `{ suspense: true, ssr: false }`.
- You are using `{ suspense: true, loading }`.
## Possible Ways to Fix It
**If you are using `{ suspense: true }` with React version older than 18**
- You can try upgrading to React 18 or newer
- If upgrading React is not an option, remove `{ suspense: true }` from `next/dynamic` usages.
**If you are using `{ suspense: true, ssr: false }`**
Next.js will use `React.lazy` when `suspense` is set to true. React 18 or newer will always try to resolve the Suspense boundary on the server. This behavior can not be disabled, thus the `ssr: false` is ignored with `suspense: true`.
- You should write code that works in both client-side and server-side.
- If rewriting the code is not an option, remove `{ suspense: true }` from `next/dynamic` usages.
**If you are using `{ suspense: true, loading }`**
Next.js will use `React.lazy` when `suspense` is set to true, when your dynamic-imported component is loading, React will use the closest suspense boundary's fallback.
You should remove `loading` from `next/dynamic` usages, and use `<Suspense />`'s `fallback` prop.
## Useful Links
- [Dynamic Import Suspense Usage](/docs/pages/guides/lazy-loading#nextdynamic)

View File

@@ -0,0 +1,15 @@
---
title: Invalid External Rewrite
---
## Why This Error Occurred
A rewrite was defined with both `basePath: false` and an internal `destination`. Rewrites that capture urls outside of the `basePath` must route externally, as they are intended for proxying in the case of incremental adoption of Next.js in a project.
## Possible Ways to Fix It
Look for any rewrite where `basePath` is `false` and make sure its `destination` starts with `http://` or `https://`.
## Useful Links
- [Rewrites section in Documentation](/docs/pages/api-reference/config/next-config-js/rewrites)

View File

@@ -0,0 +1,23 @@
---
title: 'Invalid `getServerSideProps` Return Value'
---
## Why This Error Occurred
In one of the page's `getServerSideProps` the return value had the incorrect shape.
## Possible Ways to Fix It
Make sure to return the following shape from `getServerSideProps`:
```tsx filename="pages/example.tsx"
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
return {
props: { [key: string]: any }
}
}
```
## Useful Links
- [getServerSideProps](/docs/pages/api-reference/functions/get-server-side-props)

View File

@@ -0,0 +1,50 @@
---
title: 'Invalid `getStaticPaths` Return Value'
---
## Why This Error Occurred
In one of the page's `getStaticPaths` the return value had the incorrect shape.
## Possible Ways to Fix It
Make sure to return the following shape from `getStaticPaths`:
```js filename="pages/blog/[slug].js"
export async function getStaticPaths() {
return {
paths: Array<string | { params: { [key: string]: string } }>,
fallback: boolean
}
}
```
There are two required properties:
### `paths`
This property is an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) of URLs ("paths") that should be statically generated at build-time. The returned paths must match the dynamic route shape.
- You may return a [String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) or an [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) that explicitly defines all URL `params`.
```js filename="pages/blog/[slug].js"
export async function getStaticPaths() {
return {
paths: [
// String variant:
'/blog/first-post',
// Object variant:
{ params: { slug: 'second-post' } },
],
fallback: true,
}
}
```
### `fallback`
This property can be a [Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean), specifying whether or not a fallback version of this page should be generated, or a string `'blocking'` to wait for the generation:
- Enabling `fallback` (via `true`) allows you to return a subset of all the possible paths that should be statically generated. At runtime, Next.js will statically generate the remaining paths the **first time they are requested**. Consecutive calls to the path will be served as-if it was statically generated at build-time. This reduces build times when dealing with thousands or millions of pages.
- Disabling `fallback` (via `false`) requires you return the full collection of paths you would like to statically generate at build-time. At runtime, any path that was not generated at build-time **will 404**.
- If `fallback` is `'blocking'`, new paths not returned by getStaticPaths will wait for the HTML to be generated, identical to SSR (hence why blocking), and then be cached for future requests so it only happens once per path.

View File

@@ -0,0 +1,27 @@
---
title: 'Invalid `getStaticProps` Return Value'
---
## Why This Error Occurred
In one of the page's `getStaticProps` the return value had the incorrect shape.
## Possible Ways to Fix It
Make sure to return the following shape from `getStaticProps`:
```tsx filename="pages/example.tsx"
export async function getStaticProps(ctx: {
params?: ParsedUrlQuery;
preview?: boolean;
previewData?: PreviewData;
}) {
return {
props: { [key: string]: any }
}
}
```
## Useful Links
- [`getStaticProps` Documentation](/docs/pages/api-reference/functions/get-static-props)

View File

@@ -0,0 +1,20 @@
---
title: 'Invalid `href` passed to router'
---
## Why This Error Occurred
Next.js provides a router which can be utilized via a component imported via `next/link`, a wrapper `withRouter(Component)`, and now a hook `useRouter()`.
When using any of these, it is expected they are only used for internal navigation, i.e. navigating between pages in the same Next.js application.
Either you passed a non-internal `href` to a `next/link` component or you called `Router#push` or `Router#replace` with one.
Invalid `href`s include external sites (https://google.com) and `mailto:` links. In the past, usage of these invalid `href`s could have gone unnoticed, but since they can cause unexpected behavior we now show a warning in development for them.
## Possible Ways to Fix It
Look for any usage of `next/link` or `next/router` that is being passed a non-internal `href` and replace them with either an anchor tag (`<a>`) or `window.location.href = YOUR_HREF`.
## Useful Links
- [Routing section in Documentation](/docs/pages/building-your-application/routing)

View File

@@ -0,0 +1,46 @@
---
title: Invalid i18n config
---
## Why This Error Occurred
In your `next.config.js` file, you provided an invalid config for the `i18n` field. This could mean the limit for 100 locale items was exceeded.
## Possible Ways to Fix It
Make sure your `i18n` field follows the allowed config shape, limits, and values:
```js filename="next.config.js"
module.exports = {
i18n: {
// These are all the locales you want to support in
// your application
locales: ['en-US', 'es', 'fr', 'nl-NL'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'en-US',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
domains: [
{
domain: 'example.com',
defaultLocale: 'en-US',
// other locales that should be handled on this domain
locales: ['es'],
},
{
domain: 'example.nl',
defaultLocale: 'nl-NL',
},
{
domain: 'example.fr',
defaultLocale: 'fr',
},
],
},
}
```
## Useful Links
- [Internationalized Routing Documentation](/docs/pages/guides/internationalization)

View File

@@ -0,0 +1,55 @@
---
title: 'Invalid `images` config'
---
## Why This Error Occurred
In your `next.config.js` file, you provided an invalid config for the `images` field.
## Possible Ways to Fix It
Make sure your `images` field follows the allowed config shape and values:
```js filename="next.config.js"
module.exports = {
images: {
// limit of 25 deviceSizes values
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
// limit of 25 imageSizes values
imageSizes: [32, 48, 64, 96, 128, 256, 384],
// limit of 50 domains values (deprecated)
domains: [],
// path prefix for Image Optimization API, useful with `loader`
path: '/_next/image',
// loader can be 'default', 'imgix', 'cloudinary', 'akamai', or 'custom'
loader: 'default',
// file with `export default function loader({src, width, quality})`
loaderFile: '',
// disable static imports for image files
disableStaticImages: false,
// minimumCacheTTL is in seconds, must be integer 0 or more
minimumCacheTTL: 14400, // 4 hours
// ordered list of acceptable optimized image formats (mime types)
formats: ['image/webp'],
// enable dangerous use of SVG images
dangerouslyAllowSVG: false,
// set the Content-Security-Policy header
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// sets the Content-Disposition header ('inline' or 'attachment')
contentDispositionType: 'attachment',
// limit of 25 objects
localPatterns: [],
// limit of 50 objects
remotePatterns: [],
// limit of 20 integers
qualities: [25, 50, 75],
// when true, every image will be unoptimized
unoptimized: false,
},
}
```
## Useful Links
- [Image Optimization Documentation](/docs/pages/api-reference/components/image)
- [`next/image` Documentation](/docs/pages/api-reference/components/image)

View File

@@ -0,0 +1,39 @@
---
title: Invalid Instant Configuration
---
## Why This Message Occurred
You provided an invalid configuration for `export const unstable_instant` in a Layout or Page file.
### Example of Correct Usage
#### Static Prefetching
```tsx filename="app/.../layout.tsx"
export const unstable_instant = {
prefetch: 'static',
}
```
#### Runtime Prefetching
```tsx filename="app/[slug]/page.tsx"
export const unstable_instant = {
prefetch: 'runtime',
samples: [
{
cookies: [{ name: 'experiment', value: 'A' }],
params: { slug: 'example' },
},
],
}
```
#### Indicating that there is no instant UI
This does not disable prefetching.
```tsx filename="app/[slug]/page.tsx"
export const unstable_instant = false
```

View File

@@ -0,0 +1,29 @@
---
title: Invalid Multi-match
---
## Why This Error Occurred
In one of your custom-routes you specified a multi-match `/:path*` and used it in your `destination` without adding the `*` in your `destination` e.g. `destination: '/another/:path'`
## Possible Ways to Fix It
Add `*` to your usage of the multi-match param in your `destination`.
**Before**
```js
{
source: '/:path*',
destination: '/another/:path'
}
```
**After**
```js
{
source: '/:path*',
destination: '/another/:path*'
}
```

View File

@@ -0,0 +1,21 @@
---
title: 'Invalid `<Link>` with `<a>` child'
---
## Why This Error Occurred
Starting with Next.js 13, `<Link>` renders as `<a>`, so attempting to use `<a>` as a child is invalid.
## Possible Ways to Fix It
Run the `new-link` codemod to automatically upgrade previous versions of Next.js to the new `<Link>` usage:
```bash filename="Terminal"
npx @next/codemod new-link .
```
This will change `<Link><a id="link">Home</a></Link>` to `<Link id="link">Home</Link>`.
## Useful Links
- [next/link](/docs/pages/api-reference/components/link)

View File

@@ -0,0 +1,47 @@
---
title: 'Invalid `next.config.js`'
---
## Why this error occurred
In your `next.config.js` file, you passed invalid options that either are the incorrect type or an unknown field. This warning is shown to help catch typos, deprecated or updated options.
## Possible ways to fix it
You can use the `NextConfig` type to help ensure your config is correct.
```js filename="next.config.js"
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
module.exports = nextConfig
```
Alternatively, you can use `next.config.ts` for better type safety and auto-completion:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
/* config options here */
}
export default nextConfig
```
### Deprecated or updated options
Some configuration options have been removed or updated in recent versions of Next.js. For example:
- `eslint` configuration option has been removed from `next.config`. Remove the `eslint` option and use the ESLint CLI instead. See the [ESLint](/docs/app/api-reference/config/eslint) documentation.
- `experimental.turbo` configuration has moved to a top-level `turbopack` configuration. See the [`turbopack` option](/docs/app/api-reference/config/next-config-js/turbopack) documentation.
See the [`next.config.js` docs](/docs/app/api-reference/config/next-config-js) for a list of all available and legacy options.
## Useful links
- [`next.config.js`](/docs/pages/api-reference/config/next-config-js)

View File

@@ -0,0 +1,90 @@
---
title: Invalid Page / API Route Config
---
## Why This Error Occurred
In one of your pages or API Routes, you used `export const config` with an invalid value.
## Possible Ways to Fix It
- The page's `config` must be an object initialized directly when being exported and not modified dynamically.
- The `config` object must only contain static constant literals without expressions.
<table>
<thead>
<tr>
<th>Not Allowed</th>
<th>Allowed</th>
</tr>
</thead>
<tbody>
<tr>
<td>
```js
// `config` should be an object
export const config = 'hello world'
```
</td>
<td>
```js
export const config = {}
```
</td>
</tr>
<tr>
<td>
```js
// `config.runtime` contains a dynamic expression
export const config = {
runtime: `node${'js'}`,
}
```
</td>
<td>
```js
export const config = {
runtime: 'nodejs',
}
export const config = {
runtime: `edge`,
}
```
</td>
</tr>
<tr>
<td>
```js
// Re-exported `config` is not allowed
export { config } from '../config'
```
</td>
<td>
```js
export const config = {}
```
</td>
</tr>
</tbody>
</table>
## Useful Links
- [API Routes Request Helpers](/docs/pages/building-your-application/routing/api-routes)
- [Edge Runtime](/docs/app/api-reference/edge)

View File

@@ -0,0 +1,18 @@
---
title: Invalid Project Directory Casing
---
## Why This Error Occurred
When starting Next.js, the current directory is a different casing than the actual directory on your filesystem. This can cause files to resolve inconsistently.
This can occur when using a case-insensitive filesystem. For example, opening PowerShell on Windows navigating to `cd path/to/myproject` instead of `cd path/to/MyProject`.
## Possible Ways to Fix It
Ensure the casing for the current working directory matches the actual case of the real directory. Use a terminal that enforces case-sensitivity.
## Useful Links
- [Next.js CLI documentation](/docs/pages/api-reference/cli/next)
- [Case sensitivity in filesystems](https://en.wikipedia.org/wiki/Case_sensitivity#In_filesystems)

View File

@@ -0,0 +1,11 @@
---
title: Invalid React Version
---
## Why This Error Occurred
You tried running `next` in a project with an incompatible react version. Next.js uses certain react features that when are unavailable show this error since it can't work without them.
## Possible Ways to Fix It
Run `npm i react@latest react-dom@latest` or `yarn add react@latest react-dom@latest` in your project and then try running `next` again.

View File

@@ -0,0 +1,70 @@
---
title: 'Invalid Redirect `getStaticProps` / `getServerSideProps`'
---
## Why This Error Occurred
The `redirect` value returned from your `getStaticProps` or `getServerSideProps` function had invalid values.
## Possible Ways to Fix It
Make sure you return the proper values for the `redirect` value.
```tsx filename="pages/index.tsx" switcher
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
if (!repo) {
return {
redirect: {
permanent: false, // or true
destination: '/404',
},
}
}
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}
```
```jsx filename="pages/index.js" switcher
export async function getStaticPaths() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
if (!repo) {
return {
redirect: {
permanent: false, // or true
destination: '/404',
},
}
}
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}
```
## Useful Links
- [Data Fetching Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)

View File

@@ -0,0 +1,49 @@
---
title: 'Invalid relative `href` and external `as` values'
---
## Why This Error Occurred
Somewhere you are utilizing the `next/link` component, `Router#push`, or `Router#replace` with a relative route in your `href` that has an external `as` value. The `as` value must be relative also or only `href` should be used with an external URL.
> **Note**: this error will only show when the `next/link` component is clicked not when only rendered.
**Incompatible `href` and `as`**
```jsx filename="pages/example.js"
import Link from 'next/link'
export default function Page(props) {
return (
<>
<Link href="/invalid" as="mailto:john@example.com">
<a>Invalid link</a>
</Link>
</>
)
}
```
**Compatible `href` and `as`**
```jsx filename="pages/example.js"
import Link from 'next/link'
export default function Page(props) {
return (
<>
<Link href="mailto:john@example.com">
<a>Invalid link</a>
</Link>
</>
)
}
```
## Possible Ways to Fix It
Look for any usage of the `next/link` component, `Router#push`, or `Router#replace` and make sure that the provided `href` and `as` values are compatible
## Useful Links
- [Routing section in Documentation](/docs/pages/building-your-application/routing)

View File

@@ -0,0 +1,24 @@
---
title: 'Invalid `webpack` resolve alias'
---
## Why This Error Occurred
When overriding `config.resolve.alias` incorrectly in `next.config.js` webpack will throw an error because private-next-pages is not defined.
## Possible Ways to Fix It
This is not a bug in Next.js, it's related to the user adding a custom webpack(config) config to next.config.js and overriding internals by not applying Next.js' aliases. Solution would be:
```js filename="next.config.js"
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
// your aliases
}
}
```
## Useful Links
- [Related issue](https://github.com/vercel/next.js/issues/6681)

View File

@@ -0,0 +1,56 @@
---
title: 'Invalid Custom Route `source`'
---
## Why This Error Occurred
A pattern could not be parsed when defining custom routes or a proxy `matcher`.
This could have been due to trying to use normal `RegExp` syntax like negative lookaheads (`?!exclude`) without following [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp)'s syntax.
## Possible Ways to Fix It
Wrap the `RegExp` part of your `source` as an un-named parameter.
### Custom Routes
**Before**
```js
{
source: '/feedback/(?!general)',
destination: '/feedback/general'
}
```
**After**
```js
{
source: '/feedback/((?!general).*)',
destination: '/feedback/general'
}
```
### Proxy
**Before**
```ts filename="proxy.ts"
const config = {
matcher: '/feedback/(?!general)',
}
```
**After**
```ts filename="proxy.ts"
const config = {
matcher: '/feedback/((?!general).*)',
}
```
## Useful Links
- [path-to-regexp](https://github.com/pillarjs/path-to-regexp)
- [un-named parameters](https://github.com/pillarjs/path-to-regexp#unnamed-parameters)

40
errors/invalid-script.mdx Normal file
View File

@@ -0,0 +1,40 @@
---
title: Invalid Script
---
## Why This Error Occurred
Somewhere in your application, you are using the `next/script` component without including an inline script or `src` attribute.
## Possible Ways to Fix It
Look for any usage of the `next/script` component and make sure that `src` is provided or an inline script is used.
**Compatible `src` attribute**
```jsx
<Script src="https://example.com/analytics.js" />
```
**Compatible inline script with curly braces**
```jsx
<Script id="show-banner">
{`document.getElementById('banner').classList.remove('hidden')`}
</Script>
```
**Compatible inline script with `dangerouslySetInnerHtml`**
```jsx
<Script
id="show-banner"
dangerouslySetInnerHTML={{
__html: `document.getElementById('banner').classList.remove('hidden')`,
}}
/>
```
## Useful Links
- [Script Component in Documentation](/docs/pages/guides/scripts)

View File

@@ -0,0 +1,13 @@
---
title: Invalid Layout or Page Export
---
## Why This Error Occurred
Your [layout](/docs/app/api-reference/file-conventions/layout) or [page](/docs/app/api-reference/file-conventions/page) inside the app directory exports an invalid field. In these files, you're only allowed to export a default React component, or [Segment Configuration Options](/docs/app/api-reference/file-conventions/route-segment-config) for layout and pages, such as `revalidate`, `generateStaticParams`, etc.
Other custom exports are not allowed to catch misspelt configuration options and prevent conflicts with future options.
## Possible Ways to Fix It
You can create a new file and co-locate it with the page or layout. In the new file, you can export any custom fields and import it from anywhere.

View File

@@ -0,0 +1,27 @@
---
title: It looks like the next instance is being instantiated incorrectly.
---
## Why This Error Occurred
You have passed a null or undefined parameter to the `next()` call.
## Possible Ways to Fix It
Make sure you are passing the variables properly:
```js filename="server.js"
const app = next()
```
And make sure you're passing dev as shown in the examples below:
```js filename="server.js"
const app = next({ dev: boolean })
```
## Useful Links
- [custom-server-express](https://github.com/vercel/next.js/blob/6ca00bfe312c8d3fc5c20d25a9cd8d2741a29332/examples/custom-server-express/server.js#L6)
- [custom-server](https://github.com/vercel/next.js/blob/6ca00bfe312c8d3fc5c20d25a9cd8d2741a29332/examples/custom-server/server.js#L6)
- [custom-server-typescript](https://github.com/vercel/next.js/blob/6ca00bfe312c8d3fc5c20d25a9cd8d2741a29332/examples/custom-server-typescript/server/index.ts#L7)

Some files were not shown because too many files have changed in this diff Show More