@@ -17,7 +16,7 @@ description: Start a Next.js app programmatically using a custom server.
By default, Next.js includes its own server with `next start`. If you have an existing backend, you can still use it with Next.js (this is not a custom server). A custom Next.js server allows you to start a server 100% programmatically in order to use custom server patterns. Most of the time, you will not need this – but it's available for complete customization.
-> **Note:** A custom server **can not** be deployed on [Vercel](https://vercel.com/solutions/nextjs).
+> **Note:** A custom server **cannot** be deployed on [Vercel](https://vercel.com/solutions/nextjs).
> Before deciding to use a custom server, please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like **serverless functions** and **[Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md).**
@@ -30,33 +29,42 @@ const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
-const app = next({ dev })
+const hostname = 'localhost'
+const port = 3000
+// when using middleware `hostname` and `port` must be provided below
+const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
app.prepare().then(() => {
- createServer((req, res) => {
- // Be sure to pass `true` as the second argument to `url.parse`.
- // This tells it to parse the query portion of the URL.
- const parsedUrl = parse(req.url, true)
- const { pathname, query } = parsedUrl
-
- if (pathname === '/a') {
- app.render(req, res, '/a', query)
- } else if (pathname === '/b') {
- app.render(req, res, '/b', query)
- } else {
- handle(req, res, parsedUrl)
+ createServer(async (req, res) => {
+ try {
+ // Be sure to pass `true` as the second argument to `url.parse`.
+ // This tells it to parse the query portion of the URL.
+ const parsedUrl = parse(req.url, true)
+ const { pathname, query } = parsedUrl
+
+ if (pathname === '/a') {
+ await app.render(req, res, '/a', query)
+ } else if (pathname === '/b') {
+ await app.render(req, res, '/b', query)
+ } else {
+ await handle(req, res, parsedUrl)
+ }
+ } catch (err) {
+ console.error('Error occurred handling', req.url, err)
+ res.statusCode = 500
+ res.end('internal server error')
}
- }).listen(3000, (err) => {
+ }).listen(port, (err) => {
if (err) throw err
- console.log('> Ready on http://localhost:3000')
+ console.log(`> Ready on http://${hostname}:${port}`)
})
})
```
> `server.js` doesn't go through babel or webpack. Make sure the syntax and sources this file requires are compatible with the current node version you are running.
-Then, to run the custom server you'll need to update the `scripts` in `package.json`, like so:
+To run the custom server you'll need to update the `scripts` in `package.json` like so:
```json
"scripts": {
diff --git a/docs/advanced-features/debugging.md b/docs/advanced-features/debugging.md
index d400d334367d..2cbcafec8834 100644
--- a/docs/advanced-features/debugging.md
+++ b/docs/advanced-features/debugging.md
@@ -4,74 +4,99 @@ description: Debug your Next.js app.
# Debugging
-This documentation explains how you can debug your Next.js frontend and backend code with full source maps support using either the [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools) or the [VSCode debugger](https://code.visualstudio.com/docs/editor/debugging).
+This documentation explains how you can debug your Next.js frontend and backend code with full source maps support using either the [VS Code debugger](https://code.visualstudio.com/docs/editor/debugging) or [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools).
-It requires you to first launch your Next.js application in debug mode in one terminal and then connect an inspector (Chrome DevTools or VS Code) to it.
+Any debugger that can attach to Node.js can also be used to debug a Next.js application. You can find more details in the Node.js [Debugging Guide](https://nodejs.org/en/docs/guides/debugging-getting-started/).
-There might be more ways to debug a Next.js application since all it requires is to expose the Node.js debugger and start an inspector client. You can find more details in the [Node.js documentation](https://nodejs.org/en/docs/guides/debugging-getting-started/).
+## Debugging with VS Code
-## Step 1: Start Next.js in debug mode
+Create a file named `.vscode/launch.json` at the root of your project with the following content:
-Next.js being a Node.js application, all we have to do is to pass down the [`--inspect`](https://nodejs.org/api/cli.html#cli_node_options_options) flag to the underlying Node.js process for it to start in debug mode.
+```json
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Next.js: debug server-side",
+ "type": "node-terminal",
+ "request": "launch",
+ "command": "npm run dev"
+ },
+ {
+ "name": "Next.js: debug client-side",
+ "type": "pwa-chrome",
+ "request": "launch",
+ "url": "http://localhost:3000"
+ },
+ {
+ "name": "Next.js: debug full stack",
+ "type": "node-terminal",
+ "request": "launch",
+ "command": "npm run dev",
+ "console": "integratedTerminal",
+ "serverReadyAction": {
+ "pattern": "started server on .+, url: (https?://.+)",
+ "uriFormat": "%s",
+ "action": "debugWithChrome"
+ }
+ }
+ ]
+}
+```
+
+`npm run dev` can be replaced with `yarn dev` if you're using Yarn. If you're [changing the port number](/docs/api-reference/cli#development) your application starts on, replace the `3000` in `http://localhost:3000` with the port you're using instead.
+
+Now go to the Debug panel (Ctrl+Shift+D on Windows/Linux, ⇧+⌘+D on macOS), select a launch configuration, then press F5 or select **Debug: Start Debugging** from the Command Palette to start your debugging session.
+
+## Debugging with Chrome DevTools
+
+### Client-side code
-First, start Next.js with the inspect flag:
+Start your development server as usual by running `next dev`, `npm run dev`, or `yarn dev`. Once the server starts, open `http://localhost:3000` (or your alternate URL) in Chrome. Next, open Chrome's Developer Tools (Ctrl+Shift+J on Windows/Linux, ⌥+⌘+I on macOS), then go to the **Sources** tab.
+
+Now, any time your client-side code reaches a [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) statement, code execution will pause and that file will appear in the debug area. You can also press Ctrl+P on Windows/Linux or ⌘+P on macOS to search for a file and set breakpoints manually. Note that when searching here, your source files will have paths starting with `webpack://_N_E/./`.
+
+### Server-side code
+
+To debug server-side Next.js code with Chrome DevTools, you need to pass the [`--inspect`](https://nodejs.org/api/cli.html#cli_inspect_host_port) flag to the underlying Node.js process:
```bash
NODE_OPTIONS='--inspect' next dev
```
-If you're using `npm run dev` or `yarn dev` (See: [Getting Started](/docs/getting-started.md)) then you should update the `dev` script on your `package.json`:
+If you're using `npm run dev` or `yarn dev` (see [Getting Started](/docs/getting-started)) then you should update the `dev` script on your `package.json`:
```json
"dev": "NODE_OPTIONS='--inspect' next dev"
```
-The result of launching Next.js with the inspect flag looks like this:
+Launching the Next.js dev server with the `--inspect` flag will look something like this:
```bash
Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95
For help, see: https://nodejs.org/en/docs/inspector
-ready - started server on http://localhost:3000
+ready - started server on 0.0.0.0:3000, url: http://localhost:3000
```
-> Be aware that using `NODE_OPTIONS='--inspect' npm run dev` or `NODE_OPTIONS='--inspect' yarn dev` won't work. This would try to start multiple debuggers on the same port: one for the npm/yarn process and one for Next.js. You would then get an error like `Starting inspector on 127.0.0.1:9229 failed: address already in use` in your console.
-
-## Step 2: Connect to the debugger
+> Be aware that running `NODE_OPTIONS='--inspect' npm run dev` or `NODE_OPTIONS='--inspect' yarn dev` won't work. This would try to start multiple debuggers on the same port: one for the npm/yarn process and one for Next.js. You would then get an error like `Starting inspector on 127.0.0.1:9229 failed: address already in use` in your console.
-### Using Chrome DevTools
+Once the server starts, open a new tab in Chrome and visit `chrome://inspect`, where you should see your Next.js application inside the **Remote Target** section. Click **inspect** under your application to open a separate DevTools window, then go to the **Sources** tab.
-Once you open a new tab in Google Chrome and go to `chrome://inspect`, you should see your Next.js application inside the "Remote Target" section. Now click "inspect" to open a screen that will be your debugging environment from now on.
+Debugging server-side code here works much like debugging client-side code with Chrome DevTools, except that when you search for files here with Ctrl+P or ⌘+P, your source files will have paths starting with `webpack://{application-name}/./` (where `{application-name}` will be replaced with the name of your application according to your `package.json` file).
-### Using the Debugger in Visual Studio Code
+### Debugging on Windows
-We will be using the [attach mode](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_setting-up-an-attach-configuration) of VS Code to attach the VS Code inspector to our running debugger started in step 1.
-
-Create a file named `.vscode/launch.json` at the root of your project with this content:
+Windows users may run into an issue when using `NODE_OPTIONS='--inspect'` as that syntax is not supported on Windows platforms. To get around this, install the [`cross-env`](https://www.npmjs.com/package/cross-env) package as a development dependency (`--dev` with NPM or `-D` for Yarn) and replace the `dev` script with the following.
```json
-{
- "version": "0.2.0",
- "configurations": [
- {
- "type": "node",
- "request": "attach",
- "name": "Attach to application",
- "skipFiles": ["/**"],
- "port": 9229
- }
- ]
-}
+"dev": "cross-env NODE_OPTIONS='--inspect' next dev",
```
-Now hit F5 or select **Debug: Start Debugging** from the Command Palette and you can start your debugging session.
-
-## Step 3: Put breakpoints and see what happens
-
-Now you can use the [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) statement to pause your backend or frontend code anytime you want to observe and debug your code more precisely.
+`cross-env` will set the `NODE_OPTIONS` environment variable regardless of which platform you are on (including Mac, Linux, and Windows) and allow you to debug consistently across devices and operating systems.
-If you trigger the underlying code by refreshing the current page, clicking on a page link or fetching an API route, your code will be paused and the debugger window will appear.
+## More information
-To learn more on how to use a JavaScript debugger, take a look at the following documentation:
+To learn more about how to use a JavaScript debugger, take a look at the following documentation:
-- [VS Code Node.js debugging: Breakpoints](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_breakpoints)
-- [Get Started with Debugging JavaScript in Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools/javascript)
+- [Node.js debugging in VS Code: Breakpoints](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_breakpoints)
+- [Chrome DevTools: Debug JavaScript](https://developers.google.com/web/tools/chrome-devtools/javascript)
diff --git a/docs/advanced-features/i18n-routing.md b/docs/advanced-features/i18n-routing.md
index 219a9956e5aa..0a55f52ffd69 100644
--- a/docs/advanced-features/i18n-routing.md
+++ b/docs/advanced-features/i18n-routing.md
@@ -100,6 +100,8 @@ module.exports = {
domains: [
{
+ // Note: subdomains must be included in the domain value to be matched
+ // e.g. www.example.com should be used if that is the expected hostname
domain: 'example.com',
defaultLocale: 'en-US',
},
@@ -122,6 +124,7 @@ module.exports = {
For example if you have `pages/blog.js` the following urls will be available:
- `example.com/blog`
+- `www.example.com/blog`
- `example.fr/blog`
- `example.nl/blog`
- `example.nl/nl-BE/blog`
@@ -139,6 +142,57 @@ When using Domain Routing, if a user with the `Accept-Language` header `fr;q=0.9
When using Sub-path Routing, the user would be redirected to `/fr`.
+### Prefixing the Default Locale
+
+With Next.js 12 and [Middleware](/docs/middleware.md), we can add a prefix to the default locale with a [workaround](https://github.com/vercel/next.js/discussions/18419).
+
+For example, here's a `next.config.js` file with support for a few languages. Note the `"default"` locale has been added intentionally.
+
+```js
+// next.config.js
+
+module.exports = {
+ i18n: {
+ locales: ['default', 'en', 'de', 'fr'],
+ defaultLocale: 'default',
+ localeDetection: false,
+ },
+ trailingSlash: true,
+}
+```
+
+Next, we can use [Middleware](/docs/middleware.md) to add custom routing rules:
+
+```js
+// pages/_middleware.ts
+
+import { NextRequest, NextResponse } from 'next/server'
+
+const PUBLIC_FILE = /\.(.*)$/
+
+const stripDefaultLocale = (str: string): string => {
+ const stripped = str.replace('/default', '')
+ return stripped
+}
+
+export function middleware(request: NextRequest) {
+ const shouldHandleLocale =
+ !PUBLIC_FILE.test(request.nextUrl.pathname) &&
+ !request.nextUrl.pathname.includes('/api/') &&
+ request.nextUrl.locale === 'default'
+
+ return shouldHandleLocale
+ ? NextResponse.redirect(
+ `/en${stripDefaultLocale(request.nextUrl.pathname)}${
+ request.nextUrl.search
+ }`
+ )
+ : undefined
+}
+```
+
+This [Middleware](/docs/middleware.md) skips adding the default prefix to [API Routes](/docs/api-routes/introduction.md) and [public](/docs/basic-features/static-file-serving.md) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`.
+
### Disabling Automatic Locale Detection
The automatic locale detection can be disabled with:
@@ -162,7 +216,7 @@ You can access the locale information via the Next.js router. For example, using
- `locales` contains all configured locales.
- `defaultLocale` contains the configured default locale.
-When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) provided to the function.
+When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching/get-static-props.md) provided to the function.
When leveraging `getStaticPaths`, the configured locales are provided in the context parameter of the function under `locales` and the configured defaultLocale under `defaultLocale`.
@@ -204,6 +258,18 @@ export default function IndexPage(props) {
}
```
+Note that to handle switching only the `locale` while preserving all routing information such as [dynamic route](/docs/routing/dynamic-routes.md) query values or hidden href query values, you can provide the `href` parameter as an object:
+
+```jsx
+import { useRouter } from 'next/router'
+const router = useRouter()
+const { pathname, asPath, query } = router
+// change just the locale and maintain all other route information including href's query
+router.push({ pathname, query }, asPath, { locale: nextLocale })
+```
+
+See [here](/docs/api-reference/next/router.md#with-url-object) for more information on the object structure for `router.push`.
+
If you have a `href` that already includes the locale you can opt-out of automatically handling the locale prefixing:
```jsx
@@ -236,7 +302,7 @@ Next.js doesn't know about variants of a page so it's up to you to add the `href
### Dynamic Routes and `getStaticProps` Pages
-For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example:
+For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example:
```js
// pages/blog/[slug].js
@@ -256,7 +322,7 @@ For [Automatically Statically Optimized](/docs/advanced-features/automatic-stati
For example, if you have 50 locales configured with 10 non-dynamic pages using `getStaticProps`, this means `getStaticProps` will be called 500 times. 50 versions of the 10 pages will be generated during each build.
-To decrease the build time of dynamic pages with `getStaticProps`, use a [`fallback` mode](https://nextjs.org/docs/basic-features/data-fetching#fallback-true). This allows you to return only the most popular paths and locales from `getStaticPaths` for prerendering during the build. Then, Next.js will build the remaining pages at runtime as they are requested.
+To decrease the build time of dynamic pages with `getStaticProps`, use a [`fallback` mode](/docs/api-reference/data-fetching/get-static-paths#fallback-true). This allows you to return only the most popular paths and locales from `getStaticPaths` for prerendering during the build. Then, Next.js will build the remaining pages at runtime as they are requested.
### Automatically Statically Optimized Pages
@@ -294,4 +360,4 @@ export async function getStaticProps({ locale }) {
- `locales`: 100 total locales
- `domains`: 100 total locale domain items
-> **Note:** These limits have been added initially to prevent potential [performance issues at build time](#dynamic-routes-and-getStaticProps-pages). We are continuing to evaluate if these limits are sufficient.
+> **Note:** These limits have been added initially to prevent potential [performance issues at build time](#dynamic-routes-and-getStaticProps-pages). You can workaround these limits with custom routing using [Middleware](/docs/middleware.md) in Next.js 12.
diff --git a/docs/advanced-features/measuring-performance.md b/docs/advanced-features/measuring-performance.md
index 789d94bb8759..0a861b416473 100644
--- a/docs/advanced-features/measuring-performance.md
+++ b/docs/advanced-features/measuring-performance.md
@@ -164,7 +164,7 @@ export function reportWebVitals(metric) {
> ```js
> export function reportWebVitals({ id, name, label, value }) {
> // Use `window.gtag` if you initialized Google Analytics as this example:
-> // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_document.js
+> // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js
> window.gtag('event', name, {
> event_category:
> label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
diff --git a/docs/advanced-features/output-file-tracing.md b/docs/advanced-features/output-file-tracing.md
new file mode 100644
index 000000000000..844190514753
--- /dev/null
+++ b/docs/advanced-features/output-file-tracing.md
@@ -0,0 +1,54 @@
+---
+description: Next.js automatically traces which files are needed by each page to allow for easy deployment of your application. Learn how it works here.
+---
+
+# Output File Tracing
+
+During a build, Next.js will automatically trace each page and its dependencies to determine all of the files that are needed for deploying a production version of your application.
+
+This feature helps reduce the size of deployments drastically. Previously, when deploying with Docker you would need to have all files from your package's `dependencies` installed to run `next start`. Starting with Next.js 12, you can leverage Output File Tracing in the `.next/` directory to only include the necessary files.
+
+Furthermore, this removes the need for the deprecated `serverless` target which can cause various issues and also creates unnecessary duplication.
+
+## How It Works
+
+During `next build`, Next.js will use [`@vercel/nft`](https://github.com/vercel/nft) to statically analyze `import`, `require`, and `fs` usage to determine all files that a page might load.
+
+Next.js' production server is also traced for its needed files and output at `.next/next-server.js.nft.json` which can be leveraged in production.
+
+To leverage the `.nft.json` files emitted to the `.next` output directory, you can read the list of files in each trace which are relative to the `.nft.json` file and then copy them to your deployment location.
+
+## Automatically Copying Traced Files (experimental)
+
+Next.js can automatically create a `standalone` folder which copies only the necessary files for a production deployment including select files in `node_modules`.
+
+To leverage this automatic copying you can enable it in your `next.config.js`:
+
+```js
+module.exports = {
+ experimental: {
+ outputStandalone: true,
+ },
+}
+```
+
+This will create a folder at `.next/standalone` which can then be deployed on it's own without installing `node_modules`.
+
+Additionally, a minimal `server.js` file is also output which can be used instead of `next start`. This minimal server does not copy the `.next/static` directory by default as this should ideally be handled by a CDN instead, although it can be copied to the `standalone` folder manually and the `server.js` file will serve it automatically.
+
+## Caveats
+
+- While tracing in monorepo setups, the project directory is used for tracing by default. For `next build packages/web-app`, `packages/web-app` would be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can set `experimental.outputFileTracingRoot` in your `next.config.js`.
+
+```js
+// packages/web-app/next.config.js
+module.exports = {
+ experimental: {
+ // this includes files from the monorepo base two directories up
+ outputFileTracingRoot: path.join(__dirname, '../../'),
+ },
+}
+```
+
+- There are some cases that Next.js might fail to include required files, or might incorrectly include unused files. In those cases, you can export page configs props `unstable_includeFiles` and `unstable_excludeFiles` respectively. Each prop accepts an array of [globs]() relative to the project's root to either include or exclude in the trace.
+- Currently, Next.js does not do anything with the emitted `.nft.json` files. The files must be read by your deployment platform, for example [Vercel](https://vercel.com), to create a minimal deployment. In a future release, a new command is planned to utilize these `.nft.json` files.
diff --git a/docs/advanced-features/preview-mode.md b/docs/advanced-features/preview-mode.md
index 98d1ae6698cb..8ef9c7a9fe1d 100644
--- a/docs/advanced-features/preview-mode.md
+++ b/docs/advanced-features/preview-mode.md
@@ -23,10 +23,11 @@ description: Next.js has the preview mode for statically generated pages. You ca
-In the [Pages documentation](/docs/basic-features/pages.md) and the [Data Fetching documentation](/docs/basic-features/data-fetching.md), we talked about how to pre-render a page at build time (**Static Generation**) using `getStaticProps` and `getStaticPaths`.
+In the [Pages documentation](/docs/basic-features/pages.md) and the [Data Fetching documentation](/docs/basic-features/data-fetching/overview.md), we talked about how to pre-render a page at build time (**Static Generation**) using `getStaticProps` and `getStaticPaths`.
Static Generation is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to **preview** the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to bypass Static Generation only for this specific case.
@@ -185,6 +186,8 @@ export default function handler(req, res) {
}
```
+> **Note:** If calling this route using `Link` component, you must pass in `prefetch={false}` to prevent calling `clearPreviewData` during prefetch.
+
### Specify the preview mode duration
`setPreviewData` takes an optional second parameter which should be an options object. It accepts the following keys:
@@ -229,7 +232,7 @@ This ensures that the bypass cookie can’t be guessed.
The following pages might also be useful.
-
+ Data Fetching:
Learn more about data fetching in Next.js.
diff --git a/docs/advanced-features/react-18.md b/docs/advanced-features/react-18.md
new file mode 100644
index 000000000000..1d82c82b71b4
--- /dev/null
+++ b/docs/advanced-features/react-18.md
@@ -0,0 +1,154 @@
+# React 18
+
+[React 18](https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html) adds new features including, Suspense, automatic batching of updates, APIs like `startTransition`, and a new streaming API for server rendering with support for `React.lazy`.
+
+React 18 is in RC now. Read more about React 18's [release plan](https://github.com/reactwg/react-18/discussions) and discussions from the [working group](https://github.com/reactwg/react-18/discussions).
+
+### React 18 Usage in Next.js
+
+Ensure you have the `rc` npm tag of React installed:
+
+```jsx
+npm install next@latest react@rc react-dom@rc
+```
+
+That's all! You can now start using React 18's new APIs like `startTransition` and `Suspense` in Next.js.
+
+### Enable SSR Streaming (Alpha)
+
+Concurrent features in React 18 include built-in support for server-side Suspense and SSR streaming support, allowing you to server-render pages using HTTP streaming.
+
+This is an experimental feature in Next.js 12, but once enabled, SSR will use the same [Edge Runtime](/docs/api-reference/edge-runtime.md) as [Middleware](/docs/middleware.md).
+
+To enable, use the experimental flag `concurrentFeatures: true`:
+
+```jsx
+// next.config.js
+module.exports = {
+ experimental: {
+ concurrentFeatures: true,
+ },
+}
+```
+
+Once enabled, you can use Suspense and SSR streaming for all pages. This also means that you can use Suspense-based data-fetching, `next/dynamic`, and React's built-in `React.lazy` with Suspense boundaries.
+
+```jsx
+import dynamic from 'next/dynamic'
+import { lazy, Suspense } from 'react'
+
+import Content from '../components/content'
+
+// These two ways are identical:
+const Profile = dynamic(() => import('./profile'), { suspense: true })
+const Footer = lazy(() => import('./footer'))
+
+export default function Home() {
+ return (
+
+ )
+}
+```
+
+## React Server Components
+
+React Server Components allow us to render everything, including the components themselves, on the server. This is fundamentally different from server-side rendering where you're pre-generating HTML on the server. With Server Components, there's **zero client-side JavaScript needed,** making page rendering faster. This improves the user experience of your application, pairing the best parts of server-rendering with client-side interactivity.
+
+### Enable React Server Components (Alpha)
+
+To use React Server Components, ensure you have React 18 installed. Then, turn on the `concurrentFeatures` and `serverComponents` options in `next.config.js`:
+
+```jsx
+// next.config.js
+module.exports = {
+ experimental: {
+ concurrentFeatures: true,
+ serverComponents: true,
+ },
+}
+```
+
+Next, if you already have customized `pages/_document` component, you need to remove the `getInitialProps` static method and the `getServerSideProps` export if there’s any, otherwise it won't work with server components. If no custom Document component is provided, Next.js will fallback to a default one like below.
+
+```jsx
+// pages/_document.js
+import { Html, Head, Main, NextScript } from 'next/document'
+
+export default function Document() {
+ return (
+
+
+
+
+
+
+
+ )
+}
+```
+
+Then, you can start using React Server Components. [See our example](https://github.com/vercel/next-rsc-demo) for more information.
+
+### Server Components APIs (Alpha)
+
+To run a component on the server, append `.server.js` to the end of the filename. For example `./pages/home.server.js` is a Server Component.
+
+For client components, add `.client.js`. For example, `./components/avatar.client.js`.
+
+You can then import other server or client components from any server component. Note: a server component **can not** be imported by a client component. Components without "server/client" extensions will be treated as "universal component" and can be used and rendered by both sides, depending on where it is imported. For example:
+
+```jsx
+// pages/home.server.js
+
+import { Suspense } from 'react'
+
+import Profile from '../components/profile.server'
+import Content from '../components/content.client'
+
+export default function Home() {
+ return (
+
+
Welcome to React Server Components
+
+
+
+
+
+ )
+}
+```
+
+The `` and `` components will always be server-side rendered and streamed to the client, and will not be included by the client runtime. However `` will still be hydrated on the client-side, like normal React components.
+
+To see a full example, check out [link to the demo and repository](https://github.com/vercel/next-rsc-demo).
+
+## **Supported Next.js APIs**
+
+- `next/link` / `next/image`
+- `next/document` / `next/app`
+- Dynamic routing
+
+## **Unsupported Next.js APIs**
+
+While RSC and SSR streaming is still in the alpha stage, not all Next.js APIs are supported. The following Next.js APIs have limited functionality inside Server Components:
+
+- React internals: Most of React hooks such as `useContext`, `useState`, `useReducer`, `useEffect` and `useLayoutEffect` are not supported as of today since Server Components are executed per requests and aren't stateful.
+- `next/head`
+- Partial: Note that Inside `.client.js` components `useRouter` is supported
+- Styled JSX
+- CSS Modules
+- Next.js I18n
+- `getInitialProps`, `getStaticProps` and `getStaticPaths`
+
+React 18 without SSR streaming isn't affected.
diff --git a/docs/advanced-features/security-headers.md b/docs/advanced-features/security-headers.md
index c51718bdcb08..521ab7be2869 100644
--- a/docs/advanced-features/security-headers.md
+++ b/docs/advanced-features/security-headers.md
@@ -18,7 +18,7 @@ module.exports = {
return [
{
// Apply these headers to all routes in your application.
- source: '/(.*)',
+ source: '/:path*',
headers: securityHeaders,
},
]
@@ -43,7 +43,7 @@ This header controls DNS prefetching, allowing browsers to proactively perform d
This header informs browsers it should only be accessed using HTTPS, instead of using HTTP. Using the configuration below, all present and future subdomains will use HTTPS for a `max-age` of 2 years. This blocks access to pages or subdomains that can only be served over HTTP.
-If you're deploying to [Vercel](https://vercel.com/docs/edge-network/headers#strict-transport-security), this header is not necessary as it's automatically added to all deployments.
+If you're deploying to [Vercel](https://vercel.com/docs/edge-network/headers#strict-transport-security), this header is not necessary as it's automatically added to all deployments unless you declare [`headers`](/docs/api-reference/next.config.js/headers.md) in your `next.config.js`.
```jsx
{
@@ -113,10 +113,29 @@ This header helps prevent cross-site scripting (XSS), clickjacking and other cod
You can read about the many different CSP options [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).
+You can add Content Security Policy directives using a template string.
+
+```jsx
+// Before defining your Security Headers
+// add Content Security Policy directives using a template string.
+
+const ContentSecurityPolicy = `
+ default-src 'self';
+ script-src 'self';
+ child-src example.com;
+ style-src 'self' example.com;
+ font-src 'self';
+`
+```
+
+When a directive uses a keyword such as `self`, wrap it in single quotes `''`.
+
+In the header's value, replace the new line with an empty string.
+
```jsx
{
key: 'Content-Security-Policy',
- value: // Your CSP Policy
+ value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
}
```
diff --git a/docs/advanced-features/src-directory.md b/docs/advanced-features/src-directory.md
index 00a162832382..6bb496833fd5 100644
--- a/docs/advanced-features/src-directory.md
+++ b/docs/advanced-features/src-directory.md
@@ -11,7 +11,7 @@ The `src` directory is very common in many apps and Next.js supports it by defau
## Caveats
- `src/pages` will be ignored if `pages` is present in the root directory
-- Config files like `next.config.js` and `tsconfig.json` should be inside the root directory, moving them to `src` won't work. Same goes for the [`public` directory](/docs/basic-features/static-file-serving.md)
+- Config files like `next.config.js` and `tsconfig.json`, as well as environment variables, should be inside the root directory, moving them to `src` won't work. Same goes for the [`public` directory](/docs/basic-features/static-file-serving.md)
## Related
diff --git a/docs/advanced-features/static-html-export.md b/docs/advanced-features/static-html-export.md
index c217b55d952a..6408adf0b7c6 100644
--- a/docs/advanced-features/static-html-export.md
+++ b/docs/advanced-features/static-html-export.md
@@ -11,27 +11,13 @@ description: Export your Next.js app to static HTML, and run it standalone witho
-`next export` allows you to export your app to static HTML, which can be run standalone without the need of a Node.js server.
+`next export` allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use `next export` if you don't need any of the [unsupported features](#unsupported-features) requiring a server.
-The exported app supports almost every feature of Next.js, including dynamic routes, prefetching, preloading and dynamic imports.
+If you're looking to build a hybrid site where only _some_ pages are prerendered to static HTML, Next.js already does that automatically. Learn more about [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) and [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md).
-`next export` works by prerendering all pages to HTML. For [dynamic routes](/docs/routing/dynamic-routes.md), your page can export a [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation) function to let the exporter know which HTML pages to generate for that route.
+## `next export`
-> `next export` is intended for scenarios where **none** of your pages have server-side or incremental data requirements (though statically-rendered pages can still [fetch data on the client side](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side)).
->
-> If you're looking to make a hybrid site where only _some_ pages are prerendered to static HTML, Next.js already does that automatically for you! Read up on [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) for details.
->
-> `next export` also causes features like [Incremental Static Generation](/docs/basic-features/data-fetching.md#fallback-true) and [Regeneration](/docs/basic-features/data-fetching.md#incremental-static-regeneration) to be disabled, as they require [`next start`](/docs/api-reference/cli.md#production) or a serverless deployment to function.
-
-## How to use it
-
-Develop your app as you normally do with Next.js. Then run:
-
-```bash
-next build && next export
-```
-
-For that you may want to update the scripts in your `package.json` like this:
+Update your build script in `package.json` to use `next export`:
```json
"scripts": {
@@ -39,37 +25,48 @@ For that you may want to update the scripts in your `package.json` like this:
}
```
-And run it with:
+Running `npm run build` will generate an `out` directory.
-```bash
-npm run build
-```
-
-Then you'll have a static version of your app in the `out` directory.
+`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`.
-By default `next export` doesn't require any configuration.
-It will output a static HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md), where it will call [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation) and generate pages based on the result).
For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated.
-## Deployment
+## Supported Features
+
+The majority of core Next.js features needed to build a static site are supported, including:
+
+- [Dynamic Routes when using `getStaticPaths`](/docs/routing/dynamic-routes.md)
+- Prefetching with `next/link`
+- Preloading JavaScript
+- [Dynamic Imports](/docs/advanced-features/dynamic-import.md)
+- Any styling options (e.g. CSS Modules, styled-jsx)
+- [Client-side data fetching](/docs/basic-features/data-fetching/client-side.md)
+- [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md)
+- [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md)
+- [Image Optimization](/docs/basic-features/image-optimization.md) using a [custom loader](/docs/basic-features/image-optimization.md#loader)
-By default, `next export` will generate an `out` directory, which can be served by any static hosting service or CDN.
+## Unsupported Features
-> We strongly recommend using [Vercel](https://vercel.com/) even if your Next.js app is fully static. [Vercel](https://vercel.com/) is optimized to make static Next.js apps blazingly fast. `next export` works with Zero Config deployments on Vercel.
+Features that require a Node.js server, or dynamic logic that cannot be computed during the build process, are not supported:
-## Caveats
+- [Image Optimization](/docs/basic-features/image-optimization.md) (default loader)
+- [Internationalized Routing](/docs/advanced-features/i18n-routing.md)
+- [API Routes](/docs/api-routes/introduction.md)
+- [Rewrites](/docs/api-reference/next.config.js/rewrites.md)
+- [Redirects](/docs/api-reference/next.config.js/redirects.md)
+- [Headers](/docs/api-reference/next.config.js/headers.md)
+- [Middleware](/docs/middleware.md)
+- [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md)
+- [`fallback: true`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-true)
+- [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)
-- With `next export`, we build an HTML version of your app. At export time, we call [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) for each page that exports it, and pass the result to the page's component. It's also possible to use the older [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) API instead of `getStaticProps`, but it comes with a few caveats:
+### `getInitialProps`
- - `getInitialProps` cannot be used alongside `getStaticProps` or `getStaticPaths` on any given page. If you have dynamic routes, instead of using `getStaticPaths` you'll need to configure the [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) parameter in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to let the exporter know which HTML files it should output.
- - When `getInitialProps` is called during export, the `req` and `res` fields of its [`context`](/docs/api-reference/data-fetching/getInitialProps.md#context-object) parameter will be empty objects, since during export there is no server running.
- - `getInitialProps` **will be called on every client-side navigation**, if you'd like to only fetch data at build-time, switch to `getStaticProps`.
- - `getInitialProps` should fetch from an API and cannot use Node.js-specific libraries or the file system like `getStaticProps` can.
+It's possible to use the [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) API instead of `getStaticProps`, but it comes with a few caveats:
- It's recommended to use and migrate towards `getStaticProps` over `getInitialProps` whenever possible.
+- `getInitialProps` cannot be used alongside `getStaticProps` or `getStaticPaths` on any given page. If you have dynamic routes, instead of using `getStaticPaths` you'll need to configure the [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) parameter in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to let the exporter know which HTML files it should output.
+- When `getInitialProps` is called during export, the `req` and `res` fields of its [`context`](/docs/api-reference/data-fetching/get-initial-props.md#context-object) parameter will be empty objects, since during export there is no server running.
+- `getInitialProps` **will be called on every client-side navigation**, if you'd like to only fetch data at build-time, switch to `getStaticProps`.
+- `getInitialProps` should fetch from an API and cannot use Node.js-specific libraries or the file system like `getStaticProps` can.
-- The [`fallback: true`](/docs/basic-features/data-fetching.md#fallback-true) mode of `getStaticPaths` is not supported when using `next export`.
-- [API Routes](/docs/api-routes/introduction.md) are not supported by this method because they can't be prerendered to HTML.
-- [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) cannot be used within pages because the method requires a server. Consider using [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) instead.
-- [Internationalized Routing](/docs/advanced-features/i18n-routing.md) is not supported as it requires Next.js' server-side routing.
-- The [`next/image`](/docs/api-reference/next/image.md) component's default loader is not supported when using `next export`. However, other [loader](/docs/basic-features/image-optimization.md#loader) options will work.
+We recommend migrating towards `getStaticProps` over `getInitialProps` whenever possible.
diff --git a/docs/advanced-features/using-mdx.md b/docs/advanced-features/using-mdx.md
new file mode 100644
index 000000000000..f8e932266e8f
--- /dev/null
+++ b/docs/advanced-features/using-mdx.md
@@ -0,0 +1,194 @@
+---
+description: Learn how to use @next/mdx in your Next.js project.
+---
+
+# Using MDX with Next.js
+
+MDX is a superset of markdown that lets you write JSX directly in your markdown files. It is a powerful way to add dynamic interactivity, and embed components within your content, helping you to bring your pages to life.
+
+Next.js supports MDX through a number of different means, this page will outline some of the ways you can begin integrating MDX into your Next.js project.
+
+## Why use MDX?
+
+Authoring in markdown is an intuitive way to write content, its terse syntax, once adopted, can enable you to write content that is both readable and maintainable. Because you can use `HTML` elements in your markdown, you can also get creative when styling your markdown pages.
+
+However, because markdown is essentially static content, you can't create _dynamic_ content based on user interactivity. Where MDX shines is in its ability to let you create and use your React components directly in the markup. This opens up a wide range of possibilities when composing your sites pages with interactivity in mind.
+
+## MDX Plugins
+
+Internally MDX uses remark and rehype. Remark is a markdown processor powered by a plugins ecosystem. This plugin ecosystem lets you parse code, transform `HTML` elements, change syntax, extract frontmatter, and more.
+
+Rehype is an `HTML` processor, also powered by a plugin ecosystem. Similar to remark, these plugins let you manipulate, sanitize, compile and configure all types of data, elements and content.
+
+To use a plugin from either remark or rehype, you will need to add it to the MDX packages config.
+
+## `@next/mdx`
+
+The `@next/mdx` package is configured in the `next.config.js` file at your projects root. **It sources data from local files**, allowing you to create pages with a `.mdx` extension, directly in your `/pages` directory.
+
+### Setup `@next/mdx` in Next.js
+
+The following steps outline how to setup `@next/mdx` in your Next.js project:
+
+1. Install the required packages:
+
+ ```bash
+ npm install @next/mdx @mdx-js/loader
+ ```
+
+2. Require the package and configure to support top level `.mdx` pages. The following adds the `options` object key allowing you to pass in any plugins:
+
+ ```js
+ // next.config.js
+
+ const withMDX = require('@next/mdx')({
+ extension: /\.mdx?$/,
+ options: {
+ remarkPlugins: [],
+ rehypePlugins: [],
+ // If you use `MDXProvider`, uncomment the following line.
+ // providerImportSource: "@mdx-js/react",
+ },
+ })
+ module.exports = withMDX({
+ pageExtensions: ['js', 'jsx', 'md', 'mdx'],
+ })
+ ```
+
+3. Create a new MDX page within the `/pages` directory:
+
+ ```bash
+ - /pages
+ - my-mdx-page.mdx
+ - package.json
+ ```
+
+## Using Components, Layouts and Custom Elements
+
+You can now import a React component directly inside your MDX page:
+
+```md
+import { MyComponent } from 'my-components'
+
+# My MDX page
+
+This is a list in markdown:
+
+- One
+- Two
+- Three
+
+Checkout my React component:
+
+
+```
+
+### Frontmatter
+
+Frontmatter is a YAML like key/value pairing that can be used to store data about a page. `@next/mdx` does **not** support frontmatter by default, though there are many solutions for adding frontmatter to your MDX content, such as [gray-matter](https://github.com/jonschlinkert/gray-matter).
+
+To access page metadata with `@next/mdx`, you can export a meta object from within the `.mdx` file:
+
+```md
+export const meta = {
+author: 'Rich Haines'
+}
+
+# My MDX page
+```
+
+### Layouts
+
+To add a layout to your MDX page, create a new component and import it into the MDX page. Then you can wrap the MDX page with your layout component:
+
+```md
+import { MyComponent, MyLayoutComponent } from 'my-components'
+
+export const meta = {
+author: 'Rich Haines'
+}
+
+# My MDX Page with a Layout
+
+This is a list in markdown:
+
+- One
+- Two
+- Three
+
+Checkout my React component:
+
+
+
+export default ({ children }) => {children}
+```
+
+### Custom Elements
+
+One of the pleasant aspects of using markdown, is that it maps to native `HTML` elements, making writing fast, and intuitive:
+
+```md
+# H1 heading
+
+## H2 heading
+
+This is a list in markdown:
+
+- One
+- Two
+- Three
+```
+
+The above generates the following `HTML`:
+
+```html
+
H1 heading
+
+
H2 heading
+
+
This is a list in markdown:
+
+
+
One
+
Two
+
Three
+
+```
+
+When you want to style your own elements to give a custom feel to your website or application, you can pass in shortcodes. These are your own custom components that map to `HTML` elements. To do this you use the `MDXProvider` and pass a components object as a prop. Each object key in the components object maps to a `HTML` element name. You also need to specify `providerImportSource: "@mdx-js/react"` in `next.config.js`.
+
+```jsx
+// pages/index.js
+
+import { MDXProvider } from '@mdx-js/react'
+import Image from 'next/image'
+import { Heading, Text, Pre, Code, Table } from 'my-components'
+
+const ResponsiveImage = (props) => (
+
+)
+
+const components = {
+ img: ResponsiveImage,
+ h1: Heading.H1,
+ h2: Heading.H2,
+ p: Text,
+ code: Pre,
+ inlineCode: Code,
+}
+
+export default function Post(props) {
+ return (
+
+
+
+ )
+}
+```
+
+## Helpful Links
+
+- [MDX](https://mdxjs.com)
+- [`@next/mdx`](https://www.npmjs.com/package/@next/mdx)
+- [remark](https://github.com/remarkjs/remark)
+- [rehype](https://github.com/rehypejs/rehype)
diff --git a/docs/api-reference/cli.md b/docs/api-reference/cli.md
index b79edb5f0bbc..20b36920d7bf 100644
--- a/docs/api-reference/cli.md
+++ b/docs/api-reference/cli.md
@@ -21,7 +21,7 @@ Usage
$ next
Available commands
- build, start, export, dev, lint, telemetry
+ build, start, export, dev, lint, telemetry, info
Options
--version, -v Version number
@@ -125,3 +125,36 @@ Next.js collects **completely anonymous** telemetry data about general usage.
Participation in this anonymous program is optional, and you may opt-out if you'd not like to share any information.
To learn more about Telemetry, [please read this document](https://nextjs.org/telemetry/).
+
+## Info
+
+`next info` prints relevant details about the current system which can be used to report Next.js bugs.
+This information includes Operating System platform/arch/version, Binaries (Node.js, npm, Yarn, pnpm) and npm package versions (`next`, `react`, `react-dom`).
+
+Running the following in your project's root directory:
+
+```bash
+next info
+```
+
+will give you information like this example:
+
+```bash
+
+ Operating System:
+ Platform: linux
+ Arch: x64
+ Version: #22-Ubuntu SMP Fri Nov 5 13:21:36 UTC 2021
+ Binaries:
+ Node: 16.13.0
+ npm: 8.1.0
+ Yarn: 1.22.17
+ pnpm: 6.24.2
+ Relevant packages:
+ next: 12.0.8
+ react: 17.0.2
+ react-dom: 17.0.2
+
+```
+
+This information should then be pasted into GitHub Issues.
diff --git a/docs/api-reference/create-next-app.md b/docs/api-reference/create-next-app.md
index 1192865d09c0..f463840b88b9 100644
--- a/docs/api-reference/create-next-app.md
+++ b/docs/api-reference/create-next-app.md
@@ -7,7 +7,7 @@ description: Create Next.js apps in one command with create-next-app.
The easiest way to get started with Next.js is by using `create-next-app`. This CLI tool enables you to quickly start building a new Next.js application, with everything set up for you. You can create a new app using the default Next.js template, or by using one of the [official Next.js examples](https://github.com/vercel/next.js/tree/canary/examples). To get started, use the following command:
```bash
-npx create-next-app
+npx create-next-app@latest
# or
yarn create next-app
```
@@ -15,7 +15,7 @@ yarn create next-app
You can create a [TypeScript project](https://github.com/vercel/next.js/blob/canary/docs/basic-features/typescript.md) with the `--ts, --typescript` flag:
```bash
-npx create-next-app --ts
+npx create-next-app@latest --ts
# or
yarn create next-app --typescript
```
@@ -25,7 +25,7 @@ yarn create next-app --typescript
`create-next-app` comes with the following options:
- **--ts, --typescript** - Initialize as a TypeScript project.
-- **-e, --example [name]|[github-url]** - An example to bootstrap the app with. You can use an example name from the [Next.js repo](https://github.com/vercel/next.js/tree/master/examples) or a GitHub URL. The URL can use any branch and/or subdirectory.
+- **-e, --example [name]|[github-url]** - An example to bootstrap the app with. You can use an example name from the [Next.js repo](https://github.com/vercel/next.js/tree/canary/examples) or a GitHub URL. The URL can use any branch and/or subdirectory.
- **--example-path [path-to-example]** - In a rare case, your GitHub URL might contain a branch name with a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar). In this case, you must specify the path to the example separately: `--example-path foo/bar`
- **--use-npm** - Explicitly tell the CLI to bootstrap the app using npm. To bootstrap using yarn we recommend running `yarn create next-app`
@@ -33,7 +33,7 @@ yarn create next-app --typescript
`create-next-app` allows you to create a new Next.js app within seconds. It is officially maintained by the creators of Next.js, and includes a number of benefits:
-- **Interactive Experience**: Running `npx create-next-app` (with no arguments) launches an interactive experience that guides you through setting up a project.
+- **Interactive Experience**: Running `npx create-next-app@latest` (with no arguments) launches an interactive experience that guides you through setting up a project.
- **Zero Dependencies**: Initializing a project is as quick as one second. Create Next App has zero dependencies.
- **Offline Support**: Create Next App will automatically detect if you're offline and bootstrap your project using your local package cache.
- **Support for Examples**: Create Next App can bootstrap your application using an example from the Next.js examples collection (e.g. `npx create-next-app --example api-routes`).
diff --git a/docs/api-reference/data-fetching/get-initial-props.md b/docs/api-reference/data-fetching/get-initial-props.md
new file mode 100644
index 000000000000..004ba283a4ff
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-initial-props.md
@@ -0,0 +1,126 @@
+---
+description: Enable Server-Side Rendering in a page and do initial data population with `getInitialProps`.
+---
+
+# getInitialProps
+
+**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering.
+
+`getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization).
+
+`getInitialProps` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md).
+
+`getInitialProps` is an [`async`](https://vercel.com/blog/async-and-await) function that can be added to any page as a [`static method`](https://javascript.info/static-properties-methods). Take a look at the following example:
+
+```jsx
+function Page({ stars }) {
+ return
+ }
+}
+
+export default Page
+```
+
+`getInitialProps` is used to asynchronously fetch some data, which then populates `props`.
+
+Data returned from `getInitialProps` is serialized when server rendering, similar to what [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) does. Make sure the returned object from `getInitialProps` is a plain `Object` and not using `Date`, `Map` or `Set`.
+
+For the initial page load, `getInitialProps` will run on the server only. `getInitialProps` will then run on the client when navigating to a different route via the [`next/link`](/docs/api-reference/next/link.md) component or by using [`next/router`](/docs/api-reference/next/router.md). However, if `getInitialProps` is used in a custom `_app.js`, and the page being navigated to implements `getServerSideProps`, then `getInitialProps` will run on the server.
+
+## Context Object
+
+`getInitialProps` receives a single argument called `context`, it's an object with the following properties:
+
+- `pathname` - Current route. That is the path of the page in `/pages`
+- `query` - Query string section of URL parsed as an object
+- `asPath` - `String` of the actual path (including the query) shown in the browser
+- `req` - [HTTP request object](https://nodejs.org/api/http.html#http_class_http_incomingmessage 'Class: http.IncomingMessage HTTP | Node.js v14.8.0 Documentation') (server only)
+- `res` - [HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse 'Class: http.ServerResponse HTTP | Node.js v14.8.0 Documentation') (server only)
+- `err` - Error object if any error is encountered during the rendering
+
+## Caveats
+
+- `getInitialProps` can **not** be used in children components, only in the default export of every page
+- If you are using server-side only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules), otherwise it'll slow down your app
+
+## TypeScript
+
+If you're using TypeScript, you can use the `NextPage` type for function components:
+
+```jsx
+import { NextPage } from 'next'
+
+interface Props {
+ userAgent?: string;
+}
+
+const Page: NextPage = ({ userAgent }) => (
+ Your user agent: {userAgent}
+)
+
+Page.getInitialProps = async ({ req }) => {
+ const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
+ return { userAgent }
+}
+
+export default Page
+```
+
+And for `React.Component`, you can use `NextPageContext`:
+
+```jsx
+import React from 'react'
+import { NextPageContext } from 'next'
+
+interface Props {
+ userAgent?: string;
+}
+
+export default class Page extends React.Component {
+ static async getInitialProps({ req }: NextPageContext) {
+ const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
+ return { userAgent }
+ }
+
+ render() {
+ const { userAgent } = this.props
+ return Your user agent: {userAgent}
+ }
+}
+```
+
+## Related
+
+For more information on what to do next, we recommend the following sections:
+
+
diff --git a/docs/api-reference/data-fetching/get-server-side-props.md b/docs/api-reference/data-fetching/get-server-side-props.md
new file mode 100644
index 000000000000..d7e7c1ee6ef5
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-server-side-props.md
@@ -0,0 +1,151 @@
+---
+description: API reference for `getServerSideProps`. Learn how to fetch data on each request with Next.js.
+---
+
+# getServerSideProps
+
+
+ Version History
+
+| Version | Changes |
+| --------- | ------------------------------------------------------------------- |
+| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. |
+| `v9.3.0` | `getServerSideProps` introduced. |
+
+
+
+When exporting a function called `getServerSideProps` (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. This is useful if you want to fetch data that changes often, and have the page update to show the most current data.
+
+```js
+export async function getServerSideProps(context) {
+ return {
+ props: {}, // will be passed to the page component as props
+ }
+}
+```
+
+You can import modules in top-level scope for use in `getServerSideProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getServerSideProps`**, including fetching data from your database.
+
+## Context parameter
+
+The `context` parameter is an object containing the following keys:
+
+- `params`: If this page uses a [dynamic route](/docs/routing/dynamic-routes.md), `params` contains the route parameters. If the page name is `[id].js` , then `params` will look like `{ id: ... }`.
+- `req`: [The `HTTP` IncomingMessage object](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
+- `res`: [The `HTTP` response object](https://nodejs.org/api/http.html#http_class_http_serverresponse).
+- `query`: An object representing the query string.
+- `preview`: `preview` is `true` if the page is in the [Preview Mode](/docs/advanced-features/preview-mode.md) and `false` otherwise.
+- `previewData`: The [preview](/docs/advanced-features/preview-mode.md) data set by `setPreviewData`.
+- `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).
+- `defaultLocale` contains the configured default locale (if enabled).
+
+## getServerSideProps return values
+
+The `getServerSideProps` function should return an object with **any one of the following** properties:
+
+### `props`
+
+The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) so that any props passed, could be serialized with [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
+
+```jsx
+export async function getServerSideProps(context) {
+ return {
+ props: { message: `Next.js is awesome` }, // will be passed to the page component as props
+ }
+}
+```
+
+### `notFound`
+
+The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author.
+
+```js
+export async function getServerSideProps(context) {
+ const res = await fetch(`https://.../data`)
+ const data = await res.json()
+
+ if (!data) {
+ return {
+ notFound: true,
+ }
+ }
+
+ return {
+ props: { data }, // will be passed to the page component as props
+ }
+}
+```
+
+### `redirect`
+
+The `redirect` object allows redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both.
+
+```js
+export async function getServerSideProps(context) {
+ const res = await fetch(`https://.../data`)
+ const data = await res.json()
+
+ if (!data) {
+ return {
+ redirect: {
+ destination: '/',
+ permanent: false,
+ },
+ }
+ }
+
+ return {
+ props: {}, // will be passed to the page component as props
+ }
+}
+```
+
+### getServerSideProps with TypeScript
+
+For TypeScript, you can use the `GetServerSideProps` type from `next`:
+
+```ts
+import { GetServerSideProps } from 'next'
+
+export const getServerSideProps: GetServerSideProps = async (context) => {
+ // ...
+}
+```
+
+If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`:
+
+```tsx
+import { InferGetServerSidePropsType } from 'next'
+
+type Data = { ... }
+
+export const getServerSideProps = async () => {
+ const res = await fetch('https://.../data')
+ const data: Data = await res.json()
+
+ return {
+ props: {
+ data,
+ },
+ }
+}
+
+function Page({ data }: InferGetServerSidePropsType) {
+ // will resolve posts to type Data
+}
+
+export default Page
+```
+
+## Related
+
+For more information on what to do next, we recommend the following sections:
+
+
diff --git a/docs/api-reference/data-fetching/get-static-paths.md b/docs/api-reference/data-fetching/get-static-paths.md
new file mode 100644
index 000000000000..9175bed28a72
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-static-paths.md
@@ -0,0 +1,212 @@
+---
+description: API reference for `getStaticPaths`. Learn how to fetch data and generate static pages with `getStaticPaths`.
+---
+
+# getStaticPaths
+
+
+ Version History
+
+| Version | Changes |
+| -------- | --------------------------------------------------------------------------------------------------------------- |
+| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) |
+| `v9.3.0` | `getStaticPaths` introduced. |
+
+
+
+When exporting a function called `getStaticPaths` from a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`.
+
+```jsx
+export async function getStaticPaths() {
+ return {
+ paths: [
+ { params: { ... } } // See the "paths" section below
+ ],
+ fallback: true, false or "blocking" // See the "fallback" section below
+ };
+}
+```
+
+## getStaticPaths return values
+
+The `getStaticPaths` function should return an object with the following **required** properties:
+
+### `paths`
+
+The `paths` key determines which paths will be pre-rendered. For example, suppose that you have a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md) named `pages/posts/[id].js`. If you export `getStaticPaths` from this page and return the following for `paths`:
+
+```js
+return {
+ paths: [
+ { params: { id: '1' } },
+ { params: { id: '2' } }
+ ],
+ fallback: ...
+}
+```
+
+Then, Next.js will statically generate `/posts/1` and `/posts/2` during `next build` using the page component in `pages/posts/[id].js`.
+
+The value for each `params` object must match the parameters used in the page name:
+
+- If the page name is `pages/posts/[postId]/[commentId]`, then `params` should contain `postId` and `commentId`.
+- If the page name uses [catch-all routes](/docs/routing/dynamic-routes.md#catch-all-routes) like `pages/[...slug]`, then `params` should contain `slug` (which is an array). If this array is `['hello', 'world']`, then Next.js will statically generate the page at `/hello/world`.
+- If the page uses an [optional catch-all route](/docs/routing/dynamic-routes.md#optional-catch-all-routes), use `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`.
+
+### `fallback: false`
+
+If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**.
+
+When `next build` is run, Next.js will check if `getStaticPaths` returned `fallback: false`, it will then build **only** the paths returned by `getStaticPaths`. This option is useful if you have a small number of paths to create, or new page data is not added often. If you find that you need to add more paths, and you have `fallback: false`, you will need to run `next build` again so that the new paths can be generated.
+
+The following example pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths`. Then, for each page, it fetches the post data from a CMS using [`getStaticProps`](/docs/api-reference/data-fetching/get-static-props.md).
+
+```jsx
+// pages/posts/[id].js
+
+function Post({ post }) {
+ // Render post...
+}
+
+// This function gets called at build time
+export async function getStaticPaths() {
+ // Call an external API endpoint to get posts
+ const res = await fetch('https://.../posts')
+ const posts = await res.json()
+
+ // Get the paths we want to pre-render based on posts
+ const paths = posts.map((post) => ({
+ params: { id: post.id },
+ }))
+
+ // We'll pre-render only these paths at build time.
+ // { fallback: false } means other routes should 404.
+ return { paths, fallback: false }
+}
+
+// This also gets called at build time
+export async function getStaticProps({ params }) {
+ // params contains the post `id`.
+ // If the route is like /posts/1, then params.id is 1
+ const res = await fetch(`https://.../posts/${params.id}`)
+ const post = await res.json()
+
+ // Pass post data to the page via props
+ return { props: { post } }
+}
+
+export default Post
+```
+
+### `fallback: true`
+
+
+ Examples
+
+
+
+If `fallback` is `true`, then the behavior of `getStaticProps` changes in the following ways:
+
+- The paths returned from `getStaticPaths` will be rendered to `HTML` at build time by `getStaticProps`.
+- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a [“fallback”](#fallback-pages) version of the page on the first request to such a path. Web crawlers, such as Google, won't be served a fallback and instead the path will behave as in [`fallback: 'blocking'`](#fallback-blocking).
+- In the background, Next.js will statically generate the requested path `HTML` and `JSON`. This includes running `getStaticProps`.
+- When complete, the browser receives the `JSON` for the generated path. This will be used to automatically render the page with the required props. From the user’s perspective, the page will be swapped from the fallback page to the full page.
+- At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, like other pages pre-rendered at build time.
+
+> **Note:** `fallback: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md).
+
+#### When is `fallback: true` useful?
+
+`fallback: true` is useful if your app has a very large number of static pages that depend on data (such as a very large e-commerce site). If you want to pre-render all product pages, the builds would take a very long time.
+
+Instead, you may statically generate a small subset of pages and use `fallback: true` for the rest. When someone requests a page that is not generated yet, the user will see the page with a loading indicator or skeleton component.
+
+Shortly after, `getStaticProps` finishes and the page will be rendered with the requested data. From now on, everyone who requests the same page will get the statically pre-rendered page.
+
+This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation.
+
+`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md).
+
+### `fallback: 'blocking'`
+
+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.
+
+`getStaticProps` will behave as follows:
+
+- The paths returned from `getStaticPaths` will be rendered to `HTML` at build time by `getStaticProps`.
+- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will SSR on the first request and return the generated `HTML`.
+- When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state.
+- At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, like other pages pre-rendered at build time.
+
+`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) in conjunction with `fallback: 'blocking'`.
+
+> **Note:** `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md).
+
+### Fallback pages
+
+In the “fallback” version of a page:
+
+- The page’s props will be empty.
+- Using the [router](/docs/api-reference/next/router.md), you can detect if the fallback is being rendered, `router.isFallback` will be `true`.
+
+The following example showcases using `isFallback`:
+
+```jsx
+// pages/posts/[id].js
+import { useRouter } from 'next/router'
+
+function Post({ post }) {
+ const router = useRouter()
+
+ // If the page is not yet generated, this will be displayed
+ // initially until getStaticProps() finishes running
+ if (router.isFallback) {
+ return
Loading...
+ }
+
+ // Render post...
+}
+
+// This function gets called at build time
+export async function getStaticPaths() {
+ return {
+ // Only `/posts/1` and `/posts/2` are generated at build time
+ paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
+ // Enable statically generating additional pages
+ // For example: `/posts/3`
+ fallback: true,
+ }
+}
+
+// This also gets called at build time
+export async function getStaticProps({ params }) {
+ // params contains the post `id`.
+ // If the route is like /posts/1, then params.id is 1
+ const res = await fetch(`https://.../posts/${params.id}`)
+ const post = await res.json()
+
+ // Pass post data to the page via props
+ return {
+ props: { post },
+ // Re-generate the post at most once per second
+ // if a request comes in
+ revalidate: 1,
+ }
+}
+
+export default Post
+```
+
+## getStaticPaths with TypeScript
+
+For TypeScript, you can use the `GetStaticPaths` type from `next`:
+
+```ts
+import { GetStaticPaths } from 'next'
+
+export const getStaticPaths: GetStaticPaths = async () => {
+ // ...
+}
+```
diff --git a/docs/api-reference/data-fetching/get-static-props.md b/docs/api-reference/data-fetching/get-static-props.md
new file mode 100644
index 000000000000..7e04d1d9252e
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-static-props.md
@@ -0,0 +1,244 @@
+---
+description: API reference for `getStaticProps`. Learn how to use `getStaticProps` to generate static pages with Next.js.
+---
+
+# getStaticProps
+
+
+ Version History
+
+| Version | Changes |
+| --------- | ----------------------------------------------------------------------------------------------------------------- |
+| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. |
+| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) |
+| `v9.3.0` | `getStaticProps` introduced. |
+| `v10.0.0` | `fallback: 'blocking'` return option added. |
+
+
+
+Exporting a function called `getStaticProps` will pre-render a page at build time using the props returned from the function:
+
+```jsx
+export async function getStaticProps(context) {
+ return {
+ props: {}, // will be passed to the page component as props
+ }
+}
+```
+
+You can import modules in top-level scope for use in `getStaticProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database.
+
+## Context parameter
+
+The `context` parameter is an object containing the following keys:
+
+- `params` contains the route parameters for pages using [dynamic routes](/docs/routing/dynamic-routes.md). 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` is `true` if the page is in the [Preview Mode](/docs/advanced-features/preview-mode.md) and `undefined` otherwise.
+- `previewData` contains the [preview](/docs/advanced-features/preview-mode.md) data set by `setPreviewData`.
+- `locale` contains the active locale (if enabled).
+- `locales` contains all supported locales (if enabled).
+- `defaultLocale` contains the configured default locale (if enabled).
+
+## getStaticProps return values
+
+The `getStaticProps` function should return an object containing either `props`, `redirect`, or `notFound` followed by an **optional** `revalidate` property.
+
+### `props`
+
+The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) so that any props passed, could be serialized with [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
+
+```jsx
+export async function getStaticProps(context) {
+ return {
+ props: { message: `Next.js is awesome` }, // will be passed to the page component as props
+ }
+}
+```
+
+### `revalidate`
+
+The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to `false` or no revalidation).
+
+```js
+// This function gets called at build time on server-side.
+// It may be called again, on a serverless function, if
+// revalidation is enabled and a new request comes in
+export async function getStaticProps() {
+ const res = await fetch('https://.../posts')
+ const posts = await res.json()
+
+ return {
+ props: {
+ posts,
+ },
+ // Next.js will attempt to re-generate the page:
+ // - When a request comes in
+ // - At most once every 10 seconds
+ revalidate: 10, // In seconds
+ }
+}
+```
+
+Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md)
+
+### `notFound`
+
+The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author.
+
+```js
+export async function getStaticProps(context) {
+ const res = await fetch(`https://.../data`)
+ const data = await res.json()
+
+ if (!data) {
+ return {
+ notFound: true,
+ }
+ }
+
+ return {
+ props: { data }, // will be passed to the page component as props
+ }
+}
+```
+
+> **Note**: `notFound` is not needed for [`fallback: false`](/docs/api-reference/data-fetching/get-static-paths#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered.
+
+### `redirect`
+
+The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`.
+
+In some rare cases, you might need to assign a custom status code for older `HTTP` clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, **but not both**. You can also set `basePath: false` similar to redirects in `next.config.js`.
+
+```js
+export async function getStaticProps(context) {
+ const res = await fetch(`https://...`)
+ const data = await res.json()
+
+ if (!data) {
+ return {
+ redirect: {
+ destination: '/',
+ permanent: false,
+ // statusCode: 301
+ },
+ }
+ }
+
+ return {
+ props: { data }, // will be passed to the page component as props
+ }
+}
+```
+
+If the redirects are known at build-time, they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md) instead.
+
+## Reading files: Use `process.cwd()`
+
+Files can be read directly from the filesystem in `getStaticProps`.
+
+In order to do so you have to get the full path to a file.
+
+Since Next.js compiles your code into a separate directory you can't use `__dirname` as the path it will return will be different from the pages directory.
+
+Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed.
+
+```jsx
+import { promises as fs } from 'fs'
+import path from 'path'
+
+// posts will be populated at build time by getStaticProps()
+function Blog({ posts }) {
+ return (
+
+ {posts.map((post) => (
+
+
{post.filename}
+
{post.content}
+
+ ))}
+
+ )
+}
+
+// This function gets called at build time on server-side.
+// It won't be called on client-side, so you can even do
+// direct database queries.
+export async function getStaticProps() {
+ const postsDirectory = path.join(process.cwd(), 'posts')
+ const filenames = await fs.readdir(postsDirectory)
+
+ const posts = filenames.map(async (filename) => {
+ const filePath = path.join(postsDirectory, filename)
+ const fileContents = await fs.readFile(filePath, 'utf8')
+
+ // Generally you would parse/transform the contents
+ // For example you can transform markdown to HTML here
+
+ return {
+ filename,
+ content: fileContents,
+ }
+ })
+ // By returning { props: { posts } }, the Blog component
+ // will receive `posts` as a prop at build time
+ return {
+ props: {
+ posts: await Promise.all(posts),
+ },
+ }
+}
+
+export default Blog
+```
+
+## getStaticProps with TypeScript
+
+You can use the `GetStaticProps` type from `next` to type the function:
+
+```ts
+import { GetStaticProps } from 'next'
+
+export const getStaticProps: GetStaticProps = async (context) => {
+ // ...
+}
+```
+
+If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`:
+
+```tsx
+import { InferGetStaticPropsType } from 'next'
+
+type Post = {
+ author: string
+ content: string
+}
+
+export const getStaticProps = async () => {
+ const res = await fetch('https://.../posts')
+ const posts: Post[] = await res.json()
+
+ return {
+ props: {
+ posts,
+ },
+ }
+}
+
+function Blog({ posts }: InferGetStaticPropsType) {
+ // will resolve posts to type Post[]
+}
+
+export default Blog
+```
+
+## Related
+
+For more information on what to do next, we recommend the following sections:
+
+
diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md
deleted file mode 100644
index f46b34615f56..000000000000
--- a/docs/api-reference/data-fetching/getInitialProps.md
+++ /dev/null
@@ -1,144 +0,0 @@
----
-description: Enable Server-Side Rendering in a page and do initial data population with `getInitialProps`.
----
-
-# getInitialProps
-
-> **Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)**.
->
-> If you're using Next.js 9.3 or newer, we recommend that you use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`.
->
-> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching.md).
-
-`getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization).
-
-> `getInitialProps` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md).
-
-`getInitialProps` is an [`async`](https://vercel.com/blog/async-and-await) function that can be added to any page as a [`static method`](https://javascript.info/static-properties-methods). Take a look at the following example:
-
-```jsx
-function Page({ stars }) {
- return
- }
-}
-
-export default Page
-```
-
-`getInitialProps` is used to asynchronously fetch some data, which then populates `props`.
-
-Data returned from `getInitialProps` is serialized when server rendering, similar to what [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) does. Make sure the returned object from `getInitialProps` is a plain `Object` and not using `Date`, `Map` or `Set`.
-
-For the initial page load, `getInitialProps` will run on the server only. `getInitialProps` will then run on the client when navigating to a different route via the [`next/link`](/docs/api-reference/next/link.md) component or by using [`next/router`](/docs/api-reference/next/router.md). However, if `getInitialProps` is used in a custom `_app.js`, and the page being navigated to implements `getServerSideProps`, then `getInitialProps` will run on the server.
-
-## Context Object
-
-`getInitialProps` receives a single argument called `context`, it's an object with the following properties:
-
-- `pathname` - Current route. That is the path of the page in `/pages`
-- `query` - Query string section of URL parsed as an object
-- `asPath` - `String` of the actual path (including the query) shown in the browser
-- `req` - [HTTP request object](https://nodejs.org/api/http.html#http_class_http_incomingmessage 'Class: http.IncomingMessage HTTP | Node.js v14.8.0 Documentation') (server only)
-- `res` - [HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse 'Class: http.ServerResponse HTTP | Node.js v14.8.0 Documentation') (server only)
-- `err` - Error object if any error is encountered during the rendering
-
-## Caveats
-
-- `getInitialProps` can **not** be used in children components, only in the default export of every page
-- If you are using server-side only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules), otherwise it'll slow down your app
-
-## TypeScript
-
-If you're using TypeScript, you can use the `NextPage` type for function components:
-
-```jsx
-import { NextPage } from 'next'
-
-interface Props {
- userAgent?: string;
-}
-
-const Page: NextPage = ({ userAgent }) => (
- Your user agent: {userAgent}
-)
-
-Page.getInitialProps = async ({ req }) => {
- const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
- return { userAgent }
-}
-
-export default Page
-```
-
-And for `React.Component`, you can use `NextPageContext`:
-
-```jsx
-import React from 'react'
-import { NextPageContext } from 'next'
-
-interface Props {
- userAgent?: string;
-}
-
-export default class Page extends React.Component {
- static async getInitialProps({ req }: NextPageContext) {
- const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
- return { userAgent }
- }
-
- render() {
- const { userAgent } = this.props
- return Your user agent: {userAgent}
- }
-}
-```
-
-## Related
-
-For more information on what to do next, we recommend the following sections:
-
-
diff --git a/docs/api-reference/edge-runtime.md b/docs/api-reference/edge-runtime.md
new file mode 100644
index 000000000000..3c722513acac
--- /dev/null
+++ b/docs/api-reference/edge-runtime.md
@@ -0,0 +1,99 @@
+---
+description: The Next.js Edge Runtime is based on standard Web APIs. Learn more about the supported APIs available.
+---
+
+# Edge Runtime
+
+The Next.js Edge Runtime is based on standard Web APIs, which is used by [Middleware](/docs/middleware.md).
+
+## Runtime APIs
+
+### Globals
+
+- [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
+- [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
+- [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
+
+### Base64
+
+- [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/atob): Decodes a string of data which has been encoded using base-64 encoding
+- [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/btoa): Creates a base-64 encoded ASCII string from a string of binary data
+
+### Encoding
+
+- [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder): Takes a stream of code points as input and emits a stream of bytes (UTF8)
+- [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder): Takes a stream of bytes as input and emit a stream of code points
+
+### Environment
+
+- `process.env`: Holds an object with all environment variables for both production and development in the exact same way as any other page or API in Next.js
+
+### Fetch
+
+The [Web Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) can be used from the runtime, enabling you to use Middleware as a proxy, or connect to external storage APIs
+
+A potential caveat to using the Fetch API in a Middleware function is latency. For example, if you have a Middleware function running a fetch request to New York, and a user accesses your site from London, the request will be resolved from the nearest Edge to the user (in this case, London), to the origin of the request, New York. There is a risk this could happen on every request, making your site slow to respond. When using the Fetch API, you _must_ make sure it does not run on every single request made.
+
+### Streams
+
+- [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream): Consists of a pair of streams: a writable stream known as its writable side, and a readable stream, known as its readable side. Writes to the writable side, result in new data being made available for reading from the readable side. Support for web streams is quite limited at the moment, although it is more extended in the development environment
+- [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream): A readable stream of byte data
+- [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream): A standard abstraction for writing streaming data to a destination, known as a sink
+
+### Timers
+
+- [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval): Schedules a function to execute every time a given number of milliseconds elapses
+- [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): Cancels the repeated execution set using `setInterval()`
+- [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout): Schedules a function to execute in a given amount of time
+- [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout): Cancels the delayed execution set using `setTimeout()`
+
+### Web
+
+- [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers): A [WHATWG](https://whatwg.org/) implementation of the headers API
+- [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL): A WHATWG implementation of the URL API.
+- [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams): A WHATWG implementation of `URLSearchParams`
+
+### Crypto
+
+- [`Crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto): The `Crypto` interface represents basic cryptography features available in the current context
+- [`crypto.randomUUID`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID): Lets you generate a v4 UUID using a cryptographically secure random number generator
+- [`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues): Lets you get cryptographically strong random values
+- [`crypto.subtle`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/subtle): A read-only property that returns a [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) which can then be used to perform low-level cryptographic operations
+
+### Logging
+
+- [`console.debug`](https://developer.mozilla.org/en-US/docs/Web/API/console/debug): Outputs a message to the console with the log level debug
+- [`console.info`](https://developer.mozilla.org/en-US/docs/Web/API/console/info): Informative logging of information. You may use string substitution and additional arguments with this method
+- [`console.clear`](https://developer.mozilla.org/en-US/docs/Web/API/console/clear): Clears the console
+- [`console.dir`](https://developer.mozilla.org/en-US/docs/Web/API/console/dir): Displays an interactive listing of the properties of a specified JavaScript object
+- [`console.count`](https://developer.mozilla.org/en-US/docs/Web/API/console/count): Log the number of times this line has been called with the given label
+- [`console.time`](https://developer.mozilla.org/en-US/docs/Web/API/console/time): Starts a timer with a name specified as an input parameter
+
+## Unsupported APIs
+
+The Edge Runtime has some restrictions including:
+
+- Native Node.js APIs **are not supported**. For example, you can't read or write to the filesystem
+- Node Modules _can_ be used, as long as they implement ES Modules and do not use any native Node.js APIs
+- Calling `require` directly is **not allowed**. Use ES Modules instead
+
+The following JavaScript language features are disabled, and **will not work:**
+
+- [`eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval): Evaluates JavaScript code represented as a string
+- [`new Function(evalString)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function): Creates a new function with the code provided as an argument
+
+## Related
+
+
diff --git a/docs/api-reference/next.config.js/build-indicator.md b/docs/api-reference/next.config.js/build-indicator.md
new file mode 100644
index 000000000000..cccaa3d4bfad
--- /dev/null
+++ b/docs/api-reference/next.config.js/build-indicator.md
@@ -0,0 +1,29 @@
+---
+description: In development mode, pages include an indicator to let you know if your new code it's being compiled. You can opt-out of it here.
+---
+
+# Build indicator
+
+When you edit your code, and Next.js is compiling the application, a compilation indicator appears in the bottom right corner of the page.
+
+> **Note:** This indicator is only present in development mode and will not appear when building and running the app in production mode.
+
+In some cases this indicator can be misplaced on your page, for example, when conflicting with a chat launcher. To change its position, open `next.config.js` and set the `buildActivityPosition` in the `devIndicators` object to `bottom-right` (default), `bottom-left`, `top-right` or `top-left`:
+
+```js
+module.exports = {
+ devIndicators: {
+ buildActivityPosition: 'bottom-right',
+ },
+}
+```
+
+In some cases this indicator might not be useful for you. To remove it, open `next.config.js` and disable the `buildActivity` config in `devIndicators` object:
+
+```js
+module.exports = {
+ devIndicators: {
+ buildActivity: false,
+ },
+}
+```
diff --git a/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md b/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md
index 20056521d6e7..0383f6ee6e6d 100644
--- a/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md
+++ b/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md
@@ -42,7 +42,7 @@ While `assetPrefix` covers requests to `_next/static`, it does not influence the
- Files in the [public](/docs/basic-features/static-file-serving.md) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself
- `/_next/data/` requests for `getServerSideProps` pages. These requests will always be made against the main domain since they're not static.
-- `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/basic-features/data-fetching.md#incremental-static-regeneration), even if you're not using it (for consistency).
+- `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/basic-features/data-fetching/incremental-static-regeneration.md), even if you're not using it (for consistency).
## Related
diff --git a/docs/api-reference/next.config.js/configuring-the-build-id.md b/docs/api-reference/next.config.js/configuring-the-build-id.md
index 1d22438a7c20..aba9bd2cc8ad 100644
--- a/docs/api-reference/next.config.js/configuring-the-build-id.md
+++ b/docs/api-reference/next.config.js/configuring-the-build-id.md
@@ -4,7 +4,7 @@ description: Configure the build id, which is used to identify the current build
# Configuring the Build ID
-Next.js uses a constant id generated at build time to identify which version of your application is being served. This can cause problems in multi-server deployments when `next build` is ran on every server. In order to keep a static build id between builds you can provide your own build id.
+Next.js uses a constant id generated at build time to identify which version of your application is being served. This can cause problems in multi-server deployments when `next build` is run on every server. In order to keep a consistent build id between builds you can provide your own build id.
Open `next.config.js` and add the `generateBuildId` function:
diff --git a/docs/api-reference/next.config.js/custom-page-extensions.md b/docs/api-reference/next.config.js/custom-page-extensions.md
index dc11fdc6fac1..a3f0d6132424 100644
--- a/docs/api-reference/next.config.js/custom-page-extensions.md
+++ b/docs/api-reference/next.config.js/custom-page-extensions.md
@@ -16,7 +16,7 @@ module.exports = {
> **Note**: The default value of `pageExtensions` is [`['tsx', 'ts', 'jsx', 'js']`](https://github.com/vercel/next.js/blob/f1dbc9260d48c7995f6c52f8fbcc65f08e627992/packages/next/server/config-shared.ts#L161).
-> **Note**: configuring `pageExtensions` also affects `_document.js`, `_app.js` as well as files under `pages/api/`. For example, setting `pageExtensions: ['page.tsx', 'page.ts']` means the following files: `_document.tsx`, `_app.tsx`, `pages/users.tsx` and `pages/api/users.ts` will have to be renamed to `_document.page.tsx`, `_app.page.tsx`, `pages/users.page.tsx` and `pages/api/users.page.ts` respectively.
+> **Note**: configuring `pageExtensions` also affects `_document.js`, `_app.js`, `_middleware.js` as well as files under `pages/api/`. For example, setting `pageExtensions: ['page.tsx', 'page.ts']` means the following files: `_document.tsx`, `_app.tsx`, `_middleware.ts`, `pages/users.tsx` and `pages/api/users.ts` will have to be renamed to `_document.page.tsx`, `_app.page.tsx`, `_middleware.page.ts`, `pages/users.page.tsx` and `pages/api/users.page.ts` respectively.
## Including non-page files in the `pages` directory
@@ -32,7 +32,7 @@ module.exports = {
Then rename your pages to have a file extension that includes `.page` (ex. rename `MyPage.tsx` to `MyPage.page.tsx`).
-> **Note**: Make sure you also rename `_document.js`, `_app.js` as well as files under `pages/api/`.
+> **Note**: Make sure you also rename `_document.js`, `_app.js`, `_middleware.js`, as well as files under `pages/api/`.
Without this config, Next.js assumes every tsx/ts/jsx/js file in the `pages` directory is a page or API route, and may expose unintended routes vulnerable to denial of service attacks, or throw an error like the following when building the production bundle:
diff --git a/docs/api-reference/next.config.js/exportPathMap.md b/docs/api-reference/next.config.js/exportPathMap.md
index a5e4420ffa11..a1ef9f65021f 100644
--- a/docs/api-reference/next.config.js/exportPathMap.md
+++ b/docs/api-reference/next.config.js/exportPathMap.md
@@ -40,7 +40,7 @@ module.exports = {
}
```
-Note: the `query` field in `exportPathMap` cannot be used with [automatically statically optimized pages](/docs/advanced-features/automatic-static-optimization) or [`getStaticProps` pages](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) as they are rendered to HTML files at build-time and additional query information cannot be provided during `next export`.
+Note: the `query` field in `exportPathMap` cannot be used with [automatically statically optimized pages](/docs/advanced-features/automatic-static-optimization) or [`getStaticProps` pages](/docs/basic-features/data-fetching/get-static-props.md) as they are rendered to HTML files at build-time and additional query information cannot be provided during `next export`.
The pages will then be exported as HTML files, for example, `/about` will become `/about.html`.
diff --git a/docs/api-reference/next.config.js/headers.md b/docs/api-reference/next.config.js/headers.md
index d64c01c676b7..5905a0860dd9 100644
--- a/docs/api-reference/next.config.js/headers.md
+++ b/docs/api-reference/next.config.js/headers.md
@@ -21,7 +21,7 @@ description: Add custom HTTP headers to your Next.js app.
-Headers allow you to set custom HTTP headers for an incoming request path.
+Headers allow you to set custom HTTP headers on the response to an incoming request on a given path.
To set custom HTTP headers you can use the `headers` key in `next.config.js`:
@@ -50,7 +50,7 @@ module.exports = {
`headers` is an async function that expects an array to be returned holding objects with `source` and `headers` properties:
- `source` is the incoming request path pattern.
-- `headers` is an array of header objects with the `key` and `value` properties.
+- `headers` is an array of response header objects, with `key` and `value` properties.
- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
@@ -83,7 +83,7 @@ module.exports = {
},
],
},
- ],
+ ]
},
}
```
@@ -109,7 +109,7 @@ module.exports = {
},
],
},
- ],
+ ]
},
}
```
@@ -135,7 +135,7 @@ module.exports = {
},
],
},
- ],
+ ]
},
}
```
@@ -157,7 +157,7 @@ module.exports = {
},
],
},
- ],
+ ]
},
}
```
@@ -365,7 +365,7 @@ module.exports = {
headers: [
{
key: 'x-hello',
- value: 'worlld',
+ value: 'world',
},
],
},
@@ -376,7 +376,7 @@ module.exports = {
### Cache-Control
-Cache-Control headers set in next.config.js will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](https://nextjs.org/docs/basic-features/pages#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) function.
+Cache-Control headers set in next.config.js will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](https://nextjs.org/docs/basic-features/pages#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) function.
## Related
diff --git a/docs/api-reference/next.config.js/introduction.md b/docs/api-reference/next.config.js/introduction.md
index 02bf1c5904bb..121510630502 100644
--- a/docs/api-reference/next.config.js/introduction.md
+++ b/docs/api-reference/next.config.js/introduction.md
@@ -4,7 +4,7 @@ description: learn more about the configuration file used by Next.js to handle y
# next.config.js
-For custom advanced behavior of Next.js, you can create a `next.config.js` in the root of your project directory (next to `package.json`).
+For custom advanced configuration of Next.js, you can create a `next.config.js` or `next.config.mjs` file in the root of your project directory (next to `package.json`).
`next.config.js` is a regular Node.js module, not a JSON file. It gets used by the Next.js server and build phases, and it's not included in the browser build.
@@ -21,6 +21,19 @@ const nextConfig = {
module.exports = nextConfig
```
+If you need [ECMAScript modules](https://nodejs.org/api/esm.html), you can use `next.config.mjs`:
+
+```js
+/**
+ * @type {import('next').NextConfig}
+ */
+const nextConfig = {
+ /* config options here */
+}
+
+export default nextConfig
+```
+
You can also use a function:
```js
@@ -35,7 +48,21 @@ module.exports = (phase, { defaultConfig }) => {
}
```
-`phase` is the current context in which the configuration is loaded. You can see the [available phases](https://github.com/vercel/next.js/blob/canary/packages/next/shared/lib/constants.ts#L1-L4). Phases can be imported from `next/constants`:
+Since Next.js 12.0.10, you can use an async function:
+
+```js
+module.exports = async (phase, { defaultConfig }) => {
+ /**
+ * @type {import('next').NextConfig}
+ */
+ const nextConfig = {
+ /* config options here */
+ }
+ return nextConfig
+}
+```
+
+`phase` is the current context in which the configuration is loaded. You can see the [available phases](https://github.com/vercel/next.js/blob/canary/packages/next/shared/lib/constants.ts#L1-L5). Phases can be imported from `next/constants`:
```js
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
diff --git a/docs/api-reference/next.config.js/redirects.md b/docs/api-reference/next.config.js/redirects.md
index 9d35b97c3450..30f7ac88c680 100644
--- a/docs/api-reference/next.config.js/redirects.md
+++ b/docs/api-reference/next.config.js/redirects.md
@@ -23,8 +23,6 @@ description: Add redirects to your Next.js app.
Redirects allow you to redirect an incoming request path to a different destination path.
-Redirects are only available on the Node.js environment and do not affect client-side routing.
-
To use Redirects you can use the `redirects` key in `next.config.js`:
```js
@@ -45,7 +43,7 @@ module.exports = {
- `source` is the incoming request path pattern.
- `destination` is the path you want to route to.
-- `permanent` if the redirect is permanent or not.
+- `permanent` `true` or `false` - if `true` will use the 308 status code which instructs clients/search engines to cache the redirect forever, if `false` will use the 307 status code which is temporary and is not cached.
- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
@@ -201,13 +199,14 @@ module.exports = {
// if the host is `example.com`,
// this redirect will be applied
{
- source: '/:path((?!another-page$).*)',,
+ source: '/:path((?!another-page$).*)',
has: [
{
type: 'host',
value: 'example.com',
},
],
+ permanent: false,
destination: '/another-page',
},
]
@@ -291,4 +290,4 @@ In some rare cases, you might need to assign a custom status code for older HTTP
## Other Redirects
- Inside [API Routes](/docs/api-routes/response-helpers.md), you can use `res.redirect()`.
-- Inside [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) and [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering), you can redirect specific pages at request-time.
+- Inside [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time.
diff --git a/docs/api-reference/next.config.js/rewrites.md b/docs/api-reference/next.config.js/rewrites.md
index 46c58eb6035d..16ae2b533df8 100644
--- a/docs/api-reference/next.config.js/rewrites.md
+++ b/docs/api-reference/next.config.js/rewrites.md
@@ -50,7 +50,7 @@ Rewrites are applied to client-side routing, a `` will have
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
-Rewrites are applied after checking the filesystem (pages and `/public` files) and before dynamic routes by default. This behavior can be changed by instead returning an object instead of an array from the `rewrites` function since `v10.1` of Next.js:
+Rewrites are applied after checking the filesystem (pages and `/public` files) and before dynamic routes by default. This behavior can be changed by returning an object instead of an array from the `rewrites` function since `v10.1` of Next.js:
```js
module.exports = {
@@ -148,6 +148,8 @@ module.exports = {
}
```
+Note: for static pages from the [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) or [prerendering](/docs/basic-features/data-fetching/get-static-props.md) params from rewrites will be parsed on the client after hydration and provided in the query.
+
## Path Matching
Path matches are allowed, for example `/blog/:slug` will match `/blog/hello-world` (no nested paths):
diff --git a/docs/api-reference/next.config.js/url-imports.md b/docs/api-reference/next.config.js/url-imports.md
new file mode 100644
index 000000000000..bb50c6ffe6b1
--- /dev/null
+++ b/docs/api-reference/next.config.js/url-imports.md
@@ -0,0 +1,94 @@
+---
+description: Configure Next.js to allow importing modules from external URLs (experimental).
+---
+
+# URL Imports
+
+URL imports are an experimental feature that allows you to import modules directly from external servers (instead of from the local disk).
+
+> **Warning**: This feature is experimental. Only use domains that you trust to download and execute on your machine. Please exercise
+> discretion, and caution until the feature is flagged as stable.
+
+To opt-in, add the allowed URL prefixes inside `next.config.js`:
+
+```js
+module.exports = {
+ experimental: {
+ urlImports: ['https://example.com/modules/'],
+ },
+}
+```
+
+Then, you can import modules directly from URLs:
+
+```js
+import { a, b, c } from 'https://example.com/modules/some/module.js'
+```
+
+URL Imports can be used everywhere normal package imports can be used.
+
+## Security Model
+
+This feature is being designed with **security as the top priority**. To start, we added an experimental flag forcing you to explicitly allow the domains you accept URL imports from. We're working to take this further by limiting URL imports to execute in the browser sandbox using the [Edge Runtime](/docs/api-reference/edge-runtime.md). This runtime is used by [Middleware](/docs/middleware.md) as well as [Next.js Live](https://vercel.com/live).
+
+## Lockfile
+
+When using URL imports, Next.js will create a lockfile in the `next.lock` directory.
+This directory is intended to be committed to Git and should **not be included** in your `.gitignore` file.
+
+- When running `next dev`, Next.js will download and add all newly discovered URL Imports to your lockfile
+- When running `next build`, Next.js will use only the lockfile to build the application for production
+
+Typically, no network requests are needed and any outdated lockfile will cause the build to fail.
+One exception is resources that respond with `Cache-Control: no-cache`.
+These resources will have a `no-cache` entry in the lockfile and will always be fetched from the network on each build.
+
+## Examples
+
+### Skypack
+
+```js
+import confetti from 'https://cdn.skypack.dev/canvas-confetti'
+import { useEffect } from 'react'
+
+export default () => {
+ useEffect(() => {
+ confetti()
+ })
+ return
Hello
+}
+```
+
+### Static Image Imports
+
+```js
+import Image from 'next/image'
+import logo from 'https://github.com/vercel/next.js/raw/canary/test/integration/production/public/vercel.png'
+
+export default () => (
+
+```
diff --git a/docs/api-reference/next/head.md b/docs/api-reference/next/head.md
index 63010ff4e064..96a6d14a5ea3 100644
--- a/docs/api-reference/next/head.md
+++ b/docs/api-reference/next/head.md
@@ -55,7 +55,7 @@ function IndexPage() {
export default IndexPage
```
-In this case only the second `` is rendered. `meta` tags with duplicate `name` attributes are automatically handled.
+In this case only the second `` is rendered. `meta` tags with duplicate `key` attributes are automatically handled.
> The contents of `head` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `head`, without making assumptions about what other pages added.
diff --git a/docs/api-reference/next/image.md b/docs/api-reference/next/image.md
index b093a8d1598b..830771ce3447 100644
--- a/docs/api-reference/next/image.md
+++ b/docs/api-reference/next/image.md
@@ -16,6 +16,8 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------- |
+| `v12.0.9` | `lazyRoot` prop added |
+| `v12.0.0` | `formats` configuration added. AVIF support added. Wrapper `
` changed to ``. |
| `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. |
| `v11.0.0` | `src` prop support for static import. `placeholder` prop added. `blurDataURL` prop added. |
| `v10.0.5` | `loader` prop added. |
@@ -24,37 +26,7 @@ description: Enable Image Optimization with the built-in Image component.
-> Before moving forward, we recommend you to read
-> [Image Optimization](/docs/basic-features/image-optimization.md) first.
-
-Image Optimization can be enabled via the `` component exported by
-`next/image`.
-
-## Usage
-
-For an example, consider a project with the following files:
-
-- `pages/index.js`
-- `public/me.png`
-
-We can serve an optimized image like so:
-
-```jsx
-import Image from 'next/image'
-import profilePic from '../public/me.png'
-
-function Home() {
- return (
- <>
-
My Homepage
-
-
Welcome to my homepage!
- >
- )
-}
-
-export default Home
-```
+> **Note: This is API documentation for the Image Component and Image Optimization. For a feature overview and usage information for images in Next.js, please see [Images](/docs/basic-features/image-optimization.md).**
## Required Props
@@ -62,14 +34,14 @@ The `` component requires the following properties.
### src
-Required and must be one of the following:
+Must be one of the following:
-1. A statically imported image file, as in the example code above, or
+1. A [statically imported](/docs/basic-features/image-optimization.md#local-images) image file, or
2. A path string. This can be either an absolute external URL,
- or an internal path depending on the [loader](#loader).
+ or an internal path depending on the [loader](#loader) prop or [loader configuration](#loader-configuration).
When using an external URL, you must add it to
-[domains](/docs/basic-features/image-optimization.md#domains) in
+[domains](#domains) in
`next.config.js`.
### width
@@ -86,18 +58,18 @@ Required, except for statically imported images, or those with [`layout="fill"`]
## Optional Props
-The `` component optionally accepts the following properties.
+The `` component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the [Advanced Props](#advanced-props) section.
### layout
The layout behavior of the image as the viewport changes size.
-| `layout` | Behavior | `srcSet` | `sizes` |
-| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
-| `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes)) | N/A |
-| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes)) | N/A |
-| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes) and [deviceSizes](/docs/basic-features/image-optimization.md#device-sizes)) | `100vw` |
-| `fill` | Grow in X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes) and [deviceSizes](/docs/basic-features/image-optimization.md#device-sizes)) | `100vw` |
+| `layout` | Behavior | `srcSet` | `sizes` |
+| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------- |
+| `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A |
+| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A |
+| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` |
+| `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` |
- [Demo the `intrinsic` layout (default)](https://image-component.nextjs.gallery/layout-intrinsic)
- When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
@@ -114,14 +86,16 @@ The layout behavior of the image as the viewport changes size.
### loader
-A custom function used to resolve URLs. Defaults to [`images` object in `next.config.js`](/docs/basic-features/image-optimization.md#loader).
+A custom function used to resolve URLs. Setting the loader as a prop on the Image component overrides the default loader defined in the [`images` section of `next.config.js`](#loader-configuration).
-`loader` is a function returning a string, given the following parameters:
+A `loader` is a function returning a URL string for the image, given the following parameters:
- [`src`](#src)
- [`width`](#width)
- [`quality`](#quality)
+Here is an example of using a custom loader with `next/image`:
+
```js
import Image from 'next/image'
@@ -144,30 +118,34 @@ const MyImage = (props) => {
### sizes
-A string mapping media queries to device sizes. Defaults to `100vw`.
+A string that provides information about how wide the image will be at different breakpoints. Defaults to `100vw` (the full width of the screen) when using `layout="responsive"` or `layout="fill"`.
-We recommend setting `sizes` when using `layout="responsive"` or `layout="fill"` and your image will **not** be the same width as the viewport.
+If you are using `layout="fill"` or `layout="responsive"`, it's important to assign `sizes` for any image that takes up less than the full viewport width.
+
+For example, when the parent element will constrain the image to always be less than half the viewport width, use `sizes="50vw"`. Without `sizes`, the image will be sent at twice the necessary resolution, decreasing performance.
+
+If you are using `layout="intrinsic"` or `layout="fixed"`, then `sizes` is not needed because the upper bound width is constrained already.
[Learn more](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes).
### quality
-The quality of the optimized image, an integer between `1` and `100` where `100`
-is the best quality. Defaults to `75`.
+The quality of the optimized image, an integer between `1` and `100` where `100` is the best quality. Defaults to `75`.
### priority
When true, the image will be considered high priority and
-[preload](https://web.dev/preload-responsive-images/).
+[preload](https://web.dev/preload-responsive-images/). Lazy loading is automatically disabled for images using `priority`.
+
+You should use the `priority` property on any image detected as the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
-Should only be used when the image is visible above the fold. Defaults to
-`false`.
+Should only be used when the image is visible above the fold. Defaults to `false`.
### placeholder
-A placeholder to use while the image is loading, possible values are `blur` or `empty`. Defaults to `empty`.
+A placeholder to use while the image is loading. Possible values are `blur` or `empty`. Defaults to `empty`.
-When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a static import and the imported image is jpg, png, or webp, then `blurDataURL` will automatically be populated.
+When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a [static import](/docs/basic-features/image-optimization.md#local-images) and the imported image is `.jpg`, `.png`, `.webp`, or `.avif`, then `blurDataURL` will be automatically populated.
For dynamic images, you must provide the [`blurDataURL`](#blurdataurl) property. Solutions such as [Plaiceholder](https://github.com/joe-bell/plaiceholder) can help with `base64` generation.
@@ -177,23 +155,23 @@ Try it out:
- [Demo the `blur` placeholder](https://image-component.nextjs.gallery/placeholder)
- [Demo the shimmer effect with `blurDataURL` prop](https://image-component.nextjs.gallery/shimmer)
+- [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)
## Advanced Props
-In some cases, you may need more advanced usage. The `` component
-optionally accepts the following advanced properties.
+In some cases, you may need more advanced usage. The `` component optionally accepts the following advanced properties.
### objectFit
-The image fit when using `layout="fill"`.
+Defines how the image will fit into its parent container when using `layout="fill"`.
-[Learn more](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
+This value is passed to the [object-fit CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) for the `src` image.
### objectPosition
-The image position when using `layout="fill"`.
+Defines how the image is positioned within its parent element when using `layout="fill"`.
-[Learn more](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position)
+This value is passed to the [object-position CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) applied to the image.
### onLoadingComplete
@@ -234,6 +212,7 @@ Try it out:
- [Demo the default `blurDataURL` prop](https://image-component.nextjs.gallery/placeholder)
- [Demo the shimmer effect with `blurDataURL` prop](https://image-component.nextjs.gallery/shimmer)
+- [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color)
You can also [generate a solid color Data URL](https://png-pixel.com) to match the image.
@@ -243,6 +222,12 @@ A string (with similar syntax to the margin property) that acts as the bounding
[Learn more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin)
+### lazyRoot
+
+A React [Ref](https://reactjs.org/docs/refs-and-the-dom.html) pointing to the Element which the [lazyBoundary](#lazyBoundary) calculates for the Intersection detection. Defaults to `null`, referring to the document viewport.
+
+[Learn more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/root)
+
### unoptimized
When true, the source image will be served as-is instead of changing quality,
@@ -255,26 +240,166 @@ Other properties on the `` component will be passed to the underlying
- `style`. Use `className` instead.
- `srcSet`. Use
- [Device Sizes](/docs/basic-features/image-optimization.md#device-sizes)
+ [Device Sizes](#device-sizes)
instead.
- `ref`. Use [`onLoadingComplete`](#onloadingcomplete) instead.
- `decoding`. It is always `"async"`.
-## Styling
+## Configuration Options
+
+### Domains
+
+To protect your application from malicious users, you must define a list of image provider domains that you want to be served from the Next.js Image Optimization API. This is configured in with the `domains` property in your `next.config.js` file, as shown below:
+
+```js
+module.exports = {
+ images: {
+ domains: ['assets.acme.com'],
+ },
+}
+```
+
+### Loader Configuration
+
+If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the `loader` and `path` prefix in your `next.config.js` file. This allows you to use relative URLs for the Image [`src`](#src) and automatically generate the correct absolute URL for your provider.
+
+```js
+module.exports = {
+ images: {
+ loader: 'imgix',
+ path: 'https://example.com/myaccount/',
+ },
+}
+```
+
+### Built-in Loaders
+
+The following Image Optimization cloud providers are included:
+
+- Default: Works automatically with `next dev`, `next start`, or a custom server
+- [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/next.js/image-optimization)
+- [Imgix](https://www.imgix.com): `loader: 'imgix'`
+- [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
+- [Akamai](https://www.akamai.com): `loader: 'akamai'`
+- Custom: `loader: 'custom'` use a custom cloud provider by implementing the [`loader`](/docs/api-reference/next/image.md#loader) prop on the `next/image` component
+
+If you need a different provider, you can use the [`loader`](#loader) prop with `next/image`.
+
+> Images can not be optimized at build time using [`next export`](/docs/advanced-features/static-html-export.md), only on-demand. To use `next/image` with `next export`, you will need to use a different loader than the default. [Read more in the discussion.](https://github.com/vercel/next.js/discussions/19065)
+
+> The `next/image` component's default loader uses [`squoosh`](https://www.npmjs.com/package/@squoosh/lib) because it is quick to install and suitable for a development environment. When using `next start` in your production environment, it is strongly recommended that you install [`sharp`](https://www.npmjs.com/package/sharp) by running `yarn add sharp` in your project directory. This is not necessary for Vercel deployments, as `sharp` is installed automatically.
+
+## Advanced
+
+The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
+
+### Device Sizes
+
+If you know the expected device widths of your users, you can specify a list of device width breakpoints using the `deviceSizes` property in `next.config.js`. These widths are used when the [`next/image`](/docs/api-reference/next/image.md) component uses `layout="responsive"` or `layout="fill"` to ensure the correct image is served for user's device.
+
+If no configuration is provided, the default below is used.
-`next/image` wraps the `img` element with other `div` elements to maintain the aspect ratio of the image and prevent [Cumulative Layout Shift](https://vercel.com/blog/core-web-vitals#cumulative-layout-shift).
+```js
+module.exports = {
+ images: {
+ deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
+ },
+}
+```
+
+### Image Sizes
+
+You can specify a list of image widths using the `images.imageSizes` property in your `next.config.js` file. These widths are concatenated with the array of [device sizes](#device-sizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset)s.
+
+The reason there are two separate lists is that imageSizes is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. **Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.**
+
+If no configuration is provided, the default below is used.
+
+```js
+module.exports = {
+ images: {
+ imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
+ },
+}
+```
-To add styles to the underlying `img` element, pass the `className` prop to the `` component. Then, use Next.js' [built-in CSS support](/docs/basic-features/built-in-css-support.md) to add rules to that class.
+### Acceptable Formats
-**Note:** If using [`layout="fill"`](/docs/api-reference/next/image.md#layout), ensure the parent element uses `position: relative`.
+The default [Image Optimization API](#loader-configuration) will automatically detect the browser's supported image formats via the request's `Accept` header.
+
+If the `Accept` head matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match, the Image Optimization API will fallback to the original image's format.
+
+If no configuration is provided, the default below is used.
+
+```js
+module.exports = {
+ images: {
+ formats: ['image/webp'],
+ },
+}
+```
+
+You can enable AVIF support with the following configuration.
+
+```js
+module.exports = {
+ images: {
+ formats: ['image/avif', 'image/webp'],
+ },
+}
+```
+
+> Note: AVIF generally takes 20% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower and then subsequent requests that are cached will be faster.
+
+## Caching Behavior
+
+The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation.
+
+Images are optimized dynamically upon request and stored in the `/cache/images` directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the cached file is deleted before generating a new optimized image and caching the new file.
+
+The expiration (or rather Max Age) is defined by either the [`minimumCacheTTL`](#minimum-cache-ttl) configuration or the upstream server's `Cache-Control` header, whichever is larger. Specifically, the `max-age` value of the `Cache-Control` header is used. If both `s-maxage` and `max-age` are found, then `s-maxage` is preferred.
+
+- You can configure [`minimumCacheTTL`](#minimum-cache-ttl) to increase the cache duration when the upstream image does not include `Cache-Control` header or the value is very low.
+- You can configure [`deviceSizes`](#device-sizes) and [`imageSizes`](#device-sizes) to reduce the total number of possible generated images.
+- You can configure [formats](/docs/basic-features/image-optimization.md#acceptable-formats) to disable multiple formats in favor of a single image format.
+
+### Minimum Cache TTL
+
+You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a [Static Image Import](/docs/basic-features/image-optimization.md#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`.
+
+```js
+module.exports = {
+ images: {
+ minimumCacheTTL: 60,
+ },
+}
+```
+
+If you need to add a `Cache-Control` header for the browser (not recommended), you can configure [`headers`](/docs/api-reference/next.config.js/headers) on the upstream image e.g. `/some-asset.jpg` not `/_next/image` itself.
+
+### Disable Static Imports
+
+The default behavior allows you to import static files such as `import icon from './icon.png` and then pass that to the `src` property.
+
+In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
+
+You can disable static image imports inside your `next.config.js`:
+
+```js
+module.exports = {
+ images: {
+ disableStaticImages: true,
+ },
+}
+```
## Related
-For more information on what to do next, we recommend the following sections:
+For an overview of the Image component features and usage guidelines, see:
diff --git a/docs/api-reference/next/link.md b/docs/api-reference/next/link.md
index a5272331968a..0525518af91f 100644
--- a/docs/api-reference/next/link.md
+++ b/docs/api-reference/next/link.md
@@ -55,12 +55,12 @@ export default Home
`Link` accepts the following props:
- `href` - The path or URL to navigate to. This is the only required prop
-- `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked
+- `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes).
- [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false`
-- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production.
+- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/get-static-props.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production.
- [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false`
- [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true`
-- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false`
+- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false`
- `locale` - The active locale is automatically prepended. `locale` allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled.
## If the route has dynamic segments
@@ -91,7 +91,7 @@ export default Posts
## If the child is a custom component that wraps an `` tag
-If the child of `Link` is a custom component that wraps an `` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `` tag will not have the `href` attribute, which might hurt your site’s SEO.
+If the child of `Link` is a custom component that wraps an `` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/basic-features/eslint.md#eslint-plugin), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.
```jsx
import Link from 'next/link'
@@ -117,9 +117,9 @@ export default NavLink
- If you’re using [emotion](https://emotion.sh/)’s JSX pragma feature (`@jsx jsx`), you must use `passHref` even if you use an `` tag directly.
- The component should support `onClick` property to trigger navigation correctly
-## If the child is a function component
+## If the child is a functional component
-If the child of `Link` is a function component, in addition to using `passHref`, you must wrap the component in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref):
+If the child of `Link` is a functional component, in addition to using `passHref`, you must wrap the component in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref):
```jsx
import Link from 'next/link'
@@ -204,7 +204,7 @@ The default behavior of the `Link` component is to `push` a new URL into the `hi
The default behavior of `Link` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal `` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `Link`:
```jsx
-
+
Disables scrolling to the top
```
diff --git a/docs/api-reference/next/router.md b/docs/api-reference/next/router.md
index 60aa34f7f709..9c0e78dfd784 100644
--- a/docs/api-reference/next/router.md
+++ b/docs/api-reference/next/router.md
@@ -42,18 +42,18 @@ export default ActiveLink
The following is the definition of the `router` object returned by both [`useRouter`](#useRouter) and [`withRouter`](#withRouter):
- `pathname`: `String` - Current route. That is the path of the page in `/pages`, the configured `basePath` or `locale` is not included.
-- `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching.md). Defaults to `{}`
+- `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching/overview.md). Defaults to `{}`
- `asPath`: `String` - The path (including the query) shown in the browser without the configured `basePath` or `locale`.
-- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/basic-features/data-fetching.md#fallback-pages).
+- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/api-reference/data-fetching/get-static-paths.md#fallback-pages).
- `basePath`: `String` - The active [basePath](/docs/api-reference/next.config.js/basepath.md) (if enabled).
- `locale`: `String` - The active locale (if enabled).
- `locales`: `String[]` - All supported locales (if enabled).
- `defaultLocale`: `String` - The current default locale (if enabled).
- `domainLocales`: `Array<{domain, defaultLocale, locales}>` - Any configured domain locales.
-- `isReady`: `boolean` - Whether the router fields are updated client-side and ready for use. Should only be used inside of `useEffect` methods and not for conditionally rendering on the server.
+- `isReady`: `boolean` - Whether the router fields are updated client-side and ready for use. Should only be used inside of `useEffect` methods and not for conditionally rendering on the server. See related docs for use case with [automatically statically optimized pages](/docs/advanced-features/automatic-static-optimization.md)
- `isPreview`: `boolean` - Whether the application is currently in [preview mode](/docs/advanced-features/preview-mode.md).
-Additionally, the following methods are also included inside `router`:
+The following methods are included inside `router`:
### router.push
@@ -70,11 +70,11 @@ Handles client-side transitions, this method is useful for cases where [`next/li
router.push(url, as, options)
```
-- `url` - The URL to navigate to
-- `as` - Optional decorator for the URL that will be shown in the browser. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked
+- `url`: `UrlObject | String` - The URL to navigate to (see [Node.JS URL module documentation](https://nodejs.org/api/url.html#legacy-urlobject) for `UrlObject` properties).
+- `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes)
- `options` - Optional object with the following configuration options:
- `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true`
- - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false`
+ - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false`
- `locale` - Optional string, indicates locale of the new page
> You don't need to use `router.push` for external URLs. [window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) is better suited for those cases.
@@ -202,7 +202,7 @@ Prefetch pages for faster client-side transitions. This method is only useful fo
router.prefetch(url, as)
```
-- `url` - The URL to prefetch, that is, a path with a matching page
+- `url` - The URL to prefetch, including explicit routes (e.g. `/dashboard`) and dynamic routes (e.g. `/product/[id]`)
- `as` - Optional decorator for `url`. Before Next.js 9.5.3 this was used to prefetch dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked
#### Usage
@@ -414,6 +414,53 @@ export default function MyApp({ Component, pageProps }) {
}
```
+## Potential ESLint errors
+
+Certain methods accessible on the `router` object return a Promise. If you have the ESLint rule, [no-floating-promises](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-floating-promises.md) enabled, consider disabling it either globally, or for the affected line.
+
+If your application needs this rule, you should either `void` the promise – or use an `async` function, `await` the Promise, then void the function call. **This is not applicable when the method is called from inside an `onClick` handler**.
+
+The affected methods are:
+
+- `router.push`
+- `router.replace`
+- `router.prefetch`
+
+### Potential solutions
+
+```jsx
+import { useEffect } from 'react'
+import { useRouter } from 'next/router'
+
+// Here you would fetch and return the user
+const useUser = () => ({ user: null, loading: false })
+
+export default function Page() {
+ const { user, loading } = useUser()
+ const router = useRouter()
+
+ useEffect(() => {
+ // disable the linting on the next line - This is the cleanest solution
+ // eslint-disable-next-line no-floating-promises
+ router.push('/login')
+
+ // void the Promise returned by router.push
+ if (!(user || loading)) {
+ void router.push('/login')
+ }
+ // or use an async function, await the Promise, then void the function call
+ async function handleRouteChange() {
+ if (!(user || loading)) {
+ await router.push('/login')
+ }
+ }
+ void handleRouteChange()
+ }, [user, loading])
+
+ return
Redirecting...
+}
+```
+
## withRouter
If [`useRouter`](#useRouter) is not the best fit for you, `withRouter` can also add the same [`router` object](#router-object) to any component.
diff --git a/docs/api-reference/next/script.md b/docs/api-reference/next/script.md
new file mode 100644
index 000000000000..79c83341f887
--- /dev/null
+++ b/docs/api-reference/next/script.md
@@ -0,0 +1,72 @@
+---
+description: Optimize loading of third-party scripts with the built-in Script component.
+---
+
+# next/script
+
+
+ Examples
+
+
+
+
+ Version History
+
+| Version | Changes |
+| --------- | ------------------------- |
+| `v11.0.0` | `next/script` introduced. |
+
+
+
+> **Note: This is API documentation for the Script Component. For a feature overview and usage information for scripts in Next.js, please see [Script Optimization](/docs/basic-features/script.md).**
+
+## Optional Props
+
+### src
+
+A path string specifying the URL of an external script. This can be either an absolute external URL or an internal path.
+
+### strategy
+
+The loading strategy of the script.
+
+| `strategy` | **Description** |
+| ------------------- | ---------------------------------------------------------- |
+| `beforeInteractive` | Load script before the page becomes interactive |
+| `afterInteractive` | Load script immediately after the page becomes interactive |
+| `lazyOnload` | Load script during browser idle time |
+
+### onLoad
+
+A method that returns additional JavaScript that should be executed after the script has finished loading.
+
+> **Note: `onLoad` can't be used with the `beforeInteractive` loading strategy.**
+
+The following is an example of how to use the `onLoad` property:
+
+```jsx
+import { useState } from 'react'
+import Script from 'next/script'
+
+export default function Home() {
+ const [stripe, setStripe] = useState(null)
+
+ return (
+ <>
+
+```
+
+Or by using the `dangerouslySetInnerHTML` property:
+
+```jsx
+
+```
+
+There are two limitations to be aware of when using the Script component for inline scripts:
+
+- Only the `afterInteractive` and `lazyOnload` strategies can be used. The `beforeInteractive` loading strategy injects the contents of an external script into the initial HTML response. Inline scripts already do this, which is why **the `beforeInteractive` strategy cannot be used with inline scripts.**
+- An `id` attribute must be defined in order for Next.js to track and optimize the script
+
+### Executing Code After Loading (`onLoad`)
+
+Some third-party scripts require users to run JavaScript code after the script has finished loading in order to instantiate content or call a function. If you are loading a script with either `beforeInteractive` or `afterInteractive` as a loading strategy, you can execute code after it has loaded using the `onLoad` property:
+
+```jsx
+import { useState } from 'react'
import Script from 'next/script'
export default function Home() {
+ const [stripe, setStripe] = useState(null)
+
return (
<>
-
-// or
-
-
-```
+### Additional Attributes
-### Forwarding Attributes
+There are many DOM attributes that can be assigned to a `
+```
+
+The HTML [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) tag is used to embed any client-side JavaScript. It can either contain inline scripting statements (as shown in the example above) or point to an external script file via the `src` attribute.
+This example validates the name and roll number of a user. The `validateFormWithJS()` function does not allow an empty name field, and the roll number must be at least three digits long. The validation is performed when you hit the Submit button. You are not redirected to the next page until the given values are correct.
+
+![js-validation](https://assets.vercel.com/image/upload/dpr_auto,q_auto,f_auto/nextjs/guides/building-forms/js-validation.jpg)
+
+#### Form Validation Using Regular Expressions
+
+JavaScript validation with Regular Expressions uses the `pattern` HTML attribute. A regular expression (commonly known as RegEx) is an object that describes a pattern of characters. You can only apply the `pattern` attribute to the `` element. This way, you can validate the input value using Regular Expressions (RegEx) by defining your own rules. Once again, if the value does not match the defined pattern, the input will give an error.
+The below example shows using the `pattern` attribute on an `input` element:
+
+```html
+
+```
+
+The password form field must only contain digits (0 to 9) and lowercase alphabets (a to z). No other characters (#,$,&, etc.) are allowed. The rule in RegEx is written as `[a-z]{1,15}`.
+
+![form-validate-regex](https://assets.vercel.com/image/upload/dpr_auto,q_auto,f_auto/nextjs/guides/building-forms/form-validate-regex.jpg)
+
+> To learn more about HTML forms, check out the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Learn/Forms).
+
+## Part 2: Project Setup
+
+In the following section you will be creating forms in React using Next.js.
+
+Create a new Next.js app. You can use the [create-next-app](https://nextjs.org/docs/getting-started#setup) for a quick start. In your command line terminal, run the following:
+
+```
+npx create-next-app
+```
+
+Answer the questions to create your project, and give it a name, this example uses [`next-forms`](https://github.com/vercel/next.js/tree/canary/examples/next-forms). Next `cd` into this directory, and run `npm run dev` or `yarn dev` command to start the development server.
+
+Open the URL printed in the terminal to ensure that your app is running successfully.
+
+## Part 3: Setting up a Next.js Form API Route
+
+Both the client and the server will be built using Next.js. For the server part, create an API endpoint where you will send the form data.
+
+Next.js offers a file-based system for routing that's built on the [concept of pages](/docs/basic-features/pages). Any file inside the folder `pages/api` is mapped to `/api/*` and will be treated as an API endpoint instead of a page. This [API endpoint](/docs/api-routes/introduction) is going to be server-side only.
+
+Go to `pages/api`, create a file called `form.js` and paste this code written in Node.js:
+
+```js
+export default function handler(req, res) {
+ // Get data submitted in request's body.
+ const body = req.body
+
+ // Optional logging to see the responses
+ // in the command line where next.js app is running.
+ console.log('body: ', body)
+
+ // Both of these are required.
+ if (!body.first || !body.last) {
+ return res.json({ data: 'First or last name not found' })
+ }
+
+ // Found the name.
+ res.json({ data: `${body.first} ${body.last}` })
+}
+```
+
+This form `handler` function will receive the request `req` from the client (i.e. submitted form data). And in return, it'll send a response `res` as JSON that will have both the first and the last name. You can access this API endpoint at `http://localhost:3000/api/form` or replace the localhost URL with an actual Vercel deployment when you deploy.
+
+> Moreover, you can also attach this API to a database like MongoDB or Google Sheets. This way, your submitted form data will be securely stored for later use. For this guide, no database is used. Instead, the same data is returned to the user to demo how it's done.
+
+### Form Submission without JavaScript
+
+You can now use `/api/form` relative endpoint inside the `action` attribute of the form. You are sending form data to the server when the form is submitted via `POST` HTTP method (which is used to send data).
+
+```html
+
+```
+
+If you submit this form, it will submit the data to the forms API endpoint `/api/form`. The server then responds, generally handling the data and loading the URL defined by the action attribute, causing a new page load. So in this case you'll be redirected to `http://localhost:3000/api/form` with the following response from the server.
+
+![form-no-js](https://assets.vercel.com/image/upload/dpr_auto,q_auto,f_auto/nextjs/guides/building-forms/form-no-js.jpg)
+
+## Part 4: Configuring Forms in Next.js
+
+You have created a Next.js API Route for form submission. Now it's time to configure the client (the form itself) inside Next.js using React. The first step will be extending your knowledge of HTML forms and converting it into React (using [JSX](https://reactjs.org/docs/introducing-jsx.html)).
+
+Here's the same form in a [React function component](https://reactjs.org/docs/components-and-props.html) written using [JSX](https://reactjs.org/docs/introducing-jsx.html).
+
+```js
+export default function Form() {
+ return (
+
+ )
+}
+```
+
+Here's what changed:
+
+- The `for` attribute is changed to `htmlFor`. (Since `for` is a keyword associated with the "for" loop in JavaScript, React elements use `htmlFor` instead.)
+- The `action` attribute now has a relative URL which is the form API endpoint.
+
+This completes the basic structure of your Next.js-based form.
+
+> You can view the entire source code of [next-forms](https://github.com/vercel/next.js/tree/canary/examples/next-forms) example repo that we're creating here as a working example. Feel free to clone it and start right away. This demo is built with create-next-app, and you can preview the basic form CSS styles inside `/styles/global.css` file.
+
+![forms with nextjs](https://assets.vercel.com/image/upload/dpr_auto,q_auto,f_auto/nextjs/guides/building-forms/forms-with-nextjs.png)
+
+## Part 5: Form Submission without JavaScript
+
+JavaScript brings interactivity to our web applications, but sometimes you need to control the JavaScript bundle from being too large, or your sites visitors might have JavaScript disabled.
+
+There are several reasons why users disable JavaScript:
+
+- Addressing bandwidth constraints
+- Increasing device (phone or laptop) battery life
+- For privacy so they won’t be tracked with analytical scripts
+
+Regardless of the reason, disabling JavaScript will impact site functionality partially, if not completely.
+
+Next open the `next-forms` directory. Inside the `/pages` directory, create a file `no-js-form.js`.
+
+> **Quick Tip**: In Next.js, a page is a React Component exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the pages directory. Each page is associated with a route based on its file name.
+>
+> Example: If you create `pages/no-js-form.js`, it will be accessible at `your-domain.tld/no-js-form`.
+
+Let's use the same code from above:
+
+```js
+export default function PageWithoutJSbasedForm() {
+ return (
+
+ )
+}
+```
+
+With JavaScript disabled, when you hit the Submit button, an event is triggered, which collects the form data and sends it to our forms API endpoint as defined in the `action` attribute and using `POST` HTTP `method`. You'll be redirected to the `/api/form` endpoint since that's how form `action` works.
+
+The form data will be submitted on the server as a request `req` to the form handler function written above. It will process the data and return a JSON string as a response `res` with your submitted name included.
+
+> To improve the experience here, as a response you can redirect the user to a page and thank them for submitting the form.
+
+## Part 6: Form Submission with JavaScript Enabled
+
+Inside `/pages`, you'll create another file called `js-form.js`. This will create a `/js-form` page on your Next.js app.
+
+Now, as soon as the form is submitted, we prevent the form's default behavior of reloading the page. We'll take the form data, convert it to JSON string, and send it to our server, the API endpoint. Finally, our server will respond with the name submitted. All of this with a basic JavaScript `handleSubmit()` function.
+
+Here's what this function looks like. It's well documented for you to understand each step:
+
+```js
+export default function PageWithJSbasedForm() {
+ // Handles the submit event on form submit.
+ const handleSubmit = async (event) => {
+ // Stop the form from submitting and refreshing the page.
+ event.preventDefault()
+
+ // Get data from the form.
+ const data = {
+ first: event.target.first.value,
+ last: event.target.last.value,
+ }
+
+ // Send the data to the server in JSON format.
+ const JSONdata = JSON.stringify(data)
+
+ // API endpoint where we send form data.
+ const endpoint = '/api/form'
+
+ // Form the request for sending data to the server.
+ const options = {
+ // The method is POST because we are sending data.
+ method: 'POST',
+ // Tell the server we're sending JSON.
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ // Body of the request is the JSON data we created above.
+ body: JSONdata,
+ }
+
+ // Send the form data to our forms API on Vercel and get a response.
+ const response = await fetch(endpoint, options)
+
+ // Get the response data from server as JSON.
+ // If server returns the name submitted, that means the form works.
+ const result = await response.json()
+ alert(`Is this your full name: ${result.data}`)
+ }
+ return (
+ // We pass the event to the handleSubmit() function on submit.
+
+ )
+}
+```
+
+It's a Next.js page with a React function component called `PageWithJSbasedForm` with a `