Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Routes Request Helpers docs. #39407

Merged
merged 3 commits into from Aug 9, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 5 additions & 6 deletions docs/api-routes/introduction.md
Expand Up @@ -8,7 +8,6 @@ description: Next.js supports API Routes, which allow you to build your API with
<summary><b>Examples</b></summary>
<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-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-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>
Expand All @@ -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:

- `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)

To handle different HTTP methods in an API route, you can use `req.method` in your request handler, like so:
Expand All @@ -57,17 +56,17 @@ For new projects, you can build your entire API with API Routes. If you have an

## 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)

## Related

For more information on what to do next, we recommend the following sections:

<div class="card">
<a href="/docs/api-routes/api-middlewares.md">
<b>API Middlewares:</b>
<small>learn about the built-in middlewares for the request.</small>
<a href="/docs/api-routes/request-helpers.md">
<b>API Routes Request Helpers:</b>
<small>learn about the built-in helpers for the request.</small>
</a>
</div>

Expand Down
@@ -1,26 +1,26 @@
---
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>
<summary><b>Examples</b></summary>
<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>
</ul>
</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.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 was sent

## 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
export const config = {
Expand All @@ -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`.

Expand Down Expand Up @@ -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`.

Expand All @@ -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

For better type-safety, it is not recommended to extend the `req` and `res` objects. Instead, use functions to work with them:
Expand Down
2 changes: 1 addition & 1 deletion docs/api-routes/response-helpers.md
Expand Up @@ -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.
---

# 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.

Expand Down
9 changes: 8 additions & 1 deletion docs/manifest.json
Expand Up @@ -127,6 +127,13 @@
{
"title": "API Routes",
"routes": [
{
"path": "/docs/api-routes/api-middlewares",
"redirect": {
"destination": "/docs/api-routes/request-helpers",
"permanent": true
}
},
{
"title": "Introduction",
"path": "/docs/api-routes/introduction.md"
Expand All @@ -137,7 +144,7 @@
},
{
"title": "API Middlewares",
"path": "/docs/api-routes/api-middlewares.md"
leerob marked this conversation as resolved.
Show resolved Hide resolved
"path": "/docs/api-routes/request-helpers.md"
},
{
"title": "Response Helpers",
Expand Down
2 changes: 1 addition & 1 deletion errors/invalid-page-config.md
Expand Up @@ -115,5 +115,5 @@ export const config = {}
### Useful Links

- [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)