Unverified Commit 5d93753b authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

API Routes Request Helpers docs. (#39407)

Renames Middleware to Request Helpers to be both more accurate and also less confusing since Middleware is a separate feature of Next.js now.
parent 71f5f258
...@@ -8,7 +8,6 @@ description: Next.js supports API Routes, which allow you to build your API with ...@@ -8,7 +8,6 @@ description: Next.js supports API Routes, which allow you to build your API with
<summary><b>Examples</b></summary> <summary><b>Examples</b></summary>
<ul> <ul>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes">Basic API Routes</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes">Basic API Routes</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware">API Routes with middleware</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql">API Routes with GraphQL</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql">API Routes with GraphQL</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-rest">API Routes with REST</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-rest">API Routes with REST</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors">API Routes with CORS</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors">API Routes with CORS</a></li>
...@@ -31,7 +30,7 @@ export default function handler(req, res) { ...@@ -31,7 +30,7 @@ export default function handler(req, res) {
For an API route to work, you need to export a function as default (a.k.a **request handler**), which then receives the following parameters: For an API route to work, you need to export a function as default (a.k.a **request handler**), which then receives the following parameters:
- `req`: An instance of [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage), plus some [pre-built middlewares](/docs/api-routes/api-middlewares.md) - `req`: An instance of [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage), plus some [pre-built middlewares](/docs/api-routes/request-helpers.md)
- `res`: An instance of [http.ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse), plus some [helper functions](/docs/api-routes/response-helpers.md) - `res`: An instance of [http.ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse), plus some [helper functions](/docs/api-routes/response-helpers.md)
To handle different HTTP methods in an API route, you can use `req.method` in your request handler, like so: To handle different HTTP methods in an API route, you can use `req.method` in your request handler, like so:
...@@ -57,7 +56,7 @@ For new projects, you can build your entire API with API Routes. If you have an ...@@ -57,7 +56,7 @@ For new projects, you can build your entire API with API Routes. If you have an
## Caveats ## Caveats
- API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS middleware](/docs/api-routes/api-middlewares.md#connectexpress-middleware-support). - API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS request helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors).
- API Routes can't be used with [`next export`](/docs/advanced-features/static-html-export.md) - API Routes can't be used with [`next export`](/docs/advanced-features/static-html-export.md)
## Related ## Related
...@@ -65,9 +64,9 @@ For new projects, you can build your entire API with API Routes. If you have an ...@@ -65,9 +64,9 @@ For new projects, you can build your entire API with API Routes. If you have an
For more information on what to do next, we recommend the following sections: For more information on what to do next, we recommend the following sections:
<div class="card"> <div class="card">
<a href="/docs/api-routes/api-middlewares.md"> <a href="/docs/api-routes/request-helpers.md">
<b>API Middlewares:</b> <b>API Routes Request Helpers:</b>
<small>learn about the built-in middlewares for the request.</small> <small>learn about the built-in helpers for the request.</small>
</a> </a>
</div> </div>
......
--- ---
description: API Routes provide built-in middlewares that parse the incoming request. Learn more about them here. description: API Routes provide built-in request helpers that parse the incoming request. Learn more about them here.
--- ---
# API Middlewares # API Routes Request Helpers
<details open> <details open>
<summary><b>Examples</b></summary> <summary><b>Examples</b></summary>
<ul> <ul>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware">API Routes with middleware</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware">API Routes Request Helpers</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors">API Routes with CORS</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors">API Routes with CORS</a></li>
</ul> </ul>
</details> </details>
API routes provide built in middlewares which parse the incoming request (`req`). Those middlewares are: API Routes provide built-in request helpers which parse the incoming request (`req`):
- `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 `{}`
...@@ -20,7 +20,7 @@ API routes provide built in middlewares which parse the incoming reques ...@@ -20,7 +20,7 @@ API routes provide built in middlewares which parse the incoming reques
## Custom config ## Custom config
Every API route can export a `config` object to change the default configs, which are the following: Every API Route can export a `config` object to change the default configuration, which is the following:
```js ```js
export const config = { export const config = {
...@@ -32,7 +32,7 @@ export const config = { ...@@ -32,7 +32,7 @@ export const config = {
} }
``` ```
The `api` object includes all configs available for API routes. The `api` object includes all config options available for API Routes.
`bodyParser` is automatically enabled. If you want to consume the body as a `Stream` or with [`raw-body`](https://www.npmjs.com/package/raw-body), you can set this to `false`. `bodyParser` is automatically enabled. If you want to consume the body as a `Stream` or with [`raw-body`](https://www.npmjs.com/package/raw-body), you can set this to `false`.
...@@ -68,7 +68,7 @@ export const config = { ...@@ -68,7 +68,7 @@ export const config = {
} }
``` ```
`responseLimit` is automatically enabled, warning when an API routes' response body is over 4MB. `responseLimit` is automatically enabled, warning when an API Routes' response body is over 4MB.
If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false`. If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false`.
...@@ -91,57 +91,6 @@ export const config = { ...@@ -91,57 +91,6 @@ export const config = {
} }
``` ```
## Connect/Express middleware support
You can also use [Connect](https://github.com/senchalabs/connect) compatible middleware.
For example, [configuring CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for your API endpoint can be done leveraging the [cors](https://www.npmjs.com/package/cors) package.
First, install `cors`:
```bash
npm i cors
# or
yarn add cors
```
Now, let's add `cors` to the API route:
```js
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
export default handler
```
> Go to the [API Routes with CORS](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors) example to see the finished app.
## Extending the `req`/`res` objects with TypeScript ## Extending the `req`/`res` objects with TypeScript
For better type-safety, it is not recommended to extend the `req` and `res` objects. Instead, use functions to work with them: For better type-safety, it is not recommended to extend the `req` and `res` objects. Instead, use functions to work with them:
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
description: API Routes include a set of Express.js-like methods for the response to help you creating new API endpoints. Learn how it works here. description: API Routes include a set of Express.js-like methods for the response to help you creating new API endpoints. Learn how it works here.
--- ---
# Response Helpers # API Routes Response Helpers
The [Server Response object](https://nodejs.org/api/http.html#http_class_http_serverresponse), (often abbreviated as `res`) includes a set of Express.js-like helper methods to improve the developer experience and increase the speed of creating new API endpoints. The [Server Response object](https://nodejs.org/api/http.html#http_class_http_serverresponse), (often abbreviated as `res`) includes a set of Express.js-like helper methods to improve the developer experience and increase the speed of creating new API endpoints.
......
...@@ -127,6 +127,13 @@ ...@@ -127,6 +127,13 @@
{ {
"title": "API Routes", "title": "API Routes",
"routes": [ "routes": [
{
"path": "/docs/api-routes/api-middlewares",
"redirect": {
"destination": "/docs/api-routes/request-helpers",
"permanent": true
}
},
{ {
"title": "Introduction", "title": "Introduction",
"path": "/docs/api-routes/introduction.md" "path": "/docs/api-routes/introduction.md"
...@@ -137,7 +144,7 @@ ...@@ -137,7 +144,7 @@
}, },
{ {
"title": "API Middlewares", "title": "API Middlewares",
"path": "/docs/api-routes/api-middlewares.md" "path": "/docs/api-routes/request-helpers.md"
}, },
{ {
"title": "Response Helpers", "title": "Response Helpers",
......
...@@ -115,5 +115,5 @@ export const config = {} ...@@ -115,5 +115,5 @@ export const config = {}
### Useful Links ### Useful Links
- [Enabling AMP Support](https://nextjs.org/docs/advanced-features/amp-support/introduction) - [Enabling AMP Support](https://nextjs.org/docs/advanced-features/amp-support/introduction)
- [API Middlewares](https://nextjs.org/docs/api-routes/api-middlewares) - [API Routes Request Helpers](https://nextjs.org/docs/api-routes/request-helpers)
- [Switchable Runtime](https://nextjs.org/docs/advanced-features/react-18/switchable-runtime) - [Switchable Runtime](https://nextjs.org/docs/advanced-features/react-18/switchable-runtime)
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