Unverified Commit ce8956ae authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Miscellaneous doc updates (#7831)

* Runtime config is not compatible w/ prerendering

Closes https://github.com/zeit/next.js/issues/7827

* Add req and res types

* Document using CORS
Closes https://github.com/zeit/next.js/issues/7805

* Add docs about GIP and Prerendering

Closes https://github.com/zeit/next.js/issues/7786

* set => provided

* Note by default

* Ref CORS doc

* Specify empty object
parent aac4e21d
...@@ -309,6 +309,10 @@ For example, `/post/abc?pid=bcd` will have the `query` object: `{ pid: 'abc' }`. ...@@ -309,6 +309,10 @@ For example, `/post/abc?pid=bcd` will have the `query` object: `{ pid: 'abc' }`.
> **Note**: Predefined routes take precedence over dynamic routes. > **Note**: Predefined routes take precedence over dynamic routes.
> For example, if you have `pages/post/[pid].js` and `pages/post/create.js`, the route `/post/create` will be matched by `pages/post/create.js` instead of the dynamic route (`[pid]`). > For example, if you have `pages/post/[pid].js` and `pages/post/create.js`, the route `/post/create` will be matched by `pages/post/create.js` instead of the dynamic route (`[pid]`).
> **Note**: Pages that are statically optimized by [automatic prerendering](#automatic-prerendering) will be hydrated without their route parameters provided (`query` will be empty, i.e. `{}`).
> After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object.
> If your application cannot tolerate this behavior, you can opt-out of static optimization by capturing the query parameter in `getInitialProps`.
### Populating `<head>` ### Populating `<head>`
<details> <details>
...@@ -1049,7 +1053,13 @@ export default withRouter(MyLink) ...@@ -1049,7 +1053,13 @@ export default withRouter(MyLink)
</ul> </ul>
</details> </details>
API routes provides a straightforward solution to build your `API` with `Next.js`. Start by creating the `api` folder inside the `pages` folder. Every file inside `./pages/api` is mapped to `/api/*`, for example `./pages/api/posts.js` will be mapped to `/api/posts`. Here's how an `api` route looks like: API routes provides a straightforward solution to build your **API** with Next.js.
Start by creating the `api/` folder inside the `./pages/` folder.
Every file inside `./pages/api` is mapped to `/api/*`.
For example, `./pages/api/posts.js` is mapped to the route `/api/posts`.
Here's an example API route file:
```js ```js
export default (req, res) => { export default (req, res) => {
...@@ -1059,7 +1069,15 @@ export default (req, res) => { ...@@ -1059,7 +1069,15 @@ export default (req, res) => {
} }
``` ```
**Note: API routes are compiled just for the server, there's no overhead added to the client bundle and every route is its own separated bundle.** - `req` refers to [NextApiRequest](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L143-L158) which extends [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
- `res` refers to [NextApiResponse](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L168-L178) which extends [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
> **Note**: API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), so they'll be **same-origin only** by default.
> You can customize this behavior by wrapping your export with CORS middleware.
> We provide an [example of this below](#api-middlewares).
API Routes do not increase your client-side bundle size. They are server-side only bundles.
#### Dynamic routes support #### Dynamic routes support
...@@ -1079,15 +1097,22 @@ export default (req, res) => { ...@@ -1079,15 +1097,22 @@ export default (req, res) => {
#### API Middlewares #### API Middlewares
API routes provides built in `middlewares` which parse the incoming `req`. Those middlewares are: API routes provides built in middlewares which parse the incoming `req`.
Those middlewares are:
- `req.cookies` - an object containing the cookies sent by the request. Defaults to `{}` - `req.cookies` - an object containing the cookies sent by the request. Defaults to `{}`
- `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}` - `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}`
- `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent - `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent
Body parsing is always on by default. However, if you don't want to parse body or you want to consume the body as `stream`. It's possible to opt-out from it. To disable body parsing you need to provide `config` option bellow inside page. Body parsing is enabled by default.
You can opt-out of automatic body parsing if you need to consume it as a `Stream`:
```js ```js
// ./pages/api/my-endpoint.js
export default (req, res) => {
// ...
}
export const config = { export const config = {
api: { api: {
bodyParser: false, bodyParser: false,
...@@ -1095,13 +1120,41 @@ export const config = { ...@@ -1095,13 +1120,41 @@ export const config = {
} }
``` ```
As an added bonus, you can also use any [Micro](https://github.com/zeit/micro) compatible [middleware](https://github.com/amio/awesome-micro)!
For example, [configuring CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for your API endpoint can be done leveraging `micro-cors`.
First, install `micro-cors`:
```bash
npm i micro-cors
# or
yarn add micro-cors
```
Then, import `micro-cors` and [configure it](https://github.com/possibilities/micro-cors#readme). Finally, wrap your exported function in the middleware:
```js
import Cors from 'micro-cors'
const cors = Cors({
allowedMethods: ['GET', 'HEAD'],
})
function Endpoint(req, res) {
res.json({ message: 'Hello Everyone!' })
}
export default cors(Endpoint)
```
#### Helper Functions #### Helper Functions
We're providing a set of `Express.js`-like methods to improve the developer experience and increase the speed of creating new `API` endpoints: We're providing a set of Express.js-like methods to improve the developer experience and increase the speed of creating new API endpoints:
```js ```js
export default (req, res) => { export default (req, res) => {
res.status(200).json({ name: 'Nextjs' }) res.status(200).json({ name: 'Next.js' })
} }
``` ```
...@@ -1887,7 +1940,7 @@ AuthMethod({ key: process.env.CUSTOM_KEY, secret: process.env.CUSTOM_SECRET }) ...@@ -1887,7 +1940,7 @@ AuthMethod({ key: process.env.CUSTOM_KEY, secret: process.env.CUSTOM_SECRET })
> **Warning:** Note that this option is not available when using `target: 'serverless'` > **Warning:** Note that this option is not available when using `target: 'serverless'`
> **Warning:** Generally you want to use build-time configuration to provide your configuration. > **Warning:** Generally you want to use build-time configuration to provide your configuration.
> The reason for this is that runtime configuration adds rendering / initialization overhead. > The reason for this is that runtime configuration adds rendering / initialization overhead and is **incompatible with [automatic prerendering](#automatic-prerendering)**.
The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`. The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`.
...@@ -1895,6 +1948,9 @@ Place any server-only runtime config under a `serverRuntimeConfig` property. ...@@ -1895,6 +1948,9 @@ Place any server-only runtime config under a `serverRuntimeConfig` property.
Anything accessible to both client and server-side code should be under `publicRuntimeConfig`. Anything accessible to both client and server-side code should be under `publicRuntimeConfig`.
> **Note**: A page that relies on `publicRuntimeConfig` **must** use `getInitialProps` to opt-out of [automatic prerendering](#automatic-prerendering).
> You can also de-optimize your entire application by creating a [Custom `<App>`](#custom-app) with `getInitialProps`.
```js ```js
// next.config.js // next.config.js
module.exports = { module.exports = {
...@@ -1979,6 +2035,7 @@ The result is an _ultra fast_ loading experience for your users. ...@@ -1979,6 +2035,7 @@ The result is an _ultra fast_ loading experience for your users.
`next build` will emit `.html` files for statically optimized pages. `next build` will emit `.html` files for statically optimized pages.
The result will be a file named `.next/server/static/${BUILD_ID}/about.html` instead of `.next/server/static/${BUILD_ID}/about.js`. The result will be a file named `.next/server/static/${BUILD_ID}/about.html` instead of `.next/server/static/${BUILD_ID}/about.js`.
This behavior is similar for `target: 'serverless'`.
The built-in Next.js server (`next start`) and programmatic API (`app.getRequestHandler()`) both support this build output transparently. The built-in Next.js server (`next start`) and programmatic API (`app.getRequestHandler()`) both support this build output transparently.
There is no configuration or special handling required. There is no configuration or special handling required.
...@@ -2016,9 +2073,12 @@ Note: we recommend putting `.next`, or your [custom dist folder](https://github. ...@@ -2016,9 +2073,12 @@ Note: we recommend putting `.next`, or your [custom dist folder](https://github.
</ul> </ul>
</details> </details>
Serverless deployment dramatically improves reliability and scalability by splitting your application into smaller parts (also called [**lambdas**](https://zeit.co/docs/v2/deployments/concepts/lambdas/)). In the case of Next.js, each page in the `pages` directory becomes a serverless lambda. Serverless deployment dramatically improves reliability and scalability by splitting your application into smaller parts (also called [**lambdas**](https://zeit.co/docs/v2/deployments/concepts/lambdas/)).
In the case of Next.js, each page in the `pages` directory becomes a serverless lambda.
There are [a number of benefits](https://zeit.co/blog/serverless-express-js-lambdas-with-now-2#benefits-of-serverless-express) to serverless. The referenced link talks about some of them in the context of Express, but the principles apply universally: serverless allows for distributed points of failure, infinite scalability, and is incredibly affordable with a "pay for what you use" model. There are [a number of benefits](https://zeit.co/blog/serverless-express-js-lambdas-with-now-2#benefits-of-serverless-express) to serverless.
The referenced link talks about some of them in the context of Express, but the principles apply universally:
serverless allows for distributed points of failure, infinite scalability, and is incredibly affordable with a "pay for what you use" model.
To enable **serverless mode** in Next.js, add the `serverless` build `target` in `next.config.js`: To enable **serverless mode** in Next.js, add the `serverless` build `target` in `next.config.js`:
...@@ -2029,10 +2089,12 @@ module.exports = { ...@@ -2029,10 +2089,12 @@ module.exports = {
} }
``` ```
The `serverless` target will output a single lambda per page. This file is completely standalone and doesn't require any dependencies to run: The `serverless` target will output a single lambda or [HTML file](#automatic-prerendering) per page.
This file is completely standalone and doesn't require any dependencies to run:
- `pages/index.js` => `.next/serverless/pages/index.js` - `pages/index.js` => `.next/serverless/pages/index.js`
- `pages/about.js` => `.next/serverless/pages/about.js` - `pages/about.js` => `.next/serverless/pages/about.js`
- `pages/blog.js` => `.next/serverless/pages/blog.html`
The signature of the Next.js Serverless function is similar to the Node.js HTTP server callback: The signature of the Next.js Serverless function is similar to the Node.js HTTP server callback:
...@@ -2044,6 +2106,9 @@ export function render(req: http.IncomingMessage, res: http.ServerResponse) => v ...@@ -2044,6 +2106,9 @@ export function render(req: http.IncomingMessage, res: http.ServerResponse) => v
- [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) - [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
- `void` refers to the function not having a return value and is equivalent to JavaScript's `undefined`. Calling the function will finish the request. - `void` refers to the function not having a return value and is equivalent to JavaScript's `undefined`. Calling the function will finish the request.
The static HTML files are ready to be served as-is.
You can read more about this feature, including how to opt-out, in the [Automatic Prerendering section](#automatic-prerendering).
Using the serverless target, you can deploy Next.js to [ZEIT Now](https://zeit.co/now) with all of the benefits and added ease of control like for example; [custom routes](https://zeit.co/guides/custom-next-js-server-to-routes/) and caching headers. See the [ZEIT Guide for Deploying Next.js with Now](https://zeit.co/guides/deploying-nextjs-with-now/) for more information. Using the serverless target, you can deploy Next.js to [ZEIT Now](https://zeit.co/now) with all of the benefits and added ease of control like for example; [custom routes](https://zeit.co/guides/custom-next-js-server-to-routes/) and caching headers. See the [ZEIT Guide for Deploying Next.js with Now](https://zeit.co/guides/deploying-nextjs-with-now/) for more information.
#### One Level Lower #### One Level Lower
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment