docs: Migrate error messages to MDX and App Router. (#52038)

This PR is part of a larger effort to migrate error messages to MDX and
use App Router: https://github.com/vercel/front/pull/23459
This commit is contained in:
Delba de Oliveira 2023-07-05 14:11:16 +01:00 committed by GitHub
parent 394533ff88
commit 44d1a1cb15
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
227 changed files with 2096 additions and 2595 deletions

File diff suppressed because one or more lines are too long

View file

@ -12,9 +12,9 @@ import { setFailed } from '@actions/core'
import type { Node, Data } from 'unist'
/**
* This script validates internal links in /docs including internal, hash,
* source and related links. It does not validate external links.
* 1. Recursively traverses the docs and collects all .mdx files.
* This script validates internal links in /docs and /errors including internal,
* hash, source and related links. It does not validate external links.
* 1. Collects all .mdx files in /docs and /errors.
* 2. For each file, it extracts the content, metadata, and heading slugs.
* 3. It creates a document map to efficiently lookup documents by path.
* 4. It then traverses each document modified in the PR and...
@ -40,18 +40,20 @@ interface Document {
interface Errors {
doc: Document
brokenLinks: string[]
brokenHashes: string[]
brokenSourceLinks: string[]
brokenRelatedLinks: string[]
link: string[]
hash: string[]
source: string[]
related: string[]
}
type ErrorType = Exclude<keyof Errors, 'doc'>
interface Comment {
id: number
}
const DOCS_PATH = '/docs/'
const EXCLUDED_PATHS = ['/docs/messages/']
const ERRORS_PATH = '/errors/'
const EXCLUDED_HASHES = ['top']
const COMMENT_TAG = '<!-- LINK_CHECKER_COMMENT -->'
@ -63,57 +65,28 @@ const sha = pullRequest.head.sha
const slugger = new GithubSlugger()
// Recursively traverses DOCS_PATH and collects all .mdx files
async function getAllMdxFiles(
dir: string,
// Collect the paths of all .mdx files in the passed directories
async function getAllMdxFilePaths(
directoriesToScan: string[],
fileList: string[] = []
): Promise<string[]> {
const files = await fs.readdir(dir)
for (const file of files) {
const filePath = path.join(dir, file)
const stats = await fs.stat(filePath)
if (stats.isDirectory()) {
fileList = await getAllMdxFiles(filePath, fileList)
} else if (path.extname(file) === '.mdx') {
fileList.push(filePath)
for (const dir of directoriesToScan) {
const dirPath = path.join('.', dir)
const files = await fs.readdir(dirPath)
for (const file of files) {
const filePath = path.join(dirPath, file)
const stats = await fs.stat(filePath)
if (stats.isDirectory()) {
fileList = await getAllMdxFilePaths([filePath], fileList)
} else if (path.extname(file) === '.mdx') {
fileList.push(filePath)
}
}
}
return fileList
}
async function getFilesChangedInPR(): Promise<string[]> {
try {
const filesChanged = await octokit.rest.pulls.listFiles({
owner,
repo,
pull_number: pullRequest.number,
})
const mdxFilesChanged = filesChanged.data
.filter(
(file) =>
path.join('/', file.filename).startsWith(DOCS_PATH) &&
file.filename.endsWith('.mdx') &&
(file.status === 'added' || file.status === 'modified')
)
.map((file) => file.filename)
if (mdxFilesChanged.length === 0) {
console.log(
"PR doesn't include any changes to .mdx files within DOCS_PATH."
)
}
return mdxFilesChanged
} catch (error) {
setFailed(`Error fetching files changed in PR: ${error}`)
return []
}
}
// Returns the slugs of all headings in a tree
function getHeadingsFromMarkdownTree(tree: Node<Data>): string[] {
const headings: string[] = []
@ -148,11 +121,30 @@ const markdownProcessor = unified()
}
})
// Github APIs returns `errors/*` and `docs/*` paths
function normalizePath(filePath: string): string {
if (filePath.startsWith(ERRORS_PATH.substring(1))) {
return (
filePath
// Remap repository file path to the next-site url path
// e.g. `errors/example.mdx` -> `docs/messages/example`
.replace(ERRORS_PATH.substring(1), DOCS_PATH.substring(1) + 'messages/')
.replace('.mdx', '')
)
}
return (
path
.relative('.' + DOCS_PATH, filePath)
// Remove prefixed numbers used for ordering from the path
// Remap repository file path to the next-site url path without `/docs/`
// e.g. `docs/01-api/getting-started/index.mdx` -> `api/getting-started`
filePath
// We remove `docs/` to normalize paths between regular links
// e.g. `/docs/api/example` and related/source links e.g `api/example`
// TODO:
// - Fix `next-site` to handle full paths for related/source links
// - Update doc files to use full paths for related/source links
// - Remove this workaround
.replace(DOCS_PATH.substring(1), '')
// Remove prefix numbers used for ordering
.replace(/(\d\d-)/g, '')
.replace('.mdx', '')
.replace('/index', '')
@ -162,8 +154,11 @@ function normalizePath(filePath: string): string {
// use Map for faster lookup
let documentMap: Map<string, Document>
// Create a map of documents with their relative paths as keys and
// Create a map of documents with their paths as keys and
// document content and metadata as values
// The key varies between doc pages and error pages
// error pages: `/docs/messages/example`
// doc pages: `api/example`
async function prepareDocumentMapEntry(
filePath: string
): Promise<[string, Document]> {
@ -172,37 +167,48 @@ async function prepareDocumentMapEntry(
const { content, data } = matter(mdxContent)
const tree = markdownProcessor.parse(content)
const headings = getHeadingsFromMarkdownTree(tree)
const normalizedPath = normalizePath(filePath)
const normalizedUrlPath = normalizePath(filePath)
return [
normalizedPath,
normalizedUrlPath,
{ body: content, path: filePath, headings, ...data },
]
} catch (error) {
setFailed(`Error preparing document map for file ${filePath}: ${error}`)
return ['', {} as Document] // Return a default document
return ['', {} as Document]
}
}
// Checks if the links point to existing documents
function validateInternalLink(errors: Errors, href: string): void {
// split href into link and hash link
// /docs/api/example#heading -> ["api/example", "heading""]
const [link, hash] = href.replace(DOCS_PATH, '').split('#')
const docExists = documentMap.get(link)
if (!docExists) {
errors.brokenLinks.push(`${DOCS_PATH}${link}${hash ? '#' + hash : ''}`)
let foundPage
if (link.startsWith('messages/')) {
// check if error page exists, key is the full url path
// e.g. `docs/messages/example`
foundPage = documentMap.get(DOCS_PATH.substring(1) + link)
} else {
// check if doc page exists, key is the url path without `/docs/`
// e.g. `api/example`
foundPage = documentMap.get(link)
}
if (!foundPage) {
errors.link.push(href)
} else if (hash && !EXCLUDED_HASHES.includes(hash)) {
// Account for documents that pull their content from another document
const sourceDoc = docExists.source
? documentMap.get(docExists.source)
const foundPageSource = foundPage.source
? documentMap.get(foundPage.source)
: undefined
// Check if the hash link points to an existing section within the document
const hashExists = (sourceDoc || docExists).headings.includes(hash)
const hashFound = (foundPageSource || foundPage).headings.includes(hash)
if (!hashExists) {
errors.brokenHashes.push(`${DOCS_PATH}${link}${hash ? '#' + hash : ''}`)
if (!hashFound) {
errors.hash.push(href)
}
}
}
@ -212,14 +218,14 @@ function validateHashLink(errors: Errors, href: string, doc: Document): void {
const hashLink = href.replace('#', '')
if (!EXCLUDED_HASHES.includes(hashLink) && !doc.headings.includes(hashLink)) {
errors.brokenHashes.push(href)
errors.hash.push(href)
}
}
// Checks if the source link points to an existing document
function validateSourceLinks(doc: Document, errors: Errors): void {
if (doc.source && !documentMap.get(doc.source)) {
errors.brokenSourceLinks.push(doc.source)
errors.source.push(doc.source)
}
}
@ -228,7 +234,7 @@ function validateRelatedLinks(doc: Document, errors: Errors): void {
if (doc.related && doc.related.links) {
doc.related.links.forEach((link) => {
if (!documentMap.get(link)) {
errors.brokenRelatedLinks.push(link)
errors.related.push(link)
}
})
}
@ -238,10 +244,10 @@ function validateRelatedLinks(doc: Document, errors: Errors): void {
function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors {
const errors: Errors = {
doc,
brokenLinks: [],
brokenHashes: [],
brokenSourceLinks: [],
brokenRelatedLinks: [],
link: [],
hash: [],
source: [],
related: [],
}
try {
@ -251,10 +257,7 @@ function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors {
if (!href) return
if (
href.startsWith(DOCS_PATH) &&
!EXCLUDED_PATHS.some((excludedPath) => href.startsWith(excludedPath))
) {
if (href.startsWith(DOCS_PATH)) {
validateInternalLink(errors, href)
} else if (href.startsWith('#')) {
validateHashLink(errors, href, doc)
@ -305,37 +308,9 @@ async function updateComment(
}
}
async function createComment(
comment: string,
allErrors: Errors[]
): Promise<string> {
async function createComment(comment: string): Promise<string> {
const isFork = pullRequest.head.repo.fork
if (isFork) {
const errorTableData = allErrors.flatMap((errors) => {
const {
doc,
brokenLinks,
brokenHashes,
brokenSourceLinks,
brokenRelatedLinks,
} = errors
const allBrokenLinks = [
...brokenLinks,
...brokenHashes,
...brokenSourceLinks,
...brokenRelatedLinks,
]
return allBrokenLinks.map((link) => ({
path: doc.path,
link,
}))
})
console.log('This PR introduces broken links to the docs:')
console.table(errorTableData, ['path', 'link'])
setFailed(
'The action could not create a Github comment because it is initiated from a forked repo. View the action logs for a list of broken links.'
)
@ -358,8 +333,12 @@ async function createComment(
}
}
const formatTableRow = (link: string, docPath: string) => {
return `| ${link} | [/${docPath}](https://github.com/vercel/next.js/blob/${sha}/${docPath}) | \n`
const formatTableRow = (
link: string,
errorType: ErrorType,
docPath: string
) => {
return `| ${link} | ${errorType} | [/${docPath}](https://github.com/vercel/next.js/blob/${sha}/${docPath}) | \n`
}
async function updateCheckStatus(
@ -413,14 +392,13 @@ async function updateCheckStatus(
// Main function that triggers link validation across .mdx files
async function validateAllInternalLinks(): Promise<void> {
try {
const allMdxFilePaths = await getAllMdxFiles('.' + DOCS_PATH)
const prMdxFilePaths = await getFilesChangedInPR()
const allMdxFilePaths = await getAllMdxFilePaths([DOCS_PATH, ERRORS_PATH])
documentMap = new Map(
await Promise.all(allMdxFilePaths.map(prepareDocumentMapEntry))
)
const docProcessingPromises = prMdxFilePaths.map(async (filePath) => {
const docProcessingPromises = allMdxFilePaths.map(async (filePath) => {
const doc = documentMap.get(normalizePath(filePath))
if (doc) {
const tree = (await markdownProcessor.process(doc.body)).contents
@ -428,60 +406,41 @@ async function validateAllInternalLinks(): Promise<void> {
} else {
return {
doc: {} as Document,
brokenLinks: [],
brokenHashes: [],
brokenSourceLinks: [],
brokenRelatedLinks: [],
link: [],
hash: [],
source: [],
related: [],
} as Errors
}
})
const allErrors = await Promise.all(docProcessingPromises)
let errorComment =
'Hi there :wave:\n\nIt looks like this PR introduces broken links to the docs, please take a moment to fix them before merging:\n\n| :heavy_multiplication_x: Broken link | :page_facing_up: File | \n| ----------- | ----------- | \n'
let errorsExist = false
let errorRows: string[] = []
const errorTypes: ErrorType[] = ['link', 'hash', 'source', 'related']
allErrors.forEach((errors) => {
const {
doc: { path: docPath },
brokenLinks,
brokenHashes,
brokenSourceLinks,
brokenRelatedLinks,
} = errors
if (brokenLinks.length > 0) {
errorsExist = true
brokenLinks.forEach((link) => {
errorComment += formatTableRow(link, docPath)
})
}
if (brokenHashes.length > 0) {
errorsExist = true
brokenHashes.forEach((hash) => {
errorComment += formatTableRow(hash, docPath)
})
}
if (brokenSourceLinks.length > 0) {
errorsExist = true
brokenSourceLinks.forEach((link) => {
errorComment += formatTableRow(link, docPath)
})
}
if (brokenRelatedLinks.length > 0) {
errorsExist = true
brokenRelatedLinks.forEach((link) => {
errorComment += formatTableRow(link, docPath)
})
}
errorTypes.forEach((errorType) => {
if (errors[errorType].length > 0) {
errorsExist = true
errors[errorType].forEach((link) => {
errorRows.push(formatTableRow(link, errorType, docPath))
})
}
})
})
errorComment += '\nThank you :pray:'
const errorComment = [
'Hi there :wave:\n\nIt looks like this PR introduces broken links to the docs, please take a moment to fix them before merging:\n\n| Broken link | Type | File | \n| ----------- | ----------- | ----------- | \n',
...errorRows,
'\nThank you :pray:',
].join('')
const botComment = await findBotComment()
@ -492,13 +451,26 @@ async function validateAllInternalLinks(): Promise<void> {
if (botComment) {
commentUrl = await updateComment(comment, botComment)
} else {
commentUrl = await createComment(comment, allErrors)
commentUrl = await createComment(comment)
}
} else {
const errorTableData = allErrors.flatMap((errors) => {
const { doc } = errors
return errorTypes.flatMap((errorType) =>
errors[errorType].map((link) => ({
docPath: doc.path,
errorType,
link,
}))
)
})
console.log('This PR introduces broken links to the docs:')
console.table(errorTableData, ['link', 'type', 'docPath'])
} else if (botComment) {
const comment = `${COMMENT_TAG}\nAll broken links are now fixed, thank you!`
if (botComment) {
commentUrl = await updateComment(comment, botComment)
}
commentUrl = await updateComment(comment, botComment)
}
try {

View file

@ -3,6 +3,7 @@ on:
pull_request:
paths:
- 'docs/**.mdx'
- 'errors/*.mdx'
jobs:
link-check:

View file

@ -339,7 +339,7 @@ export default function Image() {}
This example uses the `params` object and external data to generate the image.
> **Good to know**:
> By default, this generated image will be [statically optimized](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
> By default, this generated image will be [statically optimized](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/server'

View file

@ -54,7 +54,7 @@ The `context` parameter is an object containing the following keys:
| `query` | An object representing the query string, including dynamic route parameters. |
| `preview` | (Deprecated for `draftMode`) `preview` is `true` if the page is in the [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) and `false` otherwise. |
| `previewData` | (Deprecated for `draftMode`) The [preview](/docs/pages/building-your-application/configuring/preview-mode) data set by `setPreviewData`. |
| `draftMode` | `draftMode` is `true` if the page is in the [Draft Mode](docs/pages/building-your-application/configuring/draft-mode) and `false` otherwise. |
| `draftMode` | `draftMode` is `true` if the page is in the [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) and `false` otherwise. |
| `resolvedUrl` | A normalized version of the request `URL` that strips the `_next/data` prefix for client transitions and includes original query values. |
| `locale` | Contains the active locale (if enabled). |
| `locales` | Contains all supported locales (if enabled). |

View file

@ -51,7 +51,7 @@ The `context` parameter is an object containing the following keys:
| `params` | Contains the route parameters for pages using [dynamic routes](/docs/pages/building-your-application/routing/dynamic-routes). For example, if the page name is `[id].js`, then `params` will look like `{ id: ... }`. You should use this together with `getStaticPaths`, which we'll explain later. |
| `preview` | (Deprecated for `draftMode`) `preview` is `true` if the page is in the [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) and `false` otherwise. |
| `previewData` | (Deprecated for `draftMode`) The [preview](/docs/pages/building-your-application/configuring/preview-mode) data set by `setPreviewData`. |
| `draftMode` | `draftMode` is `true` if the page is in the [Draft Mode](docs/pages/building-your-application/configuring/draft-mode) and `false` otherwise. |
| `draftMode` | `draftMode` is `true` if the page is in the [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) and `false` otherwise. |
| `locale` | Contains the active locale (if enabled). |
| `locales` | Contains all supported locales (if enabled). |
| `defaultLocale` | Contains the configured default locale (if enabled). |

View file

@ -1,15 +1,17 @@
# 404.js Cannot Have getInitialProps
---
title: 404.js Cannot Have getInitialProps
---
#### Why This Error Occurred
## Why This Error Occurred
In your `404.js` page you added `getInitialProps` or `getServerSideProps` which is not allowed as this prevents the page from being static and `404.js` is meant to provide more flexibility for a static 404 page. Having a static 404 page is the most ideal as this page can be served very often and if not static puts extra strain on your server and more invocations for serverless functions which increase the cost of hosting your site unnecessarily.
#### Possible Ways to Fix It
## Possible Ways to Fix It
Remove `getInitialProps` from `404.js` and make sure no HOC's used in `404.js` attach `getInitialProps`.
If you want to fetch data for your `404.js` page move it to a client side fetch inside of `componentDidMount` or `useEffect(() => {}, [])`.
### Useful Links
## Useful Links
- [Automatic Static Optimization](https://nextjs.org/docs/advanced-features/automatic-static-optimization)
- [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization)

View file

@ -1,14 +1,16 @@
# AMP Bind JSX Error
---
title: AMP Bind JSX Error
---
#### Why This Error Occurred
## Why This Error Occurred
Somewhere you used `[prop]='something'` syntax which is not allowed in JSX.
#### Possible Ways to Fix It
## Possible Ways to Fix It
Instead you can use `data-amp-bind-prop='something'` which is a valid AMP alternative
### Useful Links
## Useful Links
- [AMP HTML Specification](https://www.ampproject.org/docs/fundamentals/spec)
- [Possible future syntax](https://github.com/ampproject/amphtml/issues/21600)

View file

@ -1,15 +1,17 @@
# AMP Export Validation
---
title: AMP Export Validation
---
#### Why This Error Occurred
## Why This Error Occurred
During export we validate AMP pages using [amphtml-validator](https://www.npmjs.com/package/amphtml-validator). Errors received from the validator will fail the export.
Validation errors will cause pages to not be [indexed by AMP Caches](https://www.ampproject.org/docs/fundamentals/how_cached).
#### Possible Ways to Fix It
## Possible Ways to Fix It
Look at the error messages and follow their appropriate links to learn more about the error and how to correct the problem.
### Useful Links
## Useful Links
- [AMP HTML Specification](https://www.ampproject.org/docs/fundamentals/spec)

View file

@ -1,14 +1,16 @@
# API Routes Response Size Limited to 4MB
---
title: API Routes Response Size Limited to 4MB
---
#### Why This Error Occurred
## Why This Error Occurred
API Routes are meant to respond quickly and are not intended to support responding with large amounts of data. The maximum size of responses is 4MB.
#### Possible Ways to Fix It
## Possible Ways to Fix It
If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false` inside your API Route.
```js
```js filename="pages/api/example.js"
export const config = {
api: {
responseLimit: false,
@ -19,7 +21,7 @@ export const config = {
`responseLimit` can also take the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`.
This value will be the maximum response size before a warning is displayed. The default value is 4MB.
```js
```js filename="pages/api/example.js"
export const config = {
api: {
responseLimit: '8mb',

View file

@ -1,4 +1,6 @@
# API routes in Static export
---
title: API routes in Static export
---
#### Why This Warning Occurred
@ -6,10 +8,10 @@ An `exportPathMap` path was matched to an API route. Statically exporting a Next
This command is meant for a static-only setup, and is not necessary to make your application static. Pages in your application without server-side data dependencies will be automatically statically exported by `next build`, including pages powered by `getStaticProps`
#### Possible Ways to Fix It
## Possible Ways to Fix It
Use `next build` with platforms that don't require `next export` like https://vercel.com or remove any paths using API routes from your `exportPathMap` in `next.config.js`.
### Useful Links
## Useful Links
- [Static HTML export](https://nextjs.org/docs/advanced-features/static-html-export)
- [Static HTML export](/docs/pages/building-your-application/deploying/static-exports)

View file

@ -1,17 +1,19 @@
# App Container Deprecated
---
title: App Container Deprecated
---
#### Why This Error Occurred
## Why This Error Occurred
In versions prior to v9.0.4 the `<Container>` component was used in `./pages/_app.js` to handle scrolling to hashes.
This handling has been moved up the tree so the `<Container>` component is no longer needed in your custom `<App>`!
#### Possible Ways to Fix It
## Possible Ways to Fix It
Remove the `<Container>` component from your Custom `<App>` (`./pages/_app.js`).
**Before**
```jsx
```jsx filename="pages/_app.js"
import React from 'react'
import App, { Container } from 'next/app'
@ -31,7 +33,7 @@ export default MyApp
**After**
```jsx
```jsx filename="pages/_app.js"
import React from 'react'
import App from 'next/app'

View file

@ -1,14 +1,16 @@
# Dynamic `href` is not supported in the `/app` directory
---
title: 'Dynamic `href` is not supported in the App Router'
---
#### Why This Error Occurred
## Why This Error Occurred
You have tried to use a dynamic `href` with `next/link` in the `app` directory. This is not supported as the new client-side router no longer uses a mapping of dynamic routes -> url, instead it always leverages the url.
#### Possible Ways to Fix It
## Possible Ways to Fix It
**Before**
```jsx
```jsx filename="app/page.js"
<Link
href={{
pathname: '/route/[slug]',
@ -21,16 +23,16 @@ You have tried to use a dynamic `href` with `next/link` in the `app` directory.
Or
```jsx
```jsx filename="app/page.js"
<Link href="/route/[slug]?slug=1">link</Link>
```
**After**
```jsx
```jsx filename="app/page.js"
<Link href="/route/1">link</Link>
```
### Useful Links
## Useful Links
[`next/link` documentation](https://beta.nextjs.org/docs/api-reference/components/link#href)
[`next/link` documentation](/docs/pages/api-reference/components/link#href-required)

View file

@ -1,18 +0,0 @@
# &#x60;app/&#x60; Static to Dynamic Error
#### Why This Error Occurred
Inside of one of your `app/` pages, the page was initially generated statically at build time and then during runtime either a fallback path or path being revalidated attempted to leverage dynamic server values e.g. `cookies()` or `headers()`.
This is a hard error by default as a path generated statically can't switch between types during runtime currently.
#### Possible Ways to Fix It
Prevent usage of these dynamic server values conditionally which can cause the static/dynamic mode of the page to differ between build time and runtime.
Leverage `export const dynamic = 'force-static'` to ensure the page is handled statically regardless of the usage of dynamic server values. Alternatively, if you prefer your page to always be dynamic you can set `export const dynamic = 'force-dynamic'` and it won't attempt to have the page be statically generated.
### Useful Links
- [static/dynamic rendering](https://beta.nextjs.org/docs/rendering/static-and-dynamic-rendering)
- [dynamic server value methods](https://beta.nextjs.org/docs/data-fetching/fetching#server-component-functions)

View file

@ -0,0 +1,20 @@
---
title: 'App Router Static to Dynamic Error'
---
## Why This Error Occurred
Inside one of your `app/` pages, the page was initially generated statically at build time, and then during runtime either a fallback path or path being revalidated attempted to leverage dynamic server values e.g. `cookies()` or `headers()`.
This is a hard error by default as a path generated statically can't switch between types during runtime currently.
## Possible Ways to Fix It
Prevent usage of these dynamic server values conditionally which can cause the static/dynamic mode of the page to differ between build time and runtime.
Leverage `export const dynamic = 'force-static'` to ensure the page is handled statically regardless of the usage of dynamic server values. Alternatively, if you prefer your page to always be dynamic you can set `export const dynamic = 'force-dynamic'` and it won't attempt to have the page be statically generated.
## Useful Links
- [static/dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering)
- [dynamic server value methods](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)

View file

@ -1,14 +0,0 @@
# Babel and `next/font` conflict
#### Why This Error Occurred
You have tried to use `next/font` with a custom babel config. When your application has a custom babel config you opt-out of the Next.js Compiler which is required to use `next/font`.
#### Possible Ways to Fix It
- Remove your custom babel config and use the Next.js Compiler
### Useful Links
- [Next.js Compiler](https://nextjs.org/docs/advanced-features/compiler)
- [Customizing Babel Config](https://nextjs.org/docs/advanced-features/customizing-babel-config)

View file

@ -0,0 +1,16 @@
---
title: 'Babel and `next/font` conflict'
---
## Why This Error Occurred
You have tried to use `next/font` with a custom babel config. When your application has a custom babel config you opt-out of the Next.js Compiler which is required to use `next/font`.
## Possible Ways to Fix It
- Remove your custom babel config and use the Next.js Compiler
## Useful Links
- [Next.js Compiler](/docs/architecture/nextjs-compiler)
- [Customizing Babel Config](/docs/pages/building-your-application/configuring/babel)

View file

@ -1,15 +0,0 @@
# Beta Middleware Used
#### Why This Error Occurred
[Middleware](https://nextjs.org/docs/advanced-features/middleware) was beta in versions prior to `v12.2` and not yet covered by [semver](https://semver.org/).
#### Possible Ways to Fix It
You can continue to use Middleware in versions prior to `v12.2`. However, you will need to make changes to upgrade to newer versions.
If you're using Next.js on Vercel, your existing deploys using Middleware will continue to work, and you can continue to deploy your site using Middleware. When you upgrade your site to `v12.2` or later, you will need to follow the [upgrade guide](https://nextjs.org/docs/messages/middleware-upgrade-guide).
### Useful Links
- [Middleware Upgrade Guide](https://nextjs.org/docs/messages/middleware-upgrade-guide)

View file

@ -0,0 +1,17 @@
---
title: Beta Middleware Used
---
## Why This Error Occurred
[Middleware](/docs/pages/building-your-application/routing/middleware) was beta in versions prior to `v12.2` and not yet covered by [semver](https://semver.org/).
## Possible Ways to Fix It
You can continue to use Middleware in versions prior to `v12.2`. However, you will need to make changes to upgrade to newer versions.
If you're using Next.js on Vercel, your existing deploys using Middleware will continue to work, and you can continue to deploy your site using Middleware. When you upgrade your site to `v12.2` or later, you will need to follow the [upgrade guide](/docs/messages/middleware-upgrade-guide).
## Useful Links
- [Middleware Upgrade Guide](/docs/messages/middleware-upgrade-guide)

View file

@ -1,30 +0,0 @@
# Build directory not writeable
#### Why This Error Occurred
The filesystem does not allow writing to the specified directory. A common cause for this error is starting a [custom server](https://nextjs.org/docs/advanced-features/custom-server) in development mode on a production server, for example, [Vercel](https://vercel.com) which doesn't allow you to write to the filesystem after your app is built.
#### Possible Ways to Fix It
When using a custom server with a server file, for example called `server.js`, make sure you update the scripts key in `package.json` to:
```json
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
and the custom server starts Next in production mode when `NODE_ENV` is `production`
```js
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
```
### Useful Links
- [Custom Server documentation + examples](https://nextjs.org/docs/advanced-features/custom-server)

View file

@ -0,0 +1,32 @@
---
title: Build directory not writeable
---
## Why This Error Occurred
The filesystem does not allow writing to the specified directory. A common cause for this error is starting a [custom server](/docs/pages/building-your-application/configuring/custom-server) in development mode on a production server, for example, [Vercel](https://vercel.com) which doesn't allow you to write to the filesystem after your app is built.
## Possible Ways to Fix It
When using a custom server with a server file, for example called `server.js`, make sure you update the scripts key in `package.json` to:
```json filename="package.json"
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
and the custom server starts Next in production mode when `NODE_ENV` is `production`
```js filename="server.js"
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
```
## Useful Links
- [Custom Server documentation + examples](/docs/pages/building-your-application/configuring/custom-server)

View file

@ -1,18 +1,20 @@
# Built-in CSS Support Disabled
---
title: Built-in CSS Support Disabled
---
#### Why This Error Occurred
## Why This Error Occurred
Custom CSS configuration was added in `next.config.js` which disables the built-in CSS/SCSS support to prevent conflicting configuration.
A legacy plugin such as `@zeit/next-css` being added in `next.config.js` can cause this message.
#### Possible Ways to Fix It
## Possible Ways to Fix It
If you would like to leverage the built-in CSS/SCSS support you can remove any custom CSS configuration or any plugins like `@zeit/next-css` or `@zeit/next-sass` in your `next.config.js`.
If you would prefer not to leverage the built-in support you can ignore this message.
### Useful Links
## Useful Links
- [Built-in CSS Support docs](https://nextjs.org/docs/basic-features/built-in-css-support)
- [Custom webpack config docs](https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config)
- [Built-in CSS Support docs](/docs/pages/building-your-application/styling)
- [Custom webpack config docs](/docs/pages/api-reference/next-config-js/webpack)

View file

@ -1,18 +1,20 @@
# Built-in `next/font`
---
title: 'Built-in `next/font`'
---
#### Why This Error Occurred
## Why This Error Occurred
Starting with Next.js 13.2, `next/font` is built-in to Next.js and no longer needs to be installed. The `@next/font` package will be removed in Next.js 14.
#### Possible Ways to Fix It
## Possible Ways to Fix It
Run the `built-in-next-font` codemod to automatically uninstall `@next/font` and change `@next/font` imports to `next/font`:
```sh
```bash filename="Terminal"
npx @next/codemod built-in-next-font .
```
### Useful Links
## Useful Links
- [Codemods](https://nextjs.org/docs/advanced-features/codemods)
- [Optimizing Fonts](https://nextjs.org/docs/basic-features/font-optimization)
- [Codemods](/docs/pages/building-your-application/upgrading/codemods)
- [Optimizing Fonts](/docs/pages/building-your-application/optimizing/fonts)

View file

@ -1,15 +1,17 @@
# Cannot output to /public
---
title: Cannot output to /public
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Use a different `distDir` or export to a different folder.
### Useful Links
## Useful Links
- [Static file serving docs](https://nextjs.org/docs/basic-features/static-file-serving)
- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets)

View file

@ -1,15 +1,17 @@
# Cannot output to /static
---
title: Cannot output to /static
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Use a different `distDir` or export to a different folder.
### Useful Links
## Useful Links
- [Static file serving docs](https://nextjs.org/docs/basic-features/static-file-serving)
- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets)

View file

@ -1,13 +1,15 @@
# Can't Override Next Props
---
title: Can't Override Next Props
---
#### Why This Error Occurred
## 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
## 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
## Useful Links
- [The issue this was reported in: #6480](https://github.com/vercel/next.js/issues/6480)

View file

@ -1,12 +1,14 @@
# Circular structure in "getInitialProps" result
---
title: 'Circular structure in `getInitialProps` result'
---
#### Why This Error Occurred
## 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
## 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`.

View file

@ -1,16 +1,18 @@
# React Class component rendered in a Server Component
---
title: React Class component rendered in a Server Component
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Use a Function Component.
##### Before
```jsx
```jsx filename="app/page.js"
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
@ -20,7 +22,7 @@ export default class Page extends React.Component {
##### After
```jsx
```jsx filename="app/page.js"
export default function Page() {
return <p>Hello world</p>
}
@ -30,7 +32,7 @@ Mark the component rendering the React Class Component as a Client Component by
##### Before
```jsx
```jsx filename="app/page.js"
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
@ -40,7 +42,7 @@ export default class Page extends React.Component {
##### After
```jsx
```jsx filename="app/page.js"
'use client'
export default class Page extends React.Component {
@ -50,6 +52,6 @@ export default class Page extends React.Component {
}
```
### Useful Links
## Useful Links
[Server and Client Components](https://beta.nextjs.org/docs/rendering/server-and-client-components)
[Server and Client Components](/docs/getting-started/react-essentials)

View file

@ -1,14 +1,16 @@
# Client-side Exception Occurred
---
title: Client-side Exception Occurred
---
#### Why This Error 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
## 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
## Useful Links
- [Error Boundaries Documentation](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [Custom Error Page Documentation](https://nextjs.org/docs/advanced-features/custom-error-page#more-advanced-error-page-customizing)
- [Custom Error Page Documentation](/docs/pages/building-your-application/routing/custom-error#more-advanced-error-page-customizing)

View file

@ -1,14 +1,16 @@
# Invalid webpack resolve alias
---
title: Invalid webpack resolve alias
---
#### Why This Error Occurred
## 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
## 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
```js filename="next.config.js"
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
@ -17,6 +19,6 @@ webpack(config) {
}
```
### Useful Links
## Useful Links
- [Related issue](https://github.com/vercel/next.js/issues/6681)

View file

@ -1,9 +1,11 @@
# Conflicting AMP Tag
---
title: Conflicting AMP Tag
---
#### Why This Error Occurred
## Why This Error Occurred
In AMP mode Next.js adds certain necessary tags automatically to comply with the AMP standard. You added a tag using `next/head` that conflicts with one of these automatically added tags.
#### Possible Ways to Fix It
## Possible Ways to Fix It
Remove the tag mentioned in the error message from any `<Head></Head>` elements

View file

@ -1,31 +0,0 @@
# Conflicting Public File and Page File
#### Why This Error Occurred
One of your public files has the exact 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
```
public/
hello
pages/
hello.js
```
Non-conflicting public file and page file
```
public/
hello.txt
pages/
hello.js
```
### Useful Links
- [Static file serving docs](https://nextjs.org/docs/basic-features/static-file-serving)

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/building-your-application/optimizing/static-assets)

View file

@ -1,42 +1,42 @@
# Conflicting SSG Paths
---
title: Conflicting SSG Paths
---
#### Why This Error Occurred
## Why This Error Occurred
In your `getStaticPaths` function for one of your pages you returned conflicting paths. All page paths must be unique and duplicates are not allowed.
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
## 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
// pages/hello/world.jsx
```jsx filename="pages/hello/world.js"
export default function Hello() {
return 'hello world!'
}
```
// pages/[...catchAll].jsx
```jsx filename="pages/[...catchAll].js"
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
paths: [
// this conflicts with the /hello/world.js page, remove to resolve error
'/hello/world',
'/hello/world', // <-- this conflicts with the /hello/world.js page, remove to resolve error
'/another',
],
fallback: false,
})
export default function CatchAll() {
export default function CatchAllPage() {
return 'Catch-all page'
}
```
Example conflicting paths:
```jsx
// pages/blog/[slug].jsx
```jsx filename="pages/blog/[slug].js"
export const getStaticPaths = () => ({
paths: ['/blog/conflicting', '/blog/another'],
fallback: false,
@ -45,8 +45,9 @@ export const getStaticPaths = () => ({
export default function Blog() {
return 'Blog!'
}
```
// pages/[...catchAll].jsx
```jsx filename="pages/[...catchAll].js"
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
@ -63,6 +64,6 @@ export default function CatchAll() {
}
```
### Useful Links
## Useful Links
- [`getStaticPaths` Documentation](https://nextjs.org/docs/basic-features/data-fetching/get-static-paths)
- [`getStaticPaths` Documentation](/docs/pages/building-your-application/data-fetching/get-static-paths)

View file

@ -1,16 +1,18 @@
# createContext in a Server Component
---
title: createContext in a Server Component
---
#### Why This Error Occurred
## Why This Error Occurred
You are using `createContext` in a Server Component but it only works in Client Components.
#### Possible Ways to Fix It
## 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
```jsx filename="app/example-component.js"
import { createContext } from 'react'
const Context = createContext()
@ -18,13 +20,13 @@ const Context = createContext()
##### After
```jsx
```jsx filename="app/example-component.js"
'use client'
import { createContext } from 'react'
const Context = createContext()
```
### Useful Links
## Useful Links
[Server and Client Components](https://beta.nextjs.org/docs/rendering/server-and-client-components#context)
[Server and Client Components](/docs/getting-started/react-essentials#context)

View file

@ -1,39 +0,0 @@
# Global CSS Must Be in Your Custom \<App\>
#### Why This Error Occurred
An attempt to import Global CSS from a file other than [`pages/_app.js`](https://nextjs.org/docs/advanced-features/custom-app) was made.
Global CSS cannot be used in files other than your [Custom `<App>`](https://nextjs.org/docs/advanced-features/custom-app) due to its side-effects and ordering problems.
#### Possible Ways to Fix It
To avoid conflicts, relocate all first-party Global CSS imports to your [`pages/_app.js` file](https://nextjs.org/docs/advanced-features/custom-app).
Or, [update your component to use local CSS (Component-Level CSS) via CSS Modules](https://nextjs.org/docs/basic-features/built-in-css-support#adding-component-level-css). This is the preferred approach.
#### Example
Consider the stylesheet named [`styles.css`](https://nextjs.org/docs/basic-features/built-in-css-support#adding-a-global-stylesheet)
```css
/* 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;
}
```
Create a [`pages/_app.js` file](https://nextjs.org/docs/advanced-features/custom-app) if not already present. Then [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) the [`styles.css` file](https://nextjs.org/docs/basic-features/built-in-css-support#adding-a-global-stylesheet).
```jsx
// pages/_app.js
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```

39
errors/css-global.mdx Normal file
View file

@ -0,0 +1,39 @@
---
title: 'Global CSS Must Be in Your Custom `<App>`'
---
## Why This Error Occurred
An attempt to import Global CSS from a file other than [`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>`](/docs/pages/building-your-application/routing/custom-app) due to its side-effects and ordering problems.
## Possible Ways to Fix It
To avoid conflicts, relocate all first-party Global CSS imports to your [`pages/_app.js` file](/docs/pages/building-your-application/routing/custom-app).
Or, [update your component to use local CSS (Component-Level CSS) via CSS Modules](/docs/pages/building-your-application/styling/css-modules). This is the preferred approach.
#### Example
Consider the stylesheet named [`styles.css`](/docs/pages/building-your-application/styling/css-modules)
```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;
}
```
Create a [`pages/_app.js` file](/docs/pages/building-your-application/routing/custom-app) if not already present. Then [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) the [`styles.css` file](/docs/pages/building-your-application/styling/css-modules).
```jsx filename="pages/_app.js"
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```

View file

@ -1,13 +1,15 @@
# CSS Modules Imported by a Dependency
---
title: CSS Modules Imported by a Dependency
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Reach out to the maintainer and ask for them to publish a compiled version of
their dependency.
@ -18,11 +20,6 @@ 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).
If this is **first party code**, try
[including monorepo packages in the compilation pipeline](https://nextjs.org/docs/advanced-features/compiler#module-transpilation).
---
This limitation does not exist when using the `app` directory: [beta.nextjs.org/docs](https://beta.nextjs.org/docs).
> **Good to know**: This limitation does not exist when using the [`app` directory](/docs/app/building-your-application).

View file

@ -1,13 +1,15 @@
# CSS Imported by a Dependency
---
title: CSS Imported by a Dependency
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Reach out to the maintainer and ask for them to publish a compiled version of
their dependency.

View file

@ -1,47 +0,0 @@
# Images cannot be imported into your custom document.
#### Why This Error Occurred
An attempt to import an image file into [`pages/_document.js`](https://nextjs.org/docs/advanced-features/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`](https://nextjs.org/docs/advanced-features/custom-app) file.
#### Example
```jsx
//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
module.exports = {
images: {
disableStaticImages: true,
},
}
```
### Useful Links
- [Custom `Document`](https://nextjs.org/docs/advanced-features/custom-document)
- [Custom `App`](https://nextjs.org/docs/advanced-features/custom-app)
- [Static File Serving](https://nextjs.org/docs/basic-features/static-file-serving)
- [Disable Static Image Imports](https://nextjs.org/docs/api-reference/next/image#disable-static-imports)

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/building-your-application/optimizing/static-assets)
- [Disable Static Image Imports](/docs/pages/api-reference/components/image#disablestaticimages)

View file

@ -1,14 +0,0 @@
# 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](https://nextjs.org/docs/advanced-features/automatic-static-optimization)
- [404 Page](https://nextjs.org/docs/advanced-features/custom-error-page#404-page)

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

@ -1,27 +1,29 @@
# Deleting Query Parameters In Middlewares
---
title: Deleting Query Parameters In Middlewares
---
#### Why This Error Occurred
## Why This Error Occurred
In previous versions of Next.js, we were merging query parameters with the incoming request for rewrites happening in middlewares, 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.
```typescript
```ts filename="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export default function middleware(request: NextRequest) {
const nextUrl = request.nextUrl
nextUrl.searchParams.delete('key') // this is now possible! 🎉
nextUrl.searchParams.delete('key') // <-- this is now possible! 🎉
return NextResponse.rewrite(nextUrl)
}
```
#### Possible Ways to Fix It
## 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.
```typescript
```ts filename="middleware.ts"
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
@ -32,4 +34,4 @@ export default function middleware(request: NextRequest) {
}
```
This warning will be removed in a next version of Next.js.
This warning will be removed in the next version of Next.js.

View file

@ -1,21 +1,22 @@
# Entire page deopted into client-side rendering
---
title: Entire page deopted into client-side rendering
---
#### Why This Error Occurred
## Why This Error Occurred
During static rendering the entire page was deopted into client-side rendering by `useSearchParams` as there was no [Suspense boundary](https://beta.nextjs.org/docs/data-fetching/streaming-and-suspense#example-using-suspense-boundaries) that caught it.
During static rendering, 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#static-rendering) that caught it.
If a route is statically rendered, calling `useSearchParams()` will cause the tree up to the closest [Suspense boundary](https://beta.nextjs.org/docs/data-fetching/streaming-and-suspense#example-using-suspense-boundaries) to be client-side rendered.
If a route is statically rendered, calling `useSearchParams()` will cause the tree up to the closest [Suspense boundary](/docs/app/api-reference/functions/use-search-params#static-rendering) to be client-side rendered.
This allows a part of the page to be statically rendered while the dynamic part that uses `searchParams` can be client-side rendered.
#### Possible Ways to Fix It
## 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](https://beta.nextjs.org/docs/data-fetching/streaming-and-suspense#example-using-suspense-boundaries) as shown in `app/dashboard/page.tsx`.
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#static-rendering) as shown in `app/dashboard/page.tsx`.
```js
// app/dashboard/search-bar.tsx
```tsx filename="app/dashboard/search-bar.tsx"
'use client'
import { useSearchParams } from 'next/navigation'
@ -32,8 +33,7 @@ export default function SearchBar() {
}
```
```js
// app/dashboard/page.tsx
```tsx filename="app/dashboard/page.tsx"
import { Suspense } from 'react'
import SearchBar from './search-bar'
@ -59,6 +59,6 @@ export default function Page() {
}
```
### Useful Links
## Useful Links
- [`useSearchParams` static rendering documentation](https://beta.nextjs.org/docs/api-reference/use-search-params#static-rendering)
- [`useSearchParams` static rendering documentation](/docs/app/api-reference/functions/use-search-params#static-rendering)

View file

@ -1,13 +1,15 @@
# Deprecated target config
---
title: Deprecated target config
---
#### Why This Error Occurred
## Why This Error Occurred
Starting in Next.js 13, the `target` property in `next.config.js` has been removed.
#### Possible Ways to Fix It
## 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
## Useful Links
- [Output File Tracing Documentation](https://nextjs.org/docs/advanced-features/output-file-tracing)
- [Output File Tracing Documentation](/docs/pages/api-reference/next-config-js/output)

View file

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

View file

@ -1,6 +1,8 @@
# Duplicate Sass Dependencies
---
title: Duplicate Sass Dependencies
---
#### Why This Error Occurred
## Why This Error Occurred
Your project has a direct dependency on both `sass` and `node-sass`, two
different package that both compile Sass files!
@ -8,7 +10,7 @@ different package that both compile Sass files!
Next.js will only use one of these, so it is suggested you remove one or the
other.
#### Possible Ways to Fix It
## 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.
@ -18,16 +20,16 @@ Since `sass` is now the canonical implementation, we suggest removing the older
**Via npm**
```bash
```bash filename="Terminal"
npm uninstall node-sass
```
**Via Yarn**
```bash
```bash filename="Terminal"
yarn remove node-sass
```
### Useful Links
## Useful Links
- [`sass` package documentation](https://github.com/sass/dart-sass)

View file

@ -1,6 +1,8 @@
# Dynamic code evaluation is not available in Middlewares or Edge API Routes
---
title: Dynamic code evaluation is not available in Middlewares or Edge API Routes
---
#### Why This Error Occurred
## Why This Error Occurred
`eval()`, `new Function()` or compiling WASM binaries dynamically is not allowed in Middlewares or Edge API Routes.
Specifically, the following APIs are not supported:
@ -10,11 +12,11 @@ Specifically, the following APIs are not supported:
- `WebAssembly.compile`
- `WebAssembly.instantiate` with [a buffer parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code)
#### Possible Ways to Fix It
## Possible Ways to Fix It
You can bundle your WASM binaries using `import`:
```typescript
```ts filename="middleware.ts"
import { NextResponse } from 'next/server'
import squareWasm from './square.wasm?module'
@ -28,10 +30,10 @@ export default async function middleware() {
}
```
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 treeshaking.
You can relax the check to allow specific files with your Middleware or Edge API Route exported [configuration](https://nextjs.org/docs/api-reference/edge-runtime#unsupported-apis):
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 Middleware or Edge API Route exported [configuration](/docs/pages/api-reference/edge#unsupported-apis):
```typescript
```tsx filename="pages/api/example.ts"
export const config = {
runtime: 'edge', // for Edge API Routes only
unstable_allowDynamic: [

View file

@ -1,10 +1,12 @@
# Detected next.config.js, no exported configuration found
---
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
## Possible Ways to Fix It
Check if you correctly export configuration in `next.config.js` file:
@ -14,6 +16,6 @@ module.exports = {
}
```
### Useful Links
## Useful Links
- [Introduction to next.config.js](https://nextjs.org/docs/api-reference/next.config.js/introduction)
- [Introduction to next.config.js](/docs/pages/api-reference/next-config-js)

View file

@ -1,13 +1,15 @@
# Empty Object Returned From `getInitialProps`
---
title: 'Empty Object Returned From `getInitialProps`'
---
#### Why This Error Occurred
## 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
## 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
## Useful Links
- [Automatic Static Optimization Documentation](https://nextjs.org/docs/advanced-features/automatic-static-optimization)
- [Automatic Static Optimization Documentation](/docs/pages/building-your-application/rendering/automatic-static-optimization)

View file

@ -1,9 +1,11 @@
# The key "<your key>" under "env" in next.config.js is not allowed.
---
title: 'The key "<your key>" under "env" in `next.config.js` is not allowed.'
---
#### Why This Error Occurred
## 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
## 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

@ -1,20 +1,22 @@
# Env Loading Disabled
---
title: Env Loading Disabled
---
#### Why This Error Occurred
## 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
## 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
## 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](https://nextjs.org/docs/basic-features/environment-variables)
- [Next.js Environment Variables Docs](/docs/pages/building-your-application/configuring/environment-variables)

View file

@ -1,14 +1,16 @@
# Experimental `appDir: true`
---
title: 'Experimental `appDir: true`'
---
#### Why This Error Occurred
## Why This Error Occurred
Your project contains a directory named `app/`. Since Next.js 13, this is a [reserved name](https://nextjs.org/blog/next-13#new-app-directory-beta).
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
## 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
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
@ -21,7 +23,7 @@ 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
## Useful Links
- [Next.js 13 App directory (Beta)](https://nextjs.org/blog/next-13#new-app-directory-beta)
- [App directory (Beta) documentation](https://beta.nextjs.org/docs)
- [Next.js 13 App directory](/blog/next-13#new-app-directory-beta)
- [App directory documentation](/docs/app/building-your-application)

View file

@ -1,4 +1,6 @@
# "next/jest" Experimental
---
title: '`next/jest` Experimental'
---
#### Why This Message Occurred

View file

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

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

@ -1,24 +0,0 @@
# 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`](https://nextjs.org/docs/api-reference/cli#production) 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`](https://nextjs.org/docs/api-reference/next/image#loader-configuration) in `next.config.js`.
- [Configure `unoptimized`](https://nextjs.org/docs/api-reference/next/image#unoptimized) in `next.config.js`.
### Useful Links
- [Deployment Documentation](https://nextjs.org/docs/deployment#managed-nextjs-with-vercel)
- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
- [`output: 'export'` Documentation](https://nextjs.org/docs/advanced-features/static-html-export)
- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
- [Vercel Documentation](https://vercel.com/docs/concepts/next.js/image-optimization)

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/next-cli#production) 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/building-your-application/deploying#managed-nextjs-with-vercel)
- [Image Optimization Documentation](/docs/pages/building-your-application/optimizing/images)
- [`output: 'export'` Documentation](/docs/pages/building-your-application/deploying/static-exports)
- [`next/image` Documentation](/docs/pages/api-reference/components/image)
- [Vercel Documentation](https://vercel.com/docs/concepts/next.js/image-optimization)

View file

@ -1,20 +0,0 @@
# 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`](https://nextjs.org/docs/api-reference/cli#production) to run a production server
### Useful Links
- [Deployment Documentation](https://nextjs.org/docs/deployment)
- [`output: 'export'` Documentation](https://nextjs.org/docs/advanced-features/static-html-export)
- [Rewrites Documentation](https://nextjs.org/docs/api-reference/next.config.js/rewrites)
- [Redirects Documentation](https://nextjs.org/docs/api-reference/next.config.js/redirects)
- [Headers Documentation](https://nextjs.org/docs/api-reference/next.config.js/headers)

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/next-cli#production) to run a production server
## Useful Links
- [Deployment Documentation](/docs/pages/building-your-application/deploying)
- [`output: 'export'` Documentation](/docs/pages/building-your-application/deploying/static-exports)
- [Rewrites Documentation](/docs/pages/api-reference/next-config-js/rewrites)
- [Redirects Documentation](/docs/pages/api-reference/next-config-js/redirects)
- [Headers Documentation](/docs/pages/api-reference/next-config-js/headers)

View file

@ -1,16 +0,0 @@
# 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`](https://nextjs.org/docs/api-reference/cli#production) to run a production server
### Useful Links
- [Deployment Documentation](https://nextjs.org/docs/deployment)
- [`output: 'export'` Documentation](https://nextjs.org/docs/advanced-features/static-html-export)
- [Internationalized Routing](https://nextjs.org/docs/advanced-features/i18n-routing)

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/next-cli#production) to run a production server
## Useful Links
- [Deployment Documentation](/docs/pages/building-your-application/deploying)
- [`output: 'export'` Documentation](/docs/pages/building-your-application/deploying/static-exports)
- [Internationalized Routing](/docs/pages/building-your-application/routing/internationalization)

View file

@ -1,15 +1,17 @@
# The provided export path doesn't match the page.
---
title: The provided export path doesn't match the page.
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Change your `exportPathMap` function in `next.config.js` to have a path that matches the dynamically routed page.
```js
```js filename="next.config.js"
module.exports = {
exportPathMap: function () {
return {
@ -21,6 +23,6 @@ module.exports = {
}
```
### Useful Links
## Useful Links
- [exportPathMap](https://nextjs.org/docs/api-reference/next.config.js/exportPathMap) documentation
- [exportPathMap](/docs/pages/api-reference/next-config-js/exportPathMap) documentation

View file

@ -1,12 +1,14 @@
# SWC Failed to Load
---
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 be downloaded that is compatible specific to your system. In some cases this binary may fail to load either from failing to download or an incompatibility with your architecture.
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
## 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`).
@ -20,7 +22,7 @@ This can be fixed by removing the lockfile and regenerating it with a newer vers
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
```json filename=".babelrc"
{
"presets": ["next/babel"]
}
@ -28,7 +30,7 @@ If SWC continues to fail to load you can opt-out by disabling `swcMinify` in you
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
## Useful Links
- [SWC Feedback Thread](https://github.com/vercel/next.js/discussions/30468)
- [SWC Disabled Document](https://nextjs.org/docs/messages/swc-disabled)
- [SWC Disabled Document](/docs/messages/swc-disabled)

View file

@ -1,18 +1,20 @@
# Failed to fetch devPagesManifest
---
title: 'Failed to fetch `devPagesManifest`'
---
#### Why This Error Occurred
## 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
## 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
## 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

@ -1,6 +1,8 @@
# Fast Refresh had to perform full reload
---
title: Fast Refresh had to perform full reload
---
#### Why This Error Occurred
## Why This Error Occurred
Fast Refresh had to perform a full reload when you edited a file. It may be because:
@ -8,12 +10,12 @@ Fast Refresh had to perform a full reload when you edited a file. It may be beca
- 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
## 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
## Useful Links
[Fast Refresh documentation](https://nextjs.org/docs/basic-features/fast-refresh)
[Fast Refresh documentation](/docs/architecture/fast-refresh)

View file

@ -1,10 +1,12 @@
# `future.webpack5` has been moved to `webpack5`
---
title: '`future.webpack5` has been moved to `webpack5`'
---
#### Why This Error Occurred
## Why This Error Occurred
The `future.webpack5` option has been moved to `webpack5` in `next.config.js`.
#### Possible Ways to Fix It
## 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.
@ -14,8 +16,7 @@ Change `future.webpack5` to `webpack5`.
Current `next.config.js`:
```js
// next.config.js
```js filename="next.config.js"
module.exports = {
future: {
webpack5: false,
@ -25,8 +26,7 @@ module.exports = {
Updated `next.config.js`:
```js
// next.config.js
```js filename="next.config.js"
module.exports = {
webpack5: false,
}

View file

@ -1,9 +1,11 @@
# generateBuildId did not return a string
---
title: '`generateBuildId` did not return a string'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Always return a string from generateBuildId.

View file

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

View file

@ -1,4 +1,6 @@
# getInitialProps Export Warning
---
title: '`getInitialProps` Export Warning'
---
#### Why This Warning Occurred
@ -6,10 +8,10 @@ You attempted to statically export your application via `output: 'export'` or `n
Next.js discourages you to use `getInitialProps` in this scenario.
#### Possible Ways to Fix It
## Possible Ways to Fix It
Use `getStaticProps` instead for proper SSG support.
### Useful Links
## Useful Links
- [`getStaticProps` Documentation](https://nextjs.org/docs/basic-features/data-fetching/get-static-props)
- [`getStaticProps` Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)

View file

@ -1,16 +1,18 @@
# Google Font Display
---
title: Google Font Display
---
> Enforce font-display behavior with Google Fonts.
### Why This Error Occurred
## 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
## Possible Ways to Fix It
For most cases, the best font display strategy for custom fonts is `optional`.
```jsx
```jsx filename="pages/index.js"
import Head from 'next/head'
export default function IndexPage() {
@ -33,7 +35,7 @@ Specifying `display=optional` minimizes the risk of invisible text or layout shi
If you want to specifically display a font using an `auto`, `block`, or `fallback` strategy, then you can disable this rule.
### Useful Links
## 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)

View file

@ -1,25 +1,27 @@
# Google Font Preconnect
---
title: Google Font Preconnect
---
> Next.js automatically adds `<link rel="preconnect" />` after version `12.0.1`.
> Ensure `preconnect` is used with Google Fonts.
### Why This Error Occurred
## 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
## Possible Ways to Fix It
Add `rel="preconnect"` to the Google Font domain `<link>` tag:
```jsx
```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
## 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](https://nextjs.org/docs/pages/building-your-application/optimizing/fonts)
- [Next.js Font Optimization](/docs/pages/building-your-application/optimizing/fonts)

View file

@ -1,14 +1,16 @@
# Missing specified subset for a `next/font/google` font
---
title: 'Missing specified subset for a `next/font/google` font'
---
#### Why This Error Occurred
## Why This Error Occurred
Preload is enabled for a font that is missing a specified subset.
#### Possible Ways to Fix It
## Possible Ways to Fix It
##### Specify which subsets to preload for that font.
```js
```js filename="example.js"
const inter = Inter({ subsets: ['latin'] })
```
@ -18,13 +20,13 @@ Note: previously it was possible to specify default subsets in your `next.config
If it's not possible to preload your intended subset you can disable preloading.
```js
```js filename="example.js"
const notoSansJapanese = Noto_Sans_JP({
weight: '400',
preload: false,
})
```
### Useful Links
## Useful Links
[Specifying a subset](https://nextjs.org/docs/basic-features/font-optimization#specifying-a-subset)
[Specifying a subset](/docs/pages/building-your-application/optimizing/fonts#specifying-a-subset)

View file

@ -1,13 +1,15 @@
# Redirect During getStaticProps Prerendering
---
title: Redirect During getStaticProps Prerendering
---
#### Why This Error Occurred
## Why This Error Occurred
The `redirect` value was returned from `getStaticProps` during prerendering which is invalid.
#### Possible Ways to Fix It
## 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
## Useful Links
- [Data Fetching Documentation](https://nextjs.org/docs/basic-features/data-fetching/get-static-props)
- [Data Fetching Documentation](/docs/pages/building-your-application/data-fetching/get-static-props)

View file

@ -1,18 +1,20 @@
# getStaticProps/getServerSideProps can not be attached to the page component
---
title: '`getStaticProps` / `getServerSideProps` can not be attached to the page component'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Move the method to it's own export from your page.
**Before**
```jsx
```jsx filename="pages/index.js"
function Page(props) {
return <p>hello world</p>
}
@ -28,7 +30,7 @@ export default Page
**After**
```jsx
```jsx filename="pages/index.js"
function Page(props) {
return <p>hello world</p>
}
@ -42,6 +44,6 @@ export const getStaticProps = () => ({
})
```
### Useful Links
## Useful Links
- [Data Fetching Docs](https://nextjs.org/docs/basic-features/data-fetching)
- [Data Fetching Docs](/docs/pages/building-your-application/data-fetching)

View file

@ -1,12 +1,14 @@
# getServerSideProps Export Error
---
title: '`getServerSideProps` Export Error'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
1. If you'd like to keep your application static, you can use `getStaticProps` instead of `getServerSideProps`.
@ -39,10 +41,10 @@ It is not possible to use `getServerSideProps` without a server, so you'll need
```
> **Note**: Removing export does not mean your entire application is no longer static.
> Pages that use `getStaticProps` or [no lifecycle](https://nextjs.org/docs/advanced-features/automatic-static-optimization) **will still be static**!
> Pages that use `getStaticProps` or [no lifecycle](/docs/pages/building-your-application/rendering/automatic-static-optimization) **will still be static**!
### Useful Links
## Useful Links
- [Automatic Static Optimization](https://nextjs.org/docs/advanced-features/automatic-static-optimization)
- [`getStaticProps` documentation](https://nextjs.org/docs/basic-features/data-fetching/get-static-props)
- [`exportPathMap` documentation](https://nextjs.org/docs/api-reference/next.config.js/exportPathMap)
- [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/next-config-js/exportPathMap)

View file

@ -1,16 +1,18 @@
# Mixed `notFound` and `redirect`
---
title: 'Mixed `notFound` and `redirect`'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Make sure only `notFound` **or** `redirect` is being returned on your page's `getStaticProps` or `getServerSideProps`
### Useful Links
## Useful Links
- [`getStaticProps` Documentation](https://nextjs.org/docs/basic-features/data-fetching/get-static-props)
- [`getServerSideProps` Documentation](https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props)
- [`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

@ -1,6 +1,8 @@
# Must not access ServerResponse after getServerSideProps() resolves
---
title: 'Must not access ServerResponse after `getServerSideProps` resolves'
---
#### Why This Error Occurred
## 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.
@ -8,12 +10,12 @@ This is because the framework tries to optimize when items like headers or statu
For this reason, accessing the object after this time is disallowed.
#### Possible Ways to Fix It
## 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 middleware like `next-session` or `express-session`, try installing the middleware in the server instead of `getServerSideProps()`.
### Useful Links
## Useful Links
- [Data Fetching Docs](https://nextjs.org/docs/basic-features/data-fetching/index)
- [Data Fetching Docs](/docs/pages/building-your-application/data-fetching)

View file

@ -1,10 +1,12 @@
# Failed to load `BUILD_ID` from Server
---
title: 'Failed to load `BUILD_ID` from Server'
---
#### Why This Error Occurred
## 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
## 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

@ -1,6 +1,8 @@
# `href` Interpolation Failed
---
title: '`href` Interpolation Failed'
---
#### Why This Error Occurred
## 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`.
@ -8,7 +10,7 @@ Note: this error will only show when the `next/link` component is clicked not wh
**Invalid `href` interpolation**
```jsx
```jsx filename="blog-link.js"
import Link from 'next/link'
export default function BlogLink() {
@ -27,7 +29,7 @@ export default function BlogLink() {
**Valid `href` interpolation**
```jsx
```jsx filename="blog-link.js"
import Link from 'next/link'
export default function BlogLink() {
@ -44,11 +46,11 @@ export default function BlogLink() {
}
```
#### Possible Ways to Fix It
## 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
## Useful Links
- [Routing section in Documentation](https://nextjs.org/docs/routing/introduction)
- [Dynamic routing section in Documentation](https://nextjs.org/docs/routing/dynamic-routes)
- [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

@ -1,9 +1,11 @@
# ignored-compiler-options
---
title: '`ignored-compiler-options`'
---
#### Why This Error Occurred
## 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
## Useful Links
- [Next.js Compiler](https://nextjs.org/docs/advanced-features/compiler)
- [Next.js Compiler](/docs/architecture/nextjs-compiler)

View file

@ -1,12 +1,14 @@
# ESM packages need to be imported
---
title: ESM packages need to be imported
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
1. Use `import` or `import()` to reference the package instead. (Recommended)
@ -14,6 +16,6 @@ You get this error when using a different way to reference the package, e. g. `r
3. Switch to loose mode (`experimental.esmExternals: 'loose'`), which tries to automatically correct this error.
### Useful Links
## Useful Links
- [Node.js ESM require docs](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html#esm_require)

View file

@ -1,17 +1,19 @@
# Invalid "next" Import
---
title: 'Invalid `next` Import'
---
#### Why This Error Occurred
## 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
## 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
## Useful Links
- [Custom Server Documentation](https://nextjs.org/docs/advanced-features/custom-server)
- [Custom Server Documentation](/docs/pages/building-your-application/configuring/custom-server)

View file

@ -1,14 +1,16 @@
# Improper webpack `devtool` used in development mode
---
title: 'Improper webpack `devtool` used in development mode'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Please remove the custom `devtool` override or only apply it to production builds in your `next.config.js`.
```js
```js filename="next.config.js"
module.exports = {
webpack: (config, options) => {
if (!options.dev) {

View file

@ -1,6 +1,8 @@
# Incompatible `href` and `as` values
---
title: 'Incompatible `href` and `as` values'
---
#### Why This Error Occurred
## 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.
@ -8,7 +10,7 @@ Note: this error will only show when the `next/link` component is clicked not wh
**Incompatible `href` and `as`**
```jsx
```jsx filename="pages/blog.js"
import Link from 'next/link'
export default function Page(props) {
@ -24,7 +26,7 @@ export default function Page(props) {
**Compatible `href` and `as`**
```jsx
```jsx filename="pages/blog.js"
import Link from 'next/link'
export default function Page(props) {
@ -38,11 +40,11 @@ export default function Page(props) {
}
```
#### Possible Ways to Fix It
## 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
## Useful Links
- [Routing section in Documentation](https://nextjs.org/docs/routing/introduction)
- [Dynamic routing section in Documentation](https://nextjs.org/docs/routing/dynamic-routes)
- [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

@ -1,4 +1,6 @@
# Inline script id
---
title: Inline script id
---
> Enforce `id` attribute on `next/script` components with inline content.
@ -10,7 +12,7 @@
Add an `id` attribute to the `next/script` component.
```jsx
```jsx filename="pages/_app.js"
import Script from 'next/script'
export default function App({ Component, pageProps }) {
@ -25,4 +27,4 @@ export default function App({ Component, pageProps }) {
## Useful links
- [Docs for Next.js Script component](https://nextjs.org/docs/basic-features/script)
- [Docs for Next.js Script component](/docs/pages/building-your-application/optimizing/scripts)

View file

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

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/building-your-application/styling/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/building-your-application/styling/sass)

View file

@ -1,16 +1,18 @@
# Install `sharp` to Use Built-In Image Optimization
---
title: 'Install `sharp` to Use Built-In Image Optimization'
---
#### Why This Error Occurred
## Why This Error Occurred
Using Next.js' built-in [Image Optimization](https://nextjs.org/docs/basic-features/image-optimization) requires [sharp](https://www.npmjs.com/package/sharp) as a dependency.
Using Next.js' built-in [Image Optimization](/docs/pages/building-your-application/optimizing/images) 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
## Possible Ways to Fix It
Option 1: Use a different version of Node.js and try to install `sharp` again.
```bash
```bash filename="Terminal"
npm i sharp
# or
yarn add sharp

View file

@ -1,18 +1,20 @@
# Invalid API Route Status/Body Response
---
title: Invalid API Route Status/Body Response
---
#### Why This Error Occurred
## 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
## 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
```js filename="pages/api/example.js"
export default function handler(req, res) {
res.status(204).send('invalid body')
}
@ -20,13 +22,13 @@ export default function handler(req, res) {
After
```js
```js filename="pages/api/example.js"
export default function handler(req, res) {
res.status(204).end()
}
```
### Useful Links
## Useful Links
- [204 status code documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204)
- [304 status code documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304)

View file

@ -1,16 +1,18 @@
# Invalid assetPrefix
---
title: 'Invalid `assetPrefix`'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
Ensure that `assetPrefix` is a `string`.
Example:
```js
```js filename="next.config.js"
module.exports = {
assetPrefix: '/',
}

View file

@ -1,14 +1,16 @@
# Invalid options type in a `next/dynamic` call
---
title: 'Invalid options type in a `next/dynamic` call'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
**Before**
```jsx
```jsx filename="example.js"
import dynamic from 'next/dynamic'
const options = { loading: () => <p>...</p>, ssr: false }
@ -17,7 +19,7 @@ const DynamicComponent = dynamic(() => import('../components/hello'), options)
**After**
```jsx
```jsx filename="example.js"
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/hello'), {
@ -26,6 +28,6 @@ const DynamicComponent = dynamic(() => import('../components/hello'), {
})
```
### Useful Links
## Useful Links
- [Dynamic Import](https://nextjs.org/docs/advanced-features/dynamic-import)
- [Dynamic Import](/docs/pages/building-your-application/optimizing/lazy-loading)

View file

@ -1,12 +1,14 @@
# Invalid Usage of `suspense` Option of `next/dynamic`
---
title: 'Invalid Usage of `suspense` Option of `next/dynamic`'
---
#### Why This Error Occurred
## 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
## Possible Ways to Fix It
**If you are using `{ suspense: true }` with React version older than 18**
@ -26,6 +28,6 @@ Next.js will use `React.lazy` when `suspense` is set to true, when your dynamic-
You should remove `loading` from `next/dynamic` usages, and use `<Suspense />`'s `fallback` prop.
### Useful Links
## Useful Links
- [Dynamic Import Suspense Usage](https://nextjs.org/docs/advanced-features/dynamic-import#with-suspense)
- [Dynamic Import Suspense Usage](/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic)

View file

@ -1,13 +1,15 @@
# Invalid External Rewrite
---
title: Invalid External Rewrite
---
#### Why This Error Occurred
## 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
## 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
## Useful Links
- [Rewrites section in Documentation](https://nextjs.org/docs/api-reference/next.config.js/rewrites)
- [Rewrites section in Documentation](/docs/pages/api-reference/next-config-js/rewrites)

View file

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

View file

@ -1,41 +0,0 @@
# 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
export async function getStaticPaths() {
return {
paths: Array<string | { params: { [key: string]: string } }>,
fallback: boolean
}
}
```
There are two required properties:
1. `paths`: this property is an [Array](https://developer.mozilla.org/en-US/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/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or an [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that explicitly defines all URL `params`.
```js
// pages/blog/[slug].js
export async function getStaticPaths() {
return {
paths: [
// String variant:
'/blog/first-post',
// Object variant:
{ params: { slug: 'second-post' } },
],
fallback: true,
}
}
```
1. `fallback`: this property can be a [Boolean](https://developer.mozilla.org/en-US/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,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/en-US/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/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or an [Object](https://developer.mozilla.org/en-US/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/en-US/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

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

View file

@ -1,6 +1,8 @@
# Invalid href passed to router
---
title: 'Invalid `href` passed to router'
---
#### Why This Error Occurred
## 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.
@ -9,10 +11,10 @@ Either you passed a non-internal `href` to a `next/link` component or you called
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
## 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
## Useful Links
- [Routing section in Documentation](https://nextjs.org/docs/routing/introduction)
- [Routing section in Documentation](/docs/pages/building-your-application/routing)

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