@@ -17,9 +16,9 @@ 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.
-> A custom server **can not** be deployed on [Vercel](https://vercel.com/solutions/nextjs), the platform Next.js was made for.
+> **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).**
+> 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).**
Take a look at the following example of a custom server:
@@ -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 3c3b30e735504..2cbcafec88345 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": "Launch Program",
- "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 pop up.
+## 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/dynamic-import.md b/docs/advanced-features/dynamic-import.md
index 2f9c8b37e7cce..fd92848067e99 100644
--- a/docs/advanced-features/dynamic-import.md
+++ b/docs/advanced-features/dynamic-import.md
@@ -45,7 +45,7 @@ export default function Page() {
You can think of dynamic imports as another way to split your code into manageable chunks.
-React components can also be imported using dynamic imports, but in this case we use it in conjunction with `next/dynamic` to make sure it works just like any other React Component. Check out the sections below for more details on how it works.
+React components can also be imported using dynamic imports, but in this case we use it in conjunction with `next/dynamic` to make sure it works like any other React Component. Check out the sections below for more details on how it works.
## Basic usage
@@ -156,3 +156,25 @@ function Home() {
export default Home
```
+
+## With suspense
+
+Option `suspense` allows you to lazy-load a component, similar to `React.lazy` and `` with React 18. Note that it only works on client-side or server-side with `fallback`. Full SSR support in concurrent mode is still a work-in-progress.
+
+```jsx
+import dynamic from 'next/dynamic'
+
+const DynamicLazyComponent = dynamic(() => import('../components/hello4'), {
+ suspense: true,
+})
+
+function Home() {
+ return (
+
+
+
+
+
+ )
+}
+```
diff --git a/docs/advanced-features/i18n-routing.md b/docs/advanced-features/i18n-routing.md
index e76fe99b15887..0a55f52ffd69a 100644
--- a/docs/advanced-features/i18n-routing.md
+++ b/docs/advanced-features/i18n-routing.md
@@ -52,6 +52,9 @@ module.exports = {
{
domain: 'example.fr',
defaultLocale: 'fr',
+ // an optional http field can also be used to test
+ // locale domains locally with http instead of https
+ http: true,
},
],
},
@@ -97,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',
},
@@ -119,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`
@@ -136,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:
@@ -159,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`.
@@ -201,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
@@ -231,6 +300,30 @@ Next.js doesn't know about variants of a page so it's up to you to add the `href
> Note that Internationalized Routing does not integrate with [`next export`](/docs/advanced-features/static-html-export.md) as `next export` does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use `next export` are fully supported.
+### 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/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
+export const getStaticPaths = ({ locales }) => {
+ return {
+ paths: [
+ // if no `locale` is provided only the defaultLocale will be generated
+ { params: { slug: 'post-1' }, locale: 'en-US' },
+ { params: { slug: 'post-1' }, locale: 'fr' },
+ ],
+ fallback: true,
+ }
+}
+```
+
+For [Automatically Statically Optimized](/docs/advanced-features/automatic-static-optimization.md) and non-dynamic `getStaticProps` pages, **a version of the page will be generated for each locale**. This is important to consider because it can increase build times depending on how many locales are configured inside `getStaticProps`.
+
+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](/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
For pages that are [automatically statically optimized](/docs/advanced-features/automatic-static-optimization.md), a version of the page will be generated for each locale.
@@ -262,19 +355,9 @@ export async function getStaticProps({ locale }) {
}
```
-### Dynamic getStaticProps Pages
+## Limits for the i18n config
-For dynamic `getStaticProps` pages, any locale variants of the page that is desired to be prerendered needs to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation). Along with the `params` object that can be returned for the `paths`, you can also return a `locale` field specifying which locale you want to render. For example:
+- `locales`: 100 total locales
+- `domains`: 100 total locale domain items
-```js
-// pages/blog/[slug].js
-export const getStaticPaths = ({ locales }) => {
- return {
- paths: [
- { params: { slug: 'post-1' }, locale: 'en-US' },
- { params: { slug: 'post-1' }, locale: 'fr' },
- ],
- fallback: true,
- }
-}
-```
+> **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 329cddd452cf7..a9c20215e0b7e 100644
--- a/docs/advanced-features/measuring-performance.md
+++ b/docs/advanced-features/measuring-performance.md
@@ -159,12 +159,12 @@ export function reportWebVitals(metric) {
> **Note**: If you use [Google Analytics](https://analytics.google.com/analytics/web/), using the
> `id` value can allow you to construct metric distributions manually (to calculate percentiles,
-> etc...).
+> etc.)
>
> ```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',
@@ -175,7 +175,7 @@ export function reportWebVitals(metric) {
> }
> ```
>
-> Read more about sending results to Google Analytics [here](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics).
+> Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics).
## TypeScript
diff --git a/docs/advanced-features/multi-zones.md b/docs/advanced-features/multi-zones.md
index 1fce98d049e58..7d288941b0cb9 100644
--- a/docs/advanced-features/multi-zones.md
+++ b/docs/advanced-features/multi-zones.md
@@ -18,7 +18,7 @@ With multi zones support, you can merge both these apps into a single one allowi
## How to define a zone
-There are no special zones related APIs. You only need to do following:
+There are no zone related APIs. You only need to do the following:
- Make sure to keep only the pages you need in your app, meaning that an app can't have pages from another app, if app `A` has `/blog` then app `B` shouldn't have it too.
- Make sure to configure a [basePath](/docs/api-reference/next.config.js/basepath.md) to avoid conflicts with pages and static files.
diff --git a/docs/advanced-features/output-file-tracing.md b/docs/advanced-features/output-file-tracing.md
new file mode 100644
index 0000000000000..dce5f2cc62860
--- /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 [minimatch globs](https://www.npmjs.com/package/minimatch) 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 98d1ae6698cb8..7850663d5506b 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.
@@ -170,22 +171,23 @@ https:///api/preview?secret=&slug=
## More Details
-### Clear the preview mode cookies
+### Clear the Preview Mode cookies
-By default, no expiration date is set for the preview mode cookies, so the preview mode ends when the browser is closed.
+By default, no expiration date is set for Preview Mode cookies, so the preview session ends when the browser is closed.
-To clear the preview cookies manually, you can create an API route which calls `clearPreviewData` and then access this API route.
+To clear the Preview Mode cookies manually, create an API route that calls `clearPreviewData()`:
```js
+// pages/api/clear-preview-mode-cookies.js
+
export default function handler(req, res) {
- // Clears the preview mode cookies.
- // This function accepts no arguments.
res.clearPreviewData()
- // ...
}
```
-### Specify the preview mode duration
+Then, send a request to `/api/clear-preview-mode-cookies` to invoke the API Route. If calling this route using [`next/link`](/docs/api-reference/next/link.md), you must pass `prefetch={false}` to prevent calling `clearPreviewData` during link prefetching.
+
+### Specify the Preview Mode duration
`setPreviewData` takes an optional second parameter which should be an options object. It accepts the following keys:
@@ -229,7 +231,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/overview.md b/docs/advanced-features/react-18/overview.md
new file mode 100644
index 0000000000000..2df4aa92b3b0b
--- /dev/null
+++ b/docs/advanced-features/react-18/overview.md
@@ -0,0 +1,28 @@
+# 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`.
+Next.js also provides streaming related APIs, please checkout [next/streaming](/docs/api-reference/next/streaming.md) for details.
+
+React 18 is now in Release Candidate (RC). Read more about React 18's [release plan](https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html) and discussions from the [working group](https://github.com/reactwg/react-18/discussions).
+
+## Using React 18 with Next.js
+
+Install the RC version of React 18:
+
+```jsx
+npm install next@latest react@rc react-dom@rc
+```
+
+You can now start using React 18's new APIs like `startTransition` and `Suspense` in Next.js.
+
+## Streaming SSR (Alpha)
+
+Streaming server-rendering (SSR) is an experimental feature in Next.js 12. When enabled, SSR will use the same [Edge Runtime](/docs/api-reference/edge-runtime.md) as [Middleware](/docs/middleware.md).
+
+[Learn how to enable streaming in Next.js.](/docs/react-18/streaming.md)
+
+## React Server Components (Alpha)
+
+Server Components are a new feature in React that let you reduce your JavaScript bundle size by separating server and client-side code. Server Components allow developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.
+
+Server Components are still in research and development. [Learn how to try Server Components](/docs/react-18/server-components.md) as an experimental feature in Next.js.
diff --git a/docs/advanced-features/react-18/server-components.md b/docs/advanced-features/react-18/server-components.md
new file mode 100644
index 0000000000000..dea51f2014fd2
--- /dev/null
+++ b/docs/advanced-features/react-18/server-components.md
@@ -0,0 +1,132 @@
+# React Server Components (Alpha)
+
+Server Components allow us to render React components on the server. This is fundamentally different from server-side rendering (SSR) 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
+
+To use React Server Components, ensure you have React 18 installed:
+
+```jsx
+npm install next@latest react@rc react-dom@rc
+```
+
+Then, update your `next.config.js`:
+
+```jsx
+// next.config.js
+module.exports = {
+ experimental: {
+ runtime: 'nodejs',
+ serverComponents: true,
+ },
+}
+```
+
+Using `runtime` also enables [Streaming SSR](/docs/advanced-features/react-18/streaming). When setting `runtime` to `'edge'`, the server will be running entirely in the [Edge Runtime](https://nextjs.org/docs/api-reference/edge-runtime).
+
+Now, you can start using React Server Components in Next.js. [See our example](https://github.com/vercel/next-rsc-demo) for more information.
+
+### Server Components Conventions
+
+To run a component on the server, append `.server.js` to the end of the filename. For example, `./pages/home.server.js` will be treated as a Server Component.
+
+For client components, append `.client.js` to the filename. 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 shared components 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-side JavaScript. However, `` will still be hydrated on the client-side, like normal React components.
+
+> Make sure you're using default imports and exports for server components (`.server.js`). The support of named exports are a work in progress!
+
+To see a full example, check out the [vercel/next-react-server-components demo](https://github.com/vercel/next-react-server-components).
+
+## Supported Next.js APIs
+
+### `next/link` and `next/image`
+
+You can use `next/link` and `next/image` like before and they will be treated as client components to keep the interaction on client side.
+
+### `next/document`
+
+If you have a custom `_document`, you have to change your `_document` to a functional component like below to use server components. If you don't have one, Next.js will use the default `_document` component for you.
+
+```jsx
+// pages/_document.js
+import { Html, Head, Main, NextScript } from 'next/document'
+
+export default function Document() {
+ return (
+
+
+
+
+
+
+
+ )
+}
+```
+
+### `next/app`
+
+If you're using `_app.js`, the usage is the same as [Custom App](/docs/advanced-features/custom-app).
+If you're using `_app.server.js` as a server component, see the example below where it only receives the `children` prop as React elements. You can wrap any other client or server components around `children` to customize the layout of your app.
+
+```js
+// pages/_app.server.js
+export default function App({ children }) {
+ return children
+}
+```
+
+### Routing
+
+Both basic routes with path and queries and dynamic routes are supported. If you need to access the router in server components(`.server.js`), they will receive `router` instance as a prop so that you can directly access them without using the `useRouter()` hook.
+
+```jsx
+// pages/index.server.js
+
+export default function Index({ router }) {
+ // You can access routing information by `router.pathname`, etc.
+ return 'hello'
+}
+```
+
+### Unsupported Next.js APIs
+
+While RSC and SSR streaming are still in the alpha stage, not all Next.js APIs are supported. The following Next.js APIs have limited functionality within Server Components. React 18 use without SSR streaming is not affected.
+
+#### React internals
+
+Most React hooks, such as `useContext`, `useState`, `useReducer`, `useEffect` and `useLayoutEffect`, are not supported as of today since server components are executed per request and aren't stateful.
+
+#### Data Fetching & Styling
+
+Like streaming SSR, styling and data fetching within `Suspense` on the server side are not well supported. We're still working on them.
+
+Page level exported methods like `getInitialProps`, `getStaticProps` and `getStaticPaths` are not supported.
+
+#### `next/head` and I18n
+
+We are still working on support for these features.
diff --git a/docs/advanced-features/react-18/streaming.md b/docs/advanced-features/react-18/streaming.md
new file mode 100644
index 0000000000000..544759b3daa66
--- /dev/null
+++ b/docs/advanced-features/react-18/streaming.md
@@ -0,0 +1,71 @@
+# Streaming SSR (Alpha)
+
+React 18 will include architectural improvements to React server-side rendering (SSR) performance. This means you can use `Suspense` in your React components in streaming SSR mode and React will render them on the server and send them through HTTP streams.
+It's worth noting that another experimental feature, React Server Components, is based on streaming. You can read more about server components related streaming APIs in [`next/streaming`](docs/api-reference/next/streaming.md). However, this guide focuses on basic React 18 streaming.
+
+## Enable Streaming SSR
+
+Enabling streaming SSR means React renders your components into streams and the client continues receiving updates from these streams even after the initial SSR response is sent. In other words, when any suspended components resolve down the line, they are rendered on the server and streamed to the client. With this strategy, the app can start emitting HTML even before all the data is ready, improving your app's loading performance. As an added bonus, in streaming SSR mode, the client will also use selective hydration strategy to prioritize component hydration which based on user interaction.
+
+To enable streaming SSR, set the experimental option `runtime` to either `'nodejs'` or `'edge'`:
+
+```jsx
+// next.config.js
+module.exports = {
+ experimental: {
+ runtime: 'nodejs',
+ },
+}
+```
+
+This option determines the environment in which streaming SSR will be happening. When setting to `'edge'`, the server will be running entirely in the [Edge Runtime](https://nextjs.org/docs/api-reference/edge-runtime).
+
+## Streaming Features
+
+### next/dynamic
+
+Dynamic imports through `React.lazy` have better support in React 18. Previously, Next.js supported dynamic imports internally without requiring `Suspense` or `React.lazy`. Now to embrace the official APIs on the React side, we provide you with `options.suspense` in `next/dynamic`.
+
+```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 (
+
+ )
+}
+```
+
+Check out [`next/streaming`](/docs/api-reference/next/streaming.md) for more details on building Next.js apps in streaming SSR mode.
+
+## Important Notes
+
+#### `next/head` and `next/script`
+
+Using resource tags (e.g. scripts or stylesheets) in `next/head` won't work as intended with streaming, as the loading order and timing of `next/head` tags can no longer be guaranteed once you add Suspense boundaries. We suggest moving resource tags to `next/script` with the `afterInteractive` or `lazyOnload` strategy, or to `_document`. For similar reasons, we also suggest migrating `next/script` instances with the `beforeInteractive` strategy to `_document`.
+
+#### Data Fetching
+
+Currently, data fetching within `Suspense` boundaries on the server side is not fully supported, which could lead to mismatching between server and client. In the short-term, please don't try data fetching within `Suspense`.
+
+#### Styling
+
+The Next.js team is working on support for `styled-jsx` and CSS modules in streaming SSR. Stay tuned for updates.
diff --git a/docs/advanced-features/security-headers.md b/docs/advanced-features/security-headers.md
new file mode 100644
index 0000000000000..521ab7be2869f
--- /dev/null
+++ b/docs/advanced-features/security-headers.md
@@ -0,0 +1,158 @@
+---
+description: Improve the security of your Next.js application by adding HTTP response headers.
+---
+
+# Security Headers
+
+To improve the security of your application, you can use [`headers`](/docs/api-reference/next.config.js/headers.md) in `next.config.js` to apply HTTP response headers to all routes in your application.
+
+```jsx
+// next.config.js
+
+// You can choose which headers to add to the list
+// after learning more below.
+const securityHeaders = []
+
+module.exports = {
+ async headers() {
+ return [
+ {
+ // Apply these headers to all routes in your application.
+ source: '/:path*',
+ headers: securityHeaders,
+ },
+ ]
+ },
+}
+```
+
+## Options
+
+### [X-DNS-Prefetch-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control)
+
+This header controls DNS prefetching, allowing browsers to proactively perform domain name resolution on external links, images, CSS, JavaScript, and more. This prefetching is performed in the background, so the [DNS](https://developer.mozilla.org/en-US/docs/Glossary/DNS) is more likely to be resolved by the time the referenced items are needed. This reduces latency when the user clicks a link.
+
+```jsx
+{
+ key: 'X-DNS-Prefetch-Control',
+ value: 'on'
+}
+```
+
+### [Strict-Transport-Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
+
+This header informs browsers it should only be accessed using HTTPS, instead of using HTTP. Using the configuration below, all present and future subdomains will use HTTPS for a `max-age` of 2 years. This blocks access to pages or subdomains that can only be served over HTTP.
+
+If you're deploying to [Vercel](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
+{
+ key: 'Strict-Transport-Security',
+ value: 'max-age=63072000; includeSubDomains; preload'
+}
+```
+
+### [X-XSS-Protection](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection)
+
+This header stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although this protection is not necessary when sites implement a strong [`Content-Security-Policy`](#content-security-policy) disabling the use of inline JavaScript (`'unsafe-inline'`), it can still provide protection for older web browsers that don't support CSP.
+
+```jsx
+{
+ key: 'X-XSS-Protection',
+ value: '1; mode=block'
+}
+```
+
+### [X-Frame-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options)
+
+This header indicates whether the site should be allowed to be displayed within an `iframe`. This can prevent against clickjacking attacks. This header has been superseded by CSP's `frame-ancestors` option, which has better support in modern browsers.
+
+```jsx
+{
+ key: 'X-Frame-Options',
+ value: 'SAMEORIGIN'
+}
+```
+
+### [Permissions-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy)
+
+This header allows you to control which features and APIs can be used in the browser. It was previously named `Feature-Policy`. You can view the full list of permission options [here](https://www.w3.org/TR/permissions-policy-1/).
+
+```jsx
+{
+ key: 'Permissions-Policy',
+ value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()'
+}
+```
+
+### [X-Content-Type-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options)
+
+This header prevents the browser from attempting to guess the type of content if the `Content-Type` header is not explicitly set. This can prevent XSS exploits for websites that allow users to upload and share files. For example, a user trying to download an image, but having it treated as a different `Content-Type` like an executable, which could be malicious. This header also applies to downloading browser extensions. The only valid value for this header is `nosniff`.
+
+```jsx
+{
+ key: 'X-Content-Type-Options',
+ value: 'nosniff'
+}
+```
+
+### [Referrer-Policy](https://scotthelme.co.uk/a-new-security-header-referrer-policy/)
+
+This header controls how much information the browser includes when navigating from the current website (origin) to another. You can read about the different options [here](https://scotthelme.co.uk/a-new-security-header-referrer-policy/).
+
+```jsx
+{
+ key: 'Referrer-Policy',
+ value: 'origin-when-cross-origin'
+}
+```
+
+### [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
+
+This header helps prevent cross-site scripting (XSS), clickjacking and other code injection attacks. Content Security Policy (CSP) can specify allowed origins for content including scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more.
+
+You can read about the many different CSP options [here](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: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
+}
+```
+
+### References
+
+- [MDN](https://developer.mozilla.org)
+- [Varun Naik](https://blog.vnaik.com/posts/web-attacks.html)
+- [Scott Helme](https://scotthelme.co.uk)
+- [Mozilla Observatory](https://observatory.mozilla.org/)
+
+## Related
+
+For more information, we recommend the following sections:
+
+
diff --git a/docs/advanced-features/src-directory.md b/docs/advanced-features/src-directory.md
index 00a1628323827..6bb496833fd59 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 4451680a3544f..6408adf0b7c68 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) just fine).
->
-> 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 0000000000000..8087473ca22d1
--- /dev/null
+++ b/docs/advanced-features/using-mdx.md
@@ -0,0 +1,212 @@
+---
+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({
+ // Append the default value with md extensions
+ pageExtensions: ['ts', 'tsx', '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.
+
+To enable you need to specify `providerImportSource: "@mdx-js/react"` in `next.config.js`.
+
+```js
+// next.config.js
+
+const withMDX = require('@next/mdx')({
+ // ...
+ options: {
+ providerImportSource: '@mdx-js/react',
+ },
+})
+```
+
+Then setup the provider in your page
+
+```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 (
+
+
+
+ )
+}
+```
+
+If you use it across the site you may want to add the provider to `_app.js` so all MDX pages pick up the custom element config.
+
+## 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 bd9959252349e..20b36920d7bf3 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, telemetry
+ build, start, export, dev, lint, telemetry, info
Options
--version, -v Version number
@@ -46,7 +46,7 @@ NODE_OPTIONS='--inspect' next
- **Size** – The number of assets downloaded when navigating to the page client-side. The size for each route only includes its dependencies.
- **First Load JS** – The number of assets downloaded when visiting the page from the server. The amount of JS shared by all is shown as a separate metric.
-The first load is colored green, yellow, or red. Aim for green for performant applications.
+The first load is indicated by green, yellow, or red. Aim for green for performant applications.
You can enable production profiling for React with the `--profile` flag in `next build`. This requires [Next.js 9.5](https://nextjs.org/blog/next-9-5):
@@ -74,6 +74,20 @@ The application will start at `http://localhost:3000` by default. The default po
npx next dev -p 4000
```
+Or using the `PORT` environment variable:
+
+```bash
+PORT=4000 npx next dev
+```
+
+> Note: `PORT` can not be set in `.env` as booting up the HTTP server happens before any other code is initialized.
+
+You can also set the hostname to be different from the default of `0.0.0.0`, this can be useful for making the application available for other devices on the network. The default hostname can be changed with `-H`, like so:
+
+```bash
+npx next dev -H 192.168.1.2
+```
+
## Production
`next start` starts the application in production mode. The application should be compiled with [`next build`](#build) first.
@@ -84,9 +98,63 @@ The application will start at `http://localhost:3000` by default. The default po
npx next start -p 4000
```
+Or using the `PORT` environment variable:
+
+```bash
+PORT=4000 npx next start
+```
+
+> Note: `PORT` can not be set in `.env` as booting up the HTTP server happens before any other code is initialized.
+
+## Lint
+
+`next lint` runs ESLint for all files in the `pages`, `components`, and `lib` directories. It also
+provides a guided setup to install any required dependencies if ESLint is not already configured in
+your application.
+
+If you have other directories that you would like to lint, you can specify them using the `--dir`
+flag:
+
+```bash
+next lint --dir utils
+```
+
## Telemetry
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 24f4255df576c..f463840b88b91 100644
--- a/docs/api-reference/create-next-app.md
+++ b/docs/api-reference/create-next-app.md
@@ -4,27 +4,36 @@ description: Create Next.js apps in one command with create-next-app.
# Create Next App
-The easiest way to get started with Next.js is by using `create-next-app`. This simple 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:
+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
```
+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@latest --ts
+# or
+yarn create next-app --typescript
+```
+
### Options
`create-next-app` comes with the following options:
-- **-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.
+- **--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/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 to run `yarn create next-app`
+- **--use-npm** - Explicitly tell the CLI to bootstrap the app using npm. To bootstrap using yarn we recommend running `yarn create next-app`
### Why use Create Next App?
`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 0000000000000..004ba283a4ff5
--- /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 0000000000000..d7e7c1ee6ef50
--- /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 0000000000000..5b86474d88909
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-static-paths.md
@@ -0,0 +1,214 @@
+---
+description: API reference for `getStaticPaths`. Learn how to fetch data and generate static pages with `getStaticPaths`.
+---
+
+# getStaticPaths
+
+
+ Version History
+
+| Version | Changes |
+| ------- | ------- |
+
+| `v12.1.0` | [On-demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). |
+| `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 0000000000000..c5f34276ffa8a
--- /dev/null
+++ b/docs/api-reference/data-fetching/get-static-props.md
@@ -0,0 +1,246 @@
+---
+description: API reference for `getStaticProps`. Learn how to use `getStaticProps` to generate static pages with Next.js.
+---
+
+# getStaticProps
+
+
+ Version History
+
+| Version | Changes |
+| ------- | ------- |
+
+| `v12.1.0` | [On-demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). |
+| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. |
+| `v10.0.0` | `fallback: 'blocking'` return option added. |
+| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) |
+| `v9.3.0` | `getStaticProps` introduced. |
+
+
+
+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 f46b34615f563..0000000000000
--- 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 0000000000000..3c722513acac3
--- /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 0000000000000..cccaa3d4bfad6
--- /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 60ebbed5abd2e..0383f6ee6e6d2 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
@@ -24,13 +24,25 @@ module.exports = {
}
```
-Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the `/_next/` path (`.next/static/` folder).
+Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the `/_next/` path (`.next/static/` folder). For example, with the above configuration, the following request for a JS chunk:
-Asset prefix support does not influence the following paths:
+```
+/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
+```
+
+Would instead become:
+
+```
+https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
+```
+
+The exact configuration for uploading your files to a given CDN will depend on your CDN of choice. The only folder you need to host on your CDN is the contents of `.next/static/`, which should be uploaded as `_next/static/` as the above URL request indicates. **Do not upload the rest of your `.next/` folder**, as you should not expose your server code and other configuration to the public.
+
+While `assetPrefix` covers requests to `_next/static`, it does not influence the following paths:
- Files in the [public](/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 1d22438a7c206..aba9bd2cc8adf 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 f457b9083d177..a3f0d6132424c 100644
--- a/docs/api-reference/next.config.js/custom-page-extensions.md
+++ b/docs/api-reference/next.config.js/custom-page-extensions.md
@@ -10,11 +10,40 @@ Open `next.config.js` and add the `pageExtensions` config:
```js
module.exports = {
- pageExtensions: ['mdx', 'jsx', 'js', 'ts', 'tsx'],
+ pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'],
}
```
-> **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**: 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`, `_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
+
+To colocate test files, generated files, or other files used by components in the `pages` directory, you can prefix the extensions with something like `page`.
+
+Open `next.config.js` and add the `pageExtensions` config:
+
+```js
+module.exports = {
+ pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
+}
+```
+
+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`, `_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:
+
+```
+Build error occurred
+Error: Build optimization failed: found pages without a React Component as default export in
+pages/MyPage.generated
+pages/MyPage.test
+
+See https://nextjs.org/docs/messages/page-without-valid-component for more info.
+```
## Related
diff --git a/docs/api-reference/next.config.js/disabling-http-keep-alive.md b/docs/api-reference/next.config.js/disabling-http-keep-alive.md
new file mode 100644
index 0000000000000..bfa79ad3d8b6d
--- /dev/null
+++ b/docs/api-reference/next.config.js/disabling-http-keep-alive.md
@@ -0,0 +1,36 @@
+---
+description: Next.js will automatically use HTTP Keep-Alive by default. Learn more about how to disable HTTP Keep-Alive here.
+---
+
+# Disabling HTTP Keep-Alive
+
+Next.js automatically polyfills [node-fetch](/docs/basic-features/supported-browsers-features#polyfills) and enables [HTTP Keep-Alive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive) by default. You may want to disable HTTP Keep-Alive for certain `fetch()` calls or globally.
+
+For a single `fetch()` call, you can add the agent option:
+
+```js
+import { Agent } from 'https'
+
+const url = 'https://example.com'
+const agent = new Agent({ keepAlive: false })
+fetch(url, { agent })
+```
+
+To override all `fetch()` calls globally, you can use `next.config.js`:
+
+```js
+module.exports = {
+ httpAgentOptions: {
+ keepAlive: false,
+ },
+}
+```
+
+## Related
+
+
diff --git a/docs/api-reference/next.config.js/exportPathMap.md b/docs/api-reference/next.config.js/exportPathMap.md
index 6a5efe93f305c..a1ef9f65021f1 100644
--- a/docs/api-reference/next.config.js/exportPathMap.md
+++ b/docs/api-reference/next.config.js/exportPathMap.md
@@ -4,7 +4,7 @@ description: Customize the pages that will be exported as HTML files when using
# exportPathMap
-> This feature is exclusive of `next export`. Please refer to [Static HTML export](/docs/advanced-features/static-html-export.md) if you want to learn more about it.
+> This feature is exclusive to `next export`. Please refer to [Static HTML export](/docs/advanced-features/static-html-export.md) if you want to learn more about it.
Examples
@@ -40,7 +40,7 @@ module.exports = {
}
```
-Note: the `query` field in `exportPathMap` can not 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 can not 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 69bc627a84aef..5905a0860dd94 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 = {
},
],
},
- ],
+ ]
},
}
```
@@ -166,13 +166,17 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg
```js
module.exports = {
- async redirects() {
+ async headers() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
- destination: '/en-us/:slug',
- permanent: false,
+ headers: [
+ {
+ key: 'x-header',
+ value: 'value',
+ },
+ ],
},
]
},
@@ -361,7 +365,7 @@ module.exports = {
headers: [
{
key: 'x-hello',
- value: 'worlld',
+ value: 'world',
},
],
},
@@ -372,4 +376,15 @@ 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
+
+For more information, we recommend the following sections:
+
+
diff --git a/docs/api-reference/next.config.js/ignoring-eslint.md b/docs/api-reference/next.config.js/ignoring-eslint.md
new file mode 100644
index 0000000000000..650c678bfd072
--- /dev/null
+++ b/docs/api-reference/next.config.js/ignoring-eslint.md
@@ -0,0 +1,37 @@
+---
+description: Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.
+---
+
+# Ignoring ESLint
+
+When ESLint is detected in your project, Next.js fails your **production build** (`next build`) when errors are present.
+
+If you'd like Next.js to produce production code even when your application has ESLint errors, you can disable the built-in linting step completely. This is not recommended unless you already have ESLint configured to run in a separate part of your workflow (for example, in CI or a pre-commit hook).
+
+Open `next.config.js` and enable the `ignoreDuringBuilds` option in the `eslint` config:
+
+```js
+module.exports = {
+ eslint: {
+ // Warning: This allows production builds to successfully complete even if
+ // your project has ESLint errors.
+ ignoreDuringBuilds: true,
+ },
+}
+```
+
+## Related
+
+
diff --git a/docs/api-reference/next.config.js/introduction.md b/docs/api-reference/next.config.js/introduction.md
index 474257638f4bc..4c7b116436a68 100644
--- a/docs/api-reference/next.config.js/introduction.md
+++ b/docs/api-reference/next.config.js/introduction.md
@@ -4,29 +4,65 @@ 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.
Take a look at the following `next.config.js` example:
```js
-module.exports = {
+/**
+ * @type {import('next').NextConfig}
+ */
+const nextConfig = {
/* config options here */
}
+
+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
module.exports = (phase, { defaultConfig }) => {
- return {
+ /**
+ * @type {import('next').NextConfig}
+ */
+ const nextConfig = {
+ /* config options here */
+ }
+ return nextConfig
+}
+```
+
+Since Next.js 12.1.0, 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 [here](https://github.com/vercel/next.js/blob/canary/packages/next/next-server/lib/constants.ts#L1-L4). Phases can be imported from `next/constants`:
+`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')
@@ -44,7 +80,7 @@ module.exports = (phase, { defaultConfig }) => {
}
```
-The commented lines are the place where you can put the configs allowed by `next.config.js`, which are defined [here](https://github.com/vercel/next.js/blob/canary/packages/next/next-server/server/config-shared.ts#L68).
+The commented lines are the place where you can put the configs allowed by `next.config.js`, which are [defined in this file](https://github.com/vercel/next.js/blob/canary/packages/next/server/config-shared.ts#L68).
However, none of the configs are required, and it's not necessary to understand what each config does. Instead, search for the features you need to enable or modify in this section and they will show you what to do.
diff --git a/docs/api-reference/next.config.js/react-strict-mode.md b/docs/api-reference/next.config.js/react-strict-mode.md
index d442b81ac1ad0..b844bf84506fd 100644
--- a/docs/api-reference/next.config.js/react-strict-mode.md
+++ b/docs/api-reference/next.config.js/react-strict-mode.md
@@ -6,7 +6,9 @@ description: The complete Next.js runtime is now Strict Mode-compliant, learn ho
> **Suggested**: We strongly suggest you enable Strict Mode in your Next.js application to better prepare your application for the future of React.
-The Next.js runtime is now Strict Mode-compliant. To opt-in to Strict Mode, configure the following option in your `next.config.js`:
+React's [Strict Mode](https://reactjs.org/docs/strict-mode.html) is a development mode only feature for highlighting potential problems in an application. It helps to identify unsafe lifecycles, legacy API usage, and a number of other features.
+
+The Next.js runtime is Strict Mode-compliant. To opt-in to Strict Mode, configure the following option in your `next.config.js`:
```js
// next.config.js
@@ -15,9 +17,7 @@ module.exports = {
}
```
-If you or your team are not ready to use Strict Mode in your entire application, that's OK! You can incrementally migrate on a page-by-page basis [using ``](https://reactjs.org/docs/strict-mode.html).
-
-React's Strict Mode is a development mode only feature for highlighting potential problems in an application. It helps to identify unsafe lifecycles, legacy API usage, and a number of other features.
+If you or your team are not ready to use Strict Mode in your entire application, that's OK! You can incrementally migrate on a page-by-page basis using ``.
## Related
diff --git a/docs/api-reference/next.config.js/redirects.md b/docs/api-reference/next.config.js/redirects.md
index 7dd369881fee5..30f7ac88c6805 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,13 +43,25 @@ 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.
Redirects are checked before the filesystem which includes pages and `/public` files.
+When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration:
+
+```js
+{
+ source: '/old-blog/:path*',
+ destination: '/blog/:path*',
+ permanent: false
+}
+```
+
+When `/old-blog/post-1?hello=world` is requested, the client will be redirected to `/blog/post-1?hello=world`.
+
## Path Matching
Path matches are allowed, for example `/old-blog/:slug` will match `/old-blog/hello-world` (no nested paths):
@@ -189,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',
},
]
@@ -279,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 927fc23778c27..16ae2b533df85 100644
--- a/docs/api-reference/next.config.js/rewrites.md
+++ b/docs/api-reference/next.config.js/rewrites.md
@@ -23,7 +23,7 @@ description: Add rewrites to your Next.js app.
Rewrites allow you to map an incoming request path to a different destination path.
-Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, [redirects](/docs/api-reference/next.config.js/redirects.md) will reroute to a new page a show the URL changes.
+Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, [redirects](/docs/api-reference/next.config.js/redirects.md) will reroute to a new page and show the URL changes.
To use rewrites you can use the `rewrites` key in `next.config.js`:
@@ -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 = {
@@ -79,7 +79,7 @@ module.exports = {
// and dynamic routes are checked
{
source: '/:path*',
- destination: 'https://my-old-site.com',
+ destination: `https://my-old-site.com/:path*`,
},
],
}
@@ -87,6 +87,17 @@ module.exports = {
}
```
+Note: rewrites in `beforeFiles` do not check the filesystem/dynamic routes immediately after matching a source, they continue until all `beforeFiles` have been checked.
+
+The order Next.js routes are checked is:
+
+1. [headers](/docs/api-reference/next.config.js/headers) are checked/applied
+2. [redirects](/docs/api-reference/next.config.js/redirects) are checked/applied
+3. `beforeFiles` rewrites are checked/applied
+4. static files from the [public directory](/docs/basic-features/static-file-serving), `_next/static` files, and non-dynamic pages are checked/served
+5. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match
+6. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked.
+
## Rewrite parameters
When using parameters in a rewrite the parameters will be passed in the query by default when none of the parameters are used in the `destination`.
@@ -137,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):
@@ -192,13 +205,12 @@ The following characters `(`, `)`, `{`, `}`, `:`, `*`, `+`, `?` are used for reg
```js
module.exports = {
- async redirects() {
+ async rewrites() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
destination: '/en-us/:slug',
- permanent: false,
},
]
},
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 0000000000000..bb50c6ffe6b10
--- /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/amp.md b/docs/api-reference/next/amp.md
index ac3ee8924b560..6cc212791168d 100644
--- a/docs/api-reference/next/amp.md
+++ b/docs/api-reference/next/amp.md
@@ -11,7 +11,7 @@ description: Enable AMP in a page, and control the way Next.js adds AMP to the p
-> AMP support is one of our advanced features, you can read more about it [here](/docs/advanced-features/amp-support/introduction.md).
+> AMP support is one of our advanced features, you can [read more about AMP here](/docs/advanced-features/amp-support/introduction.md).
To enable AMP, add the following config to your page:
diff --git a/docs/api-reference/next/head.md b/docs/api-reference/next/head.md
index b642c18cd5761..96a6d14a5ea31 100644
--- a/docs/api-reference/next/head.md
+++ b/docs/api-reference/next/head.md
@@ -55,9 +55,11 @@ 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.
`title`, `meta` or any other elements (e.g. `script`) need to be contained as **direct** children of the `Head` element,
or wrapped into maximum one level of `` or arrays—otherwise the tags won't be correctly picked up on client-side navigations.
+
+> We recommend using [next/script](/docs/basic-features/script.md) in your component instead of manually creating a `
+```
+
+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 (
+ <>
+
+```
+
+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.
+
+
+
+#### 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), lowercase alphabets (a to z) and it must be no more than 15 characters in length. No other characters (#,$,&, etc.) are allowed. The rule in RegEx is written as `[a-z0-9]{1,15}`.
+
+
+
+> 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)
+
+ // Guard clause checks for first and last name,
+ // and returns early if they are not found
+ if (!body.first || !body.last) {
+ // Sends a HTTP bad request error code
+ return res.status(400).json({ data: 'First or last name not found' })
+ }
+
+ // Found the name.
+ // Sends a HTTP success code
+ res.status(200).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.
+
+
+
+## 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.
+
+
+
+## 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 `
+ )
+}
+
+export default Home
+```
+
+### Useful Links
+
+- [Script component docs](https://nextjs.org/docs/basic-features/script/)
diff --git a/errors/no-server-import-in-page.md b/errors/no-server-import-in-page.md
new file mode 100644
index 0000000000000..c8fc45069a28f
--- /dev/null
+++ b/errors/no-server-import-in-page.md
@@ -0,0 +1,23 @@
+# No Server Import In Page
+
+### Why This Error Occurred
+
+`next/server` was imported outside of `pages/**/_middleware.{js,ts}`.
+
+### Possible Ways to Fix It
+
+Only import and use `next/server` in a file located within the pages directory: `pages/**/_middleware.{js,ts}`.
+
+```ts
+// pages/_middleware.ts
+
+import type { NextFetchEvent, NextRequest } from 'next/server'
+
+export function middleware(req: NextRequest, ev: NextFetchEvent) {
+ return new Response('Hello, world!')
+}
+```
+
+### Useful Links
+
+- [Middleware](https://nextjs.org/docs/middleware)
diff --git a/errors/no-stylesheets-in-head-component.md b/errors/no-stylesheets-in-head-component.md
new file mode 100644
index 0000000000000..3e3901a682ddd
--- /dev/null
+++ b/errors/no-stylesheets-in-head-component.md
@@ -0,0 +1,42 @@
+# No Stylesheets In Head Component
+
+### Why This Error Occurred
+
+A `` tag was added using the `next/head` component.
+
+We don't recommend this pattern because it will potentially break when used with Suspense and/or streaming. In these contexts, `next/head` tags aren't:
+
+- guaranteed to be included in the initial SSR response, so loading could be delayed until client-side rendering, regressing performance.
+
+- loaded in any particular order. The order that the app's Suspense boundaries resolve will determine the loading order of your stylesheets.
+
+### Possible Ways to Fix It
+
+#### Document
+
+Add the stylesheet in a custom `Document` component.
+
+```jsx
+// pages/_document.js
+import Document, { Html, Head, Main, NextScript } from 'next/document'
+
+export default function Document() {
+ return (
+
+
+
+
+
+
+
+
+
+ )
+}
+```
+
+Note that the functional syntax for `Document` above is preferred over the `class` syntax, so that it will be compatible with React Server Components down the line.
+
+### Useful Links
+
+- [Custom Document](https://nextjs.org/docs/advanced-features/custom-document)
diff --git a/errors/no-sync-scripts.md b/errors/no-sync-scripts.md
index 1788236d85df1..b8a200e8b58d8 100644
--- a/errors/no-sync-scripts.md
+++ b/errors/no-sync-scripts.md
@@ -11,9 +11,9 @@ A synchronous script was used which can impact your webpage's performance.
Use the Script component with the right loading strategy to defer loading of the script until necessary.
```jsx
-import Script from 'next/experimental-script'
+import Script from 'next/script'
-const Home = () => {
+function Home() {
return (
@@ -25,8 +25,6 @@ const Home = () => {
export default Home
```
-Note: This is still an experimental feature and needs to be enabled via the `experimental.scriptLoader` flag in `next.config.js`.
-
### Useful Links
- [Efficiently load third-party JavaScript](https://web.dev/efficiently-load-third-party-javascript/)
diff --git a/errors/opening-an-issue.md b/errors/opening-an-issue.md
new file mode 100644
index 0000000000000..179f895135e4d
--- /dev/null
+++ b/errors/opening-an-issue.md
@@ -0,0 +1,28 @@
+# Opening a new Issue
+
+#### Why This Message Occurred
+
+When `next info` was run, Next.js detected that it's was not on the latest canary release.
+
+`next@canary` is the canary version of Next.js that ships daily. It includes all features and fixes that have not been released to the stable version yet. Think of canary as a public beta.
+
+Some issues may already be fixed in the canary version, so please verify that your issue reproduces before opening a new issue.
+
+Run the following in the codebase:
+
+```sh
+npm install next@canary
+```
+
+or
+
+```sh
+yarn add next@canary
+```
+
+And go through the prepared reproduction steps once again, and check if the issue still exists.
+
+### Useful Links
+
+- [Video: How to Contribute to Open Source (Next.js)](https://www.youtube.com/watch?v=cuoNzXFLitc)
+- [Contributing to Next.js](https://github.com/vercel/next.js/blob/canary/contributing.md)
diff --git a/errors/page-data-collection-timeout.md b/errors/page-data-collection-timeout.md
new file mode 100644
index 0000000000000..49d2d80fa9f68
--- /dev/null
+++ b/errors/page-data-collection-timeout.md
@@ -0,0 +1,18 @@
+# Collecting page data timed out after multiple attempts
+
+#### Why This Error Occurred
+
+Next.js tries to restart the worker pool of the page data collection when no progress happens for a while, to avoid hanging builds.
+
+When restarted it will retry all uncompleted jobs, but if a job was unsuccessfully attempted multiple times, this will lead to an error.
+
+#### Possible Ways to Fix It
+
+- Make sure that there is no infinite loop during execution.
+- Make sure all Promises in `getStaticPaths` `resolve` or `reject` correctly.
+- Avoid very long timeouts for network requests.
+- Increase the timeout by changing the `config.staticPageGenerationTimeout` configuration option (default `60` in seconds).
+
+### Useful Links
+
+- [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md)
diff --git a/errors/page-without-valid-component.md b/errors/page-without-valid-component.md
index 09d94fee00c35..965bce9fdb6d6 100644
--- a/errors/page-without-valid-component.md
+++ b/errors/page-without-valid-component.md
@@ -14,3 +14,5 @@ For each, you'll want to check if the file is meant to be a page.
If the file is not meant to be a page, and instead, is a shared component or file, move the file to a different folder like `components` or `lib`.
If the file is meant to be a page, double check you have an `export default` with the React Component instead of an `export`. If you're already using `export default`, make sure the returned value is a valid React Component.
+
+If you need to support a different file extension for a page component (such as `.mdx`) or would like to include non-page files in the `pages` directory, configure [Custom Page Extensions](https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions) in the `next.config.js`.
diff --git a/errors/placeholder-blur-data-url.md b/errors/placeholder-blur-data-url.md
new file mode 100644
index 0000000000000..9c9a76819dd78
--- /dev/null
+++ b/errors/placeholder-blur-data-url.md
@@ -0,0 +1,15 @@
+# `placeholder=blur` without `blurDataURL`
+
+#### Why This Error Occurred
+
+You are attempting use the `next/image` component with `placeholder=blur` property but no `blurDataURL` property.
+
+The `blurDataURL` might be missing because you're using a string for `src` instead of a static import.
+
+Or `blurDataURL` might be missing because the static import is an unsupported image format. Only jpg, png, webp, and avif are supported at this time.
+
+#### Possible Ways to Fix It
+
+- Add a [`blurDataURL`](https://nextjs.org/docs/api-reference/next/image#blurdataurl) property, the contents should be a small Data URL to represent the image
+- Change the [`src`](https://nextjs.org/docs/api-reference/next/image#src) property to a static import with one of the supported file types: jpg, png, or webp
+- Remove the [`placeholder`](https://nextjs.org/docs/api-reference/next/image#placeholder) property, effectively no blur effect
diff --git a/errors/postcss-ignored-plugin.md b/errors/postcss-ignored-plugin.md
index 658ad57f28575..e8c73f1c69965 100644
--- a/errors/postcss-ignored-plugin.md
+++ b/errors/postcss-ignored-plugin.md
@@ -17,4 +17,4 @@ Remove the plugin specified in the error message from your custom PostCSS config
#### How do I configure CSS Modules?
CSS Modules are supported in [Next.js' built-in CSS support](https://nextjs.org/docs/advanced-features/customizing-postcss-config).
-You can [read more](https://nextjs.org/docs/advanced-features/customizing-postcss-config) about how to use them [here](https://nextjs.org/docs/advanced-features/customizing-postcss-config).
+You can [read more about how to use CSS Modules here](https://nextjs.org/docs/advanced-features/customizing-postcss-config).
diff --git a/errors/postcss-shape.md b/errors/postcss-shape.md
index 889fe55bcbc68..f121c889d04b1 100644
--- a/errors/postcss-shape.md
+++ b/errors/postcss-shape.md
@@ -39,7 +39,7 @@ module.exports = {
}
```
-You can [read more](https://nextjs.org/docs/advanced-features/customizing-postcss-config) about configuring PostCSS in Next.js [here](https://nextjs.org/docs/advanced-features/customizing-postcss-config).
+You can [read more about configuring PostCSS in Next.js here](https://nextjs.org/docs/advanced-features/customizing-postcss-config).
#### Common Errors
diff --git a/errors/prefetch-true-deprecated.md b/errors/prefetch-true-deprecated.md
index dbc5a2ed346f4..77733fea94726 100644
--- a/errors/prefetch-true-deprecated.md
+++ b/errors/prefetch-true-deprecated.md
@@ -18,4 +18,4 @@ These requests have low-priority and yield to fetch() or XHR requests. Next.js w
The prefetch attribute is no longer needed, when set to true, example: `prefetch={true}`, remove the property.
-Prefetching can be disabled with `prefetch={false}`.
+Prefetching can be turned off with `prefetch={false}`.
diff --git a/errors/prerender-error.md b/errors/prerender-error.md
index 87e301c459db6..474926c9631ba 100644
--- a/errors/prerender-error.md
+++ b/errors/prerender-error.md
@@ -7,7 +7,8 @@ While prerendering a page an error occurred. This can occur for many reasons fro
#### Possible Ways to Fix It
- Make sure to move any non-pages out of the `pages` folder
-- Check for any code that assumes a prop is available even when it might not be. e.g., have default data for all dynamic pages' props.
+- Check for any code that assumes a prop is available, even when it might not be
+- Set default values for all dynamic pages' props (avoid `undefined`, use `null` instead so it can be serialized)
- Check for any out of date modules that you might be relying on
-- Make sure your component handles `fallback` if it is enabled in `getStaticPaths`. [Fallback docs](https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required)
-- Make sure you are not trying to export (`next export`) pages that have server-side rendering enabled [(getServerSideProps)](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering)
+- Make sure your component handles `fallback` if it is enabled in `getStaticPaths`. [Fallback docs](https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-false)
+- Make sure you are not trying to export (`next export`) pages that have server-side rendering enabled [(getServerSideProps)](/docs/basic-features/data-fetching/get-server-side-props.md)
diff --git a/errors/promise-in-next-config.md b/errors/promise-in-next-config.md
index f39ce7786fc78..84ac204fa85c9 100644
--- a/errors/promise-in-next-config.md
+++ b/errors/promise-in-next-config.md
@@ -14,6 +14,8 @@ module.exports = {
#### Possible Ways to Fix It
-Check your `next.config.js` for `async` or `return Promise`
+In Next.js versions above `12.0.10`, `module.exports = async () =>` is supported.
+
+For older versions, you can check your `next.config.js` for `async` or `return Promise`.
Potentially a plugin is returning a `Promise` from the webpack function.
diff --git a/errors/react-hydration-error.md b/errors/react-hydration-error.md
new file mode 100644
index 0000000000000..38ea8e05540b9
--- /dev/null
+++ b/errors/react-hydration-error.md
@@ -0,0 +1,53 @@
+# React Hydration Error
+
+#### Why This Error Occurred
+
+While rendering your application, there was a difference between the React tree that was pre-rendered (SSR/SSG) and the React tree that rendered during the first render in the Browser. The first render is called Hydration which is a [feature of React](https://reactjs.org/docs/react-dom.html#hydrate).
+
+This can cause the React tree to be out of sync with the DOM and result in unexpected content/attributes being present.
+
+#### Possible Ways to Fix It
+
+In general this issue is caused by using a specific library or application code that is relying on something that could differ between pre-rendering and the browser. An example of this is using `window` in a component's rendering.
+
+An example:
+
+```jsx
+function MyComponent() {
+ // This condition depends on `window`. During the first render of the browser the `color` variable will be different
+ const color = typeof window !== 'undefined' ? 'red' : 'blue'
+ // As color is passed as a prop there is a mismatch between what was rendered server-side vs what was rendered in the first render
+ return
Hello World!
+}
+```
+
+How to fix it:
+
+```jsx
+// In order to prevent the first render from being different you can use `useEffect` which is only executed in the browser and is executed during hydration
+import { useEffect, useState } from 'react'
+function MyComponent() {
+ // The default value is 'blue', it will be used during pre-rendering and the first render in the browser (hydration)
+ const [color, setColor] = useState('blue')
+ // During hydration `useEffect` is called. `window` is available in `useEffect`. In this case because we know we're in the browser checking for window is not needed. If you need to read something from window that is fine.
+ // By calling `setColor` in `useEffect` a render is triggered after hydrating, this causes the "browser specific" value to be available. In this case 'red'.
+ useEffect(() => setColor('red'), [])
+ // As color is a state passed as a prop there is no mismatch between what was rendered server-side vs what was rendered in the first render. After useEffect runs the color is set to 'red'
+ return
Hello World!
+}
+```
+
+Common causes with css-in-js libraries:
+
+- When using Styled Components / Emotion
+ - When css-in-js libraries are not set up for pre-rendering (SSR/SSG) it will often lead to a hydration mismatch. In general this means the application has to follow the Next.js example for the library. For example if `pages/_document` is missing and the Babel plugin is not added.
+ - Possible fix for Styled Components: https://github.com/vercel/next.js/tree/canary/examples/with-styled-components
+ - If you want to leverage Styled Components with the new Next.js Compiler in Next.js 12 there is an [experimental flag available](https://github.com/vercel/next.js/discussions/30174#discussion-3643870)
+ - Possible fix for Emotion: https://github.com/vercel/next.js/tree/canary/examples/with-emotion
+- When using other css-in-js libraries
+ - Similar to Styled Components / Emotion css-in-js libraries generally need configuration specified in their examples in the [examples directory](https://github.com/vercel/next.js/tree/canary/examples)
+
+### Useful Links
+
+- [React Hydration Documentation](https://reactjs.org/docs/react-dom.html#hydrate)
+- [Josh Comeau's article on React Hydration](https://www.joshwcomeau.com/react/the-perils-of-rehydration/)
diff --git a/errors/react-version.md b/errors/react-version.md
index cfa4412e88461..713254102491b 100644
--- a/errors/react-version.md
+++ b/errors/react-version.md
@@ -5,7 +5,7 @@
Your project is using an old version of `react` or `react-dom` that does not
meet the suggested minimum version requirement.
-Next.js suggests using, at a minimum, `react@17.0.1` and `react-dom@17.0.1`.
+Next.js suggests using, at a minimum, `react@17.0.2` and `react-dom@17.0.2`.
Older versions of `react` and `react-dom` do work with Next.js, however, they do
not enable all of Next.js' features.
@@ -39,8 +39,8 @@ yarn add react@latest react-dom@latest
```json
{
"dependencies": {
- "react": "^17.0.1",
- "react-dom": "^17.0.1"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
}
}
```
diff --git a/errors/rewrite-auto-export-fallback.md b/errors/rewrite-auto-export-fallback.md
index a16fa7125639d..af712a447757f 100644
--- a/errors/rewrite-auto-export-fallback.md
+++ b/errors/rewrite-auto-export-fallback.md
@@ -10,7 +10,7 @@ Rewriting to these pages are not yet supported since rewrites are not available
For fallback SSG pages you can add the page to the list of [prerendered paths](https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required).
-For static dynamic routes, you will currently need to either rewrite to non-dynamic route or opt the page out of the static optimization with [`getServerSideProps`](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering)
+For static dynamic routes, you will currently need to either rewrite to non-dynamic route or opt the page out of the static optimization with [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)
### Useful Links
diff --git a/errors/sharp-missing-in-production.md b/errors/sharp-missing-in-production.md
new file mode 100644
index 0000000000000..96903efad9ca5
--- /dev/null
+++ b/errors/sharp-missing-in-production.md
@@ -0,0 +1,19 @@
+# Sharp Missing In Production
+
+#### Why This Error Occurred
+
+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. For a production environment using `next start`, it is strongly recommended you install [`sharp`](https://www.npmjs.com/package/sharp) by running `yarn add sharp` in your project directory.
+
+You are seeing this error because Image Optimization in production mode (`next start`) was detected.
+
+#### Possible Ways to Fix It
+
+- Install `sharp` by running `yarn add sharp` in your project directory and then reboot the server by running `next start` again
+- If `sharp` is already installed but can't be resolved, set the `NEXT_SHARP_PATH` environment variable such as `NEXT_SHARP_PATH=/tmp/node_modules/sharp next start`
+
+> Note: This is not necessary for Vercel deployments, since `sharp` is installed automatically for you.
+
+### Useful Links
+
+- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
+- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
diff --git a/errors/sharp-version-avif.md b/errors/sharp-version-avif.md
new file mode 100644
index 0000000000000..dcd90aea36629
--- /dev/null
+++ b/errors/sharp-version-avif.md
@@ -0,0 +1,24 @@
+# Sharp Version Does Not Support AVIF
+
+#### Why This Error Occurred
+
+The `next/image` component's default loader uses [`sharp`](https://www.npmjs.com/package/sharp) if its installed.
+
+You are seeing this error because you have an outdated version of [`sharp`](https://www.npmjs.com/package/sharp) installed that does not support the AVIF image format.
+
+AVIF support was added to [`sharp`](https://www.npmjs.com/package/sharp) in version 0.27.0 (December 2020) so your installed version is likely older.
+
+#### Possible Ways to Fix It
+
+- Install the latest version of `sharp` by running `yarn add sharp@latest` in your project directory
+- If you're using the `NEXT_SHARP_PATH` environment variable, then update the `sharp` install referenced in that path, for example `cd "$NEXT_SHARP_PATH/../" && yarn add sharp@latest`
+- If you cannot upgrade `sharp`, you can instead disable AVIF by configuring [`formats`](https://nextjs.org/docs/api-reference/next/image#image-formats) in your `next.config.js`
+
+After choosing an option above, reboot the server by running either `next dev` or `next start` for development or production respectively.
+
+> Note: This is not necessary for Vercel deployments, since `sharp` is installed automatically for you.
+
+### Useful Links
+
+- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
+- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
diff --git a/errors/static-dir-deprecated.md b/errors/static-dir-deprecated.md
index 9a8138e987ad4..76e13986aed9a 100644
--- a/errors/static-dir-deprecated.md
+++ b/errors/static-dir-deprecated.md
@@ -8,7 +8,7 @@ The reason we want to support a `public` directory instead is to not require the
#### Possible Ways to Fix It
-You can move your `static` directory inside of the `public` directory and all URLs will remain the same as they were before.
+You can move your `static` directory inside of the `public` directory and all URLs will stay the same as they were before.
**Before**
diff --git a/errors/static-page-generation-timeout.md b/errors/static-page-generation-timeout.md
new file mode 100644
index 0000000000000..c8cc05e24f341
--- /dev/null
+++ b/errors/static-page-generation-timeout.md
@@ -0,0 +1,19 @@
+# Static page generation timed out after multiple attempts
+
+#### Why This Error Occurred
+
+Next.js tries to restart the worker pool of the static page generation when no progress happens for a while, to avoid hanging builds.
+
+When restarted it will retry all uncompleted jobs, but if a job was unsuccessfully attempted multiple times, this will lead to an error.
+
+#### Possible Ways to Fix It
+
+- Make sure that there is no infinite loop during execution.
+- Make sure all Promises in `getStaticPaths`/`getStaticProps` `resolve` or `reject` correctly.
+- Avoid very long timeouts for network requests.
+- Increase the timeout by changing the `staticPageGenerationTimeout` configuration option (default `60` in seconds).
+
+### Useful Links
+
+- [`getStaticPaths`](https://nextjs.org/docs/basic-features/data-fetching/get-static-paths.md)
+- [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching/get-static-props.md)
diff --git a/errors/swc-disabled.md b/errors/swc-disabled.md
new file mode 100644
index 0000000000000..701f260c785b4
--- /dev/null
+++ b/errors/swc-disabled.md
@@ -0,0 +1,17 @@
+# SWC disabled
+
+#### Why This Message Occurred
+
+Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScript/TypeScript. This new compiler is up to 17x faster than Babel when compiling individual files and up to 5x faster Fast Refresh.
+
+Next.js provides full backwards compatibility with applications that have [custom Babel configuration](https://nextjs.org/docs/advanced-features/customizing-babel-config). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust.
+
+When an application has custom Babel configuration Next.js will automatically opt-out of using SWC for compiling JavaScript/Typescript and will fall back to using Babel in the same way that it was used in Next.js 11.
+
+Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to:
+
+- Styled Components
+- Emotion
+- Relay
+
+In order to prioritize transforms that will help you adopt SWC please provide your `.babelrc` on [the feedback thread](https://github.com/vercel/next.js/discussions/30174).
diff --git a/errors/swc-minify-enabled.md b/errors/swc-minify-enabled.md
new file mode 100644
index 0000000000000..712affcf27a7a
--- /dev/null
+++ b/errors/swc-minify-enabled.md
@@ -0,0 +1,7 @@
+# SWC minify enabled
+
+#### Why This Message Occurred
+
+The application has enabled `swcMinify` in `next.config.js`. By opting in minification will happen using the [SWC](https://swc.rs) minifier instead of Terser. This new minifier is 7x faster than Terser with comparable output. We're actively working on optimizing the output size and minification speed further.
+
+If you have feedback about the minification, please provide it on [the feedback thread](https://github.com/vercel/next.js/discussions/30237).
diff --git a/errors/template.txt b/errors/template.txt
new file mode 100644
index 0000000000000..3aa3e131acac5
--- /dev/null
+++ b/errors/template.txt
@@ -0,0 +1,13 @@
+# {{title}}
+
+#### Why This Error Occurred
+
+
+
+#### Possible Ways to Fix It
+
+
+
+### Useful Links
+
+
diff --git a/errors/threw-undefined.md b/errors/threw-undefined.md
index 0d4129ef4f115..4804488cafc49 100644
--- a/errors/threw-undefined.md
+++ b/errors/threw-undefined.md
@@ -1,9 +1,21 @@
-# Threw undefined in render
+# Threw `undefined`/`null`
#### Why This Error Occurred
-Somewhere in your code you `throw` an `undefined` value. Since this isn't a valid error there isn't a stack trace. We show this error instead to let you know what to look for.
+Somewhere in your code you `throw` an `undefined` or `null` value. Since this isn't a valid error there isn't a stack trace. We show this error instead to let you know what to look for.
+
+```js
+function getData() {
+ let error
+ throw error
+}
+
+function Page() {
+ const error = data?.error || null
+ throw error
+}
+```
#### Possible Ways to Fix It
-Look in your pages and find where an error could be throwing `undefined`
+Look in your pages and find where an error could be throwing `undefined` or `null` values and ensure `new Error()` is used instead.
diff --git a/errors/url-deprecated.md b/errors/url-deprecated.md
index 50db5b6b5ad7f..df352d8e07068 100644
--- a/errors/url-deprecated.md
+++ b/errors/url-deprecated.md
@@ -10,7 +10,7 @@ The reason this is going away is that we want to make things very predictable an
#### Possible Ways to Fix It
-https://github.com/zeit/next-codemod#url-to-withrouter
+https://nextjs.org/docs/advanced-features/codemods#url-to-withrouter
Since Next 5 we provide a way to explicitly inject the Next.js router object into pages and all their descending components.
The `router` property that is injected will hold the same values as `url`, like `pathname`, `asPath`, and `query`.
@@ -33,4 +33,4 @@ export default withRouter(Page)
We provide a codemod (a code to code transformation) to automatically change the `url` property usages to `withRouter`.
-You can find this codemod and instructions on how to run it here: https://github.com/zeit/next-codemod#url-to-withrouter
+You can find this codemod and instructions on how to run it here: https://nextjs.org/docs/advanced-features/codemods#url-to-withrouter
diff --git a/errors/webpack5.md b/errors/webpack5.md
index 97bab43d9b93d..a7f0d6f72bcde 100644
--- a/errors/webpack5.md
+++ b/errors/webpack5.md
@@ -2,17 +2,19 @@
#### Why This Message Occurred
-Next.js will soon adopt webpack 5 as the default for compilation. We've spent a lot of effort into ensuring the transition from webpack 4 to 5 will be as smooth as possible. For example Next.js now comes with both webpack 4 and 5 allowing you to adopt webpack 5 by adding a flag to your `next.config.js`:
+Next.js has adopted webpack 5 as the default for compilation. We've spent a lot of effort into ensuring the transition from webpack 4 to 5 will be as smooth as possible.
+
+Your application currently has webpack 5 disabled using the `webpack5: false` flag which has been removed in Next.js 12:
```js
module.exports = {
- future: {
- webpack5: true,
- },
+ // Webpack 5 is enabled by default
+ // You can still use webpack 4 while upgrading to the latest version of Next.js by adding the "webpack5: false" flag
+ webpack5: false,
}
```
-Adopting webpack 5 in your application has many benefits, notably:
+Using webpack 5 in your application has many benefits, notably:
- Improved Disk Caching: `next build` is significantly faster on subsequent builds
- Improved Fast Refresh: Fast Refresh work is prioritized
@@ -22,11 +24,12 @@ Adopting webpack 5 in your application has many benefits, notably:
- Support for web workers using `new Worker(new URL("worker.js", import.meta.url))`
- Support for `exports`/`imports` field in `package.json`
-In upcoming releases we'll gradually roll out webpack 5 to applications that are compatible with webpack 5:
+In the past releases we have gradually rolled out webpack 5 to Next.js applications:
-- In the next minor version we'll automatically opt-in applications without custom webpack configuration in `next.config.js`
-- In the next minor version we'll automatically opt-in applications that do not have a `next.config.js`
-- In the next major version we'll enable webpack 5 by default. You'll still be able to opt-out and use webpack 4 to help with backwards compatibility
+- In Next.js 10.2 we automatically opted-in applications without custom webpack configuration in `next.config.js`
+- In Next.js 10.2 we automatically opted-in applications that do not have a `next.config.js`
+- In Next.js 11 webpack 5 was enabled by default for all applications. You could still opt-out and use webpack 4 to help with backwards compatibility using `webpack5: false` in `next.config.js`
+- In Next.js 12 webpack 4 support was removed.
#### Custom webpack configuration
@@ -34,7 +37,7 @@ In case you do have custom webpack configuration, either through custom plugins
- When using `next-transpile-modules` make sure you use the latest version which includes [this patch](https://github.com/martpie/next-transpile-modules/pull/179)
- When using `@zeit/next-css` / `@zeit/next-sass` make sure you use the [built-in CSS/Sass support](https://nextjs.org/docs/basic-features/built-in-css-support) instead
-- When using `@zeit/next-preact` use [this example](https://github.com/vercel/next-plugins/tree/master/packages/next-preact) instead
+- When using `@zeit/next-preact` use [this example](https://github.com/vercel/next.js/tree/canary/examples/using-preact) instead
- When using `@zeit/next-source-maps` use the [built-in production Source Map support](https://nextjs.org/docs/advanced-features/source-maps)
- When using webpack plugins make sure they're upgraded to the latest version, in most cases the latest version will include webpack 5 support. In some cases these upgraded webpack plugins will only support webpack 5.
diff --git a/examples/active-class-name/README.md b/examples/active-class-name/README.md
index 03d46cea4d39e..902d79e24b7fe 100644
--- a/examples/active-class-name/README.md
+++ b/examples/active-class-name/README.md
@@ -2,6 +2,12 @@
ReactRouter has a convenience property on the `Link` element to allow an author to set the _active_ className on a link. This example replicates that functionality using Next's own `Link`.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/active-class-name)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/active-class-name/components/ActiveLink.js b/examples/active-class-name/components/ActiveLink.js
index 0db59b6a9227a..7ada49c52056e 100644
--- a/examples/active-class-name/components/ActiveLink.js
+++ b/examples/active-class-name/components/ActiveLink.js
@@ -1,20 +1,46 @@
+import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import PropTypes from 'prop-types'
import Link from 'next/link'
import React, { Children } from 'react'
const ActiveLink = ({ children, activeClassName, ...props }) => {
- const { asPath } = useRouter()
+ const { asPath, isReady } = useRouter()
+
const child = Children.only(children)
const childClassName = child.props.className || ''
+ const [className, setClassName] = useState(childClassName)
+
+ useEffect(() => {
+ // Check if the router fields are updated client-side
+ if (isReady) {
+ // Dynamic route will be matched via props.as
+ // Static route will be matched via props.href
+ const linkPathname = new URL(props.as || props.href, location.href)
+ .pathname
+
+ // Using URL().pathname to get rid of query and hash
+ const activePathname = new URL(asPath, location.href).pathname
+
+ const newClassName =
+ linkPathname === activePathname
+ ? `${childClassName} ${activeClassName}`.trim()
+ : childClassName
- // pages/index.js will be matched via props.href
- // pages/about.js will be matched via props.href
- // pages/[slug].js will be matched via props.as
- const className =
- asPath === props.href || asPath === props.as
- ? `${childClassName} ${activeClassName}`.trim()
- : childClassName
+ if (newClassName !== className) {
+ setClassName(newClassName)
+ }
+ }
+ }, [
+ asPath,
+ isReady,
+ props.as,
+ props.href,
+ childClassName,
+ activeClassName,
+ setClassName,
+ className,
+ ])
return (
diff --git a/examples/active-class-name/components/Nav.js b/examples/active-class-name/components/Nav.js
index 2c710bb42468f..921cc15120bfd 100644
--- a/examples/active-class-name/components/Nav.js
+++ b/examples/active-class-name/components/Nav.js
@@ -22,6 +22,11 @@ const Nav = () => (
About
+
+ >
+)
+
+export default News
diff --git a/examples/amp-first/README.md b/examples/amp-first/README.md
index f1734f4feb8d8..4db9d29709f07 100644
--- a/examples/amp-first/README.md
+++ b/examples/amp-first/README.md
@@ -1,6 +1,6 @@
# AMP First Boilerplate ⚡
-This example sets up the boilerplate for an AMP First Site. You can see a live version [here](https://my-next-app.sebastianbenz.vercel.app). The boilerplate includes the following features:
+This example sets up the boilerplate for an AMP First Site. You can see a [live version here](https://my-next-app.sebastianbenz.vercel.app). The boilerplate includes the following features:
- AMP Extension helpers (`amp-state`, `amp-script`, ...)
- AMP Serviceworker integration
diff --git a/examples/amp-first/package.json b/examples/amp-first/package.json
index 3c62fecf57f37..349de02f4d84b 100644
--- a/examples/amp-first/package.json
+++ b/examples/amp-first/package.json
@@ -1,6 +1,5 @@
{
- "name": "amp-first",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -8,8 +7,7 @@
},
"dependencies": {
"next": "latest",
- "react": "^16.10.2",
- "react-dom": "^16.10.2"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/amp-story/package.json b/examples/amp-story/package.json
index d577702ebefaf..349de02f4d84b 100644
--- a/examples/amp-story/package.json
+++ b/examples/amp-story/package.json
@@ -1,6 +1,5 @@
{
- "name": "amp-story",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -8,8 +7,7 @@
},
"dependencies": {
"next": "latest",
- "react": "^16.7.0",
- "react-dom": "^16.7.0"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/amp/package.json b/examples/amp/package.json
index d033597980c09..349de02f4d84b 100644
--- a/examples/amp/package.json
+++ b/examples/amp/package.json
@@ -1,6 +1,5 @@
{
- "name": "amp",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -8,8 +7,7 @@
},
"dependencies": {
"next": "latest",
- "react": "^16.7.0",
- "react-dom": "^16.7.0"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/analyze-bundles/README.md b/examples/analyze-bundles/README.md
index abea34df8353d..02e1673ccd3b8 100644
--- a/examples/analyze-bundles/README.md
+++ b/examples/analyze-bundles/README.md
@@ -1,6 +1,12 @@
# Analyzer Bundles example
-This example shows how to analyze the output bundles using [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/master/packages/next-bundle-analyzer)
+This example shows how to analyze the output bundles using [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/canary/packages/next-bundle-analyzer)
+
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/analyze-bundles)
## Deploy your own
@@ -27,3 +33,11 @@ npm run analyze
# or
yarn analyze
```
+
+Once the build is completed, you can inspect the bundle by running:
+
+```bash
+npm run serve
+# or
+yarn serve
+```
diff --git a/examples/analyze-bundles/package.json b/examples/analyze-bundles/package.json
index a5caa9e790812..a40dca11de1d7 100644
--- a/examples/analyze-bundles/package.json
+++ b/examples/analyze-bundles/package.json
@@ -1,19 +1,21 @@
{
- "name": "analyze-bundles",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
- "analyze": "cross-env ANALYZE=true yarn build"
+ "analyze": "cross-env ANALYZE=true yarn build",
+ "serve": "serve .next/analyze"
},
"dependencies": {
"@next/bundle-analyzer": "^9.1.4",
"cross-env": "^6.0.3",
"faker": "^4.1.0",
"next": "latest",
- "react": "^16.8.0",
- "react-dom": "^16.8.0"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
},
- "license": "MIT"
+ "devDependencies": {
+ "serve": "^11.3.2"
+ }
}
diff --git a/examples/api-routes-apollo-server-and-client-auth/README.md b/examples/api-routes-apollo-server-and-client-auth/README.md
index 68ca3be46917e..6385acf21368a 100644
--- a/examples/api-routes-apollo-server-and-client-auth/README.md
+++ b/examples/api-routes-apollo-server-and-client-auth/README.md
@@ -4,6 +4,12 @@
In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-apollo-server-and-client-auth)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes-apollo-server-and-client-auth/package.json b/examples/api-routes-apollo-server-and-client-auth/package.json
index 7c0ddd6572ff4..448f8254297e2 100644
--- a/examples/api-routes-apollo-server-and-client-auth/package.json
+++ b/examples/api-routes-apollo-server-and-client-auth/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-apollo-server-and-client-auth",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -15,9 +14,8 @@
"graphql": "^14.0.2",
"next": "latest",
"prop-types": "^15.6.2",
- "react": "^16.7.0",
- "react-dom": "^16.7.0",
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
"uuid": "8.1.0"
- },
- "license": "MIT"
+ }
}
diff --git a/examples/api-routes-apollo-server-and-client/README.md b/examples/api-routes-apollo-server-and-client/README.md
index 193136027c813..96c454e0527c6 100644
--- a/examples/api-routes-apollo-server-and-client/README.md
+++ b/examples/api-routes-apollo-server-and-client/README.md
@@ -4,6 +4,12 @@
In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-apollo-server-and-client)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes-apollo-server-and-client/package.json b/examples/api-routes-apollo-server-and-client/package.json
index 43263e3486f16..c1de5dc4ba83f 100644
--- a/examples/api-routes-apollo-server-and-client/package.json
+++ b/examples/api-routes-apollo-server-and-client/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-apollo-server-and-client",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -12,8 +11,7 @@
"graphql": "^14.0.2",
"next": "latest",
"prop-types": "^15.6.2",
- "react": "^16.7.0",
- "react-dom": "^16.7.0"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/api-routes-apollo-server/README.md b/examples/api-routes-apollo-server/README.md
index 320060be87784..5d1066048ddc3 100644
--- a/examples/api-routes-apollo-server/README.md
+++ b/examples/api-routes-apollo-server/README.md
@@ -1,6 +1,12 @@
# Consume local Apollo GraphQL schema to create Static Generation export
-Next.js ships with two forms of pre-rendering: [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) and [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering). This example shows how to perform Static Generation using a local [Apollo GraphQL](https://www.apollographql.com/docs/apollo-server/) schema within [getStaticProps](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) and [getStaticPaths](https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation). The end result is a Next.js application that uses one Apollo GraphQL schema to generate static pages at build time and also serve a GraphQL [API Route](https://nextjs.org/docs/api-routes/introduction) at runtime.
+Next.js ships with two forms of pre-rendering: [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) and [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering). This example shows how to perform Static Generation using a local [Apollo GraphQL](https://www.apollographql.com/docs/apollo-server/) schema within [getStaticProps](https://nextjs.org/docs/basic-features/data-fetching/get-static-props) and [getStaticPaths](https://nextjs.org/docs/basic-features/data-fetching/get-static-paths.md). The end result is a Next.js application that uses one Apollo GraphQL schema to generate static pages at build time and also serve a GraphQL [API Route](https://nextjs.org/docs/api-routes/introduction) at runtime.
+
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-apollo-server)
## Deploy your own
diff --git a/examples/api-routes-apollo-server/package.json b/examples/api-routes-apollo-server/package.json
index c42045d94020b..88af4336ccc68 100644
--- a/examples/api-routes-apollo-server/package.json
+++ b/examples/api-routes-apollo-server/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-apollo-server",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -11,8 +10,7 @@
"apollo-server-micro": "2.13.1",
"graphql": "15.0.0",
"next": "latest",
- "react": "16.13.1",
- "react-dom": "16.13.1"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/api-routes-cors/README.md b/examples/api-routes-cors/README.md
index 5fdee8ab744b8..5ba1b348401fc 100644
--- a/examples/api-routes-cors/README.md
+++ b/examples/api-routes-cors/README.md
@@ -4,6 +4,12 @@ Next.js ships with [API routes](https://nextjs.org/docs/api-routes/introduction)
This example shows how to create an `API` endpoint with [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) headers, using the [cors](https://github.com/expressjs/cors) package.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-cors)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes-cors/package.json b/examples/api-routes-cors/package.json
index 0338eb2648475..bc1300882acc4 100644
--- a/examples/api-routes-cors/package.json
+++ b/examples/api-routes-cors/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-cors",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -9,8 +8,7 @@
"dependencies": {
"cors": "2.8.5",
"next": "latest",
- "react": "^16.13.1",
- "react-dom": "^16.13.1"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2"
+ }
}
diff --git a/examples/api-routes-graphql/README.md b/examples/api-routes-graphql/README.md
index 1a31922c94a90..fe53eb534cb42 100644
--- a/examples/api-routes-graphql/README.md
+++ b/examples/api-routes-graphql/README.md
@@ -1,6 +1,12 @@
# API routes with GraphQL server
-Next.js ships with [API routes](https://github.com/vercel/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows their usage alongside [apollo-server-micro](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-server-micro) to provide simple GraphQL server consumed by Next.js app.
+Next.js ships with [API routes](https://nextjs.org/docs/api-routes/introduction), which provide an easy solution to build your own `API`. This example shows their usage alongside [apollo-server-micro](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-server-micro) to provide simple GraphQL server consumed by Next.js app.
+
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-graphql)
## Deploy your own
diff --git a/examples/api-routes-graphql/package.json b/examples/api-routes-graphql/package.json
index eb2b811a582b6..e4329bea00b67 100644
--- a/examples/api-routes-graphql/package.json
+++ b/examples/api-routes-graphql/package.json
@@ -1,18 +1,17 @@
{
- "name": "api-routes-graphql",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
- "apollo-server-micro": "2.11.0",
- "graphql": "14.6.0",
+ "apollo-server-micro": "^3.0.1",
+ "graphql": "^15.5.1",
+ "micro": "^9.3.4",
"next": "latest",
- "react": "16.13.1",
- "react-dom": "16.13.1",
- "swr": "0.1.18"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
+ "swr": "^0.5.6"
+ }
}
diff --git a/examples/api-routes-graphql/pages/api/graphql.js b/examples/api-routes-graphql/pages/api/graphql.js
index 0dcb066bbcbdc..0a29f3ce88987 100644
--- a/examples/api-routes-graphql/pages/api/graphql.js
+++ b/examples/api-routes-graphql/pages/api/graphql.js
@@ -19,10 +19,31 @@ const resolvers = {
const apolloServer = new ApolloServer({ typeDefs, resolvers })
+const startServer = apolloServer.start()
+
+export default async function handler(req, res) {
+ res.setHeader('Access-Control-Allow-Credentials', 'true')
+ res.setHeader(
+ 'Access-Control-Allow-Origin',
+ 'https://studio.apollographql.com'
+ )
+ res.setHeader(
+ 'Access-Control-Allow-Headers',
+ 'Origin, X-Requested-With, Content-Type, Accept'
+ )
+ if (req.method === 'OPTIONS') {
+ res.end()
+ return false
+ }
+
+ await startServer
+ await apolloServer.createHandler({
+ path: '/api/graphql',
+ })(req, res)
+}
+
export const config = {
api: {
bodyParser: false,
},
}
-
-export default apolloServer.createHandler({ path: '/api/graphql' })
diff --git a/examples/api-routes-middleware/README.md b/examples/api-routes-middleware/README.md
index 7ed15b6ff90a5..44a12e118ddcb 100644
--- a/examples/api-routes-middleware/README.md
+++ b/examples/api-routes-middleware/README.md
@@ -2,6 +2,12 @@
Next.js ships with [API routes](https://github.com/vercel/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows how to implement simple `middleware` to wrap around your `API` endpoints.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-middleware)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes-middleware/package.json b/examples/api-routes-middleware/package.json
index a7e21e6f70abb..ac005757491a9 100644
--- a/examples/api-routes-middleware/package.json
+++ b/examples/api-routes-middleware/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-middleware",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -9,9 +8,8 @@
"dependencies": {
"cookie": "0.4.0",
"next": "latest",
- "react": "^16.8.6",
- "react-dom": "^16.8.6",
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
"swr": "0.1.18"
- },
- "license": "MIT"
+ }
}
diff --git a/examples/api-routes-rate-limit/README.md b/examples/api-routes-rate-limit/README.md
index e3397b2a9fc4e..9328d25846365 100644
--- a/examples/api-routes-rate-limit/README.md
+++ b/examples/api-routes-rate-limit/README.md
@@ -16,6 +16,12 @@ X-RateLimit-Limit: 10
X-RateLimit-Remaining: 0
```
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-rate-limit)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
@@ -27,9 +33,9 @@ Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_mediu
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
-npx create-next-app --example api-routes api-routes-rate-limit
+npx create-next-app --example api-routes-rate-limit api-routes-rate-limit-app
# or
-yarn create next-app --example api-routes api-routes-rate-limit
+yarn create next-app --example api-routes-rate-limit api-routes-rate-limit-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
diff --git a/examples/api-routes-rate-limit/package.json b/examples/api-routes-rate-limit/package.json
index b43827f60cb63..61b3034ed6410 100644
--- a/examples/api-routes-rate-limit/package.json
+++ b/examples/api-routes-rate-limit/package.json
@@ -1,6 +1,4 @@
{
- "name": "nextjs-rate-limit",
- "version": "0.0.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -9,9 +7,9 @@
},
"dependencies": {
"lru-cache": "^6.0.0",
- "next": "10.0.3",
- "react": "17.0.1",
- "react-dom": "17.0.1",
+ "next": "latest",
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
"uuid": "^8.3.1"
}
}
diff --git a/examples/api-routes-rest/README.md b/examples/api-routes-rest/README.md
index 1136ed9d7efbb..c8f176bd5e2c1 100644
--- a/examples/api-routes-rest/README.md
+++ b/examples/api-routes-rest/README.md
@@ -2,6 +2,12 @@
Next.js ships with [API routes](https://github.com/vercel/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows how it can be used to create your [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) `API`.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes-rest)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes-rest/package.json b/examples/api-routes-rest/package.json
index 883f3d7720f03..4b23e0ce0f192 100644
--- a/examples/api-routes-rest/package.json
+++ b/examples/api-routes-rest/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes-rest",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -8,9 +7,8 @@
},
"dependencies": {
"next": "latest",
- "react": "^16.8.6",
- "react-dom": "^16.8.6",
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
"swr": "^0.1.18"
- },
- "license": "MIT"
+ }
}
diff --git a/examples/api-routes/README.md b/examples/api-routes/README.md
index 334bf15feedb0..87e9fa6321f9d 100644
--- a/examples/api-routes/README.md
+++ b/examples/api-routes/README.md
@@ -2,6 +2,12 @@
Next.js ships with [API routes](https://nextjs.org/docs/api-routes/introduction) which provides an easy solution to build your own `API`. This example shows how to create multiple `API` endpoints with serverless functions, which can execute independently.
+## Preview
+
+Preview the example live on [StackBlitz](http://stackblitz.com/):
+
+[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/api-routes)
+
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
diff --git a/examples/api-routes/data.js b/examples/api-routes/data.js
index ce2acde5041c5..f57a9d0786fdb 100644
--- a/examples/api-routes/data.js
+++ b/examples/api-routes/data.js
@@ -61,7 +61,7 @@ export const people = [
},
{
id: '7',
- name: 'Beru Whitesun lars',
+ name: 'Beru Whitesun Lars',
height: '165',
mass: '75',
hair_color: 'brown',
diff --git a/examples/api-routes/package.json b/examples/api-routes/package.json
index f6156d9d3fa1a..56e1c8107ad3f 100644
--- a/examples/api-routes/package.json
+++ b/examples/api-routes/package.json
@@ -1,6 +1,5 @@
{
- "name": "api-routes",
- "version": "1.0.0",
+ "private": true,
"scripts": {
"dev": "next",
"build": "next build",
@@ -8,9 +7,8 @@
},
"dependencies": {
"next": "latest",
- "react": "^16.8.6",
- "react-dom": "^16.8.6",
- "swr": "0.1.18"
- },
- "license": "MIT"
+ "react": "^17.0.2",
+ "react-dom": "^17.0.2",
+ "swr": "^1.0.1"
+ }
}
diff --git a/examples/auth-with-stytch/.env.template b/examples/auth-with-stytch/.env.template
new file mode 100644
index 0000000000000..4aed8e797e320
--- /dev/null
+++ b/examples/auth-with-stytch/.env.template
@@ -0,0 +1,8 @@
+# The two iron-session values may be left as-is while testing out this example app.
+IRON_SESSION_COOKIE_NAME="stytch_next_example_cookie"
+IRON_SESSION_PASSWORD="complex_password_at_least_32_characters_long"
+# The below values may be found in your Stytch Dashboard: https://stytch.com/dashboard/api-keys
+STYTCH_PROJECT_ENV=test
+STYTCH_PROJECT_ID="YOUR_STYTCH_PROJECT_ID"
+STYTCH_SECRET="YOUR_STYTCH_SECRET"
+NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN="YOUR_STYTCH_PUBLIC_TOKEN"
diff --git a/examples/with-ant-design-mobile/.gitignore b/examples/auth-with-stytch/.gitignore
similarity index 100%
rename from examples/with-ant-design-mobile/.gitignore
rename to examples/auth-with-stytch/.gitignore
diff --git a/examples/auth-with-stytch/README.md b/examples/auth-with-stytch/README.md
new file mode 100644
index 0000000000000..7d787948b5236
--- /dev/null
+++ b/examples/auth-with-stytch/README.md
@@ -0,0 +1,68 @@
+# Stytch + Next.js example app on Vercel
+
+This is a [Stytch](https://stytch.com) + [Next.js](https://nextjs.org/) project that showcases how to enable elegant authentication in your applicaiton.
+
+
+
+In this repo, we have two sample auth flows:
+
+- SDK integration: This flow uses Stytch's React component to create a login and sign-up flow using [Email Magic Links](https://stytch.com/docs/api/send-by-email).
+- API integration: This flow uses a custom UI with Stytch's backend API for [Onetime Passcodes(OTP) via SMS](https://stytch.com/docs/api/sms-otp-overview) authentication.
+
+Both flows use Stytch's [Node client library](https://github.com/stytchauth/stytch-node) and [`iron-session`](https://github.com/vvo/next-iron-session) for session management.
+
+**Note:** By default this example app enables three of our OAuth providers, Google, Microsoft, and Apple. If you haven't set up these OAuth providers in your [Dashboard](https://stytch.com/dashboard/oauth), you'll receive a redirect error when you attempt to login via those providers. You may remove all OAuth methods by removing `SDKProductTypes.oauth` from the `products` array in [pages/index.tsx](pages/index.tsx) or adjust which ones are displayed by via `oauthOptions.providers` in the same file. More detail on working with OAuth providers in our SDK may be found in our [Docs](https://stytch.com/docs/javascript-sdk#javascript-sdk/oauth).
+
+# Deploy on Vercel
+
+## Setting up Stytch
+
+The first step is to configure the appropriate redirect URLs for your project. You'll set these magic link redirect URLs in the [Redirect URLs](https://stytch.com/dashboard/redirect-urls) section of your Dashboard. Add `https://*.vercel.app:3000` as both a login and sign-up redirect URL.
+
+## Running the example app
+
+Now just click the deploy button below! Once you're signed in to your Vercel account, you'll be guided through how to get up and running quickly. Check out [.env.template](/.env.template) for pointers on filling in the appropriate environment variables for this step.
+
+[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Fblob%2Fcanary%2Fexamples%2Fauth-with-stytch%2F&env=STYTCH_PROJECT_ENV,STYTCH_PROJECT_ID,STYTCH_SECRET,NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN,IRON_SESSION_PASSWORD,IRON_SESSION_COOKIE_NAME&envDescription=All%20variables%20here%20need%20values%2C%20see%20the%20following%20link%20for%20pointers%20on%20how%20to%20feel%20these%20out.&envLink=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Fblob%2Fcanary%2Fexamples%2Fauth-with-stytch%2F.env.template&project-name=stytch-nextjs-vercel&repo-name=stytch-nextjs-vercel&demo-title=Stytch%20on%20Next.js%20with%20Vercel&demo-description=Next.js%20example%20app%20using%20Stytch%20authentication&demo-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Fblob%2Fcanary%2Fexamples%2Fauth-with-stytch&demo-image=https%3A%2F%2Fstytch.com%2Flogo-preview.png)
+
+# Running locally via `vercel dev`
+
+## Setting up Stytch
+
+After signing up for Stytch, you'll need your Project's `project_id`, `secret`, and `public_token`. You can find these in the [API keys tab](https://stytch.com/dashboard/api-keys).
+
+Once you've gathered these values, add them to a new .env.local file.
+Example:
+
+```bash
+cp .env.template .env.local
+# Replace your keys in new .env.local file
+```
+
+Next we'll configure the appropriate redirect URLs for your project, you'll set these magic link URLs for your project in the [Redirect URLs](https://stytch.com/dashboard/redirect-urls) section of your Dashboard. Add `http://localhost:3000/api/authenticate_magic_link` as both a login and sign-up redirect URL.
+
+## Running the example app
+
+Install dependencies by running
+
+```bash
+npm install
+# or
+yarn install
+```
+
+You can then run a development server using:
+
+```bash
+vercel dev
+```
+
+Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
+
+## Documentation
+
+Learn more about some of Stytch's products used in this example app:
+
+- [Stytch React](https://www.npmjs.com/package/@stytch/stytch-react)
+- [Stytch's node client library](https://www.npmjs.com/package/stytch)
+- [iron-session](https://github.com/vvo/next-iron-session)
diff --git a/examples/auth-with-stytch/components/LoginEntryPoint.tsx b/examples/auth-with-stytch/components/LoginEntryPoint.tsx
new file mode 100644
index 0000000000000..a8bf3562dca25
--- /dev/null
+++ b/examples/auth-with-stytch/components/LoginEntryPoint.tsx
@@ -0,0 +1,35 @@
+import React from 'react'
+import styles from '../styles/Home.module.css'
+import { LoginMethod } from '../lib/types'
+import StytchContainer from './StytchContainer'
+
+type Props = {
+ setLoginMethod: (loginMethod: LoginMethod) => void
+}
+
+const LoginEntryPoint = (props: Props) => {
+ const { setLoginMethod } = props
+ return (
+
+
Hello Vercel!
+
+ This example app demonstrates how you can integrate with Stytch using
+ Next.js and deploy on Vercel. Now, let’s get started!
+