Unverified Commit 82596124 authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

Add cors example and update API routes docs (#12390)

parent 8f3931a0
......@@ -4,6 +4,14 @@ description: API Routes provide built-in middlewares that parse the incoming r
# API Middlewares
<details open>
<summary><b>Examples</b></summary>
<ul>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-middleware">API Routes with middleware</a></li>
<li><a href="https://github.com/zeit/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:
- `req.cookies` - An object containing the cookies sent by the request. Defaults to `{}`
......@@ -96,3 +104,5 @@ async function handler(req, res) {
export default handler
```
> Go to the [API Routes with CORS](https://github.com/zeit/next.js/tree/canary/examples/api-routes-cors) example to see the finished app
......@@ -4,6 +4,13 @@ description: You can add the dynamic routes used for pages to API Routes too. Le
# Dynamic API Routes
<details open>
<summary><b>Examples</b></summary>
<ul>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes">Basic API Routes</a></li>
</ul>
</details>
API routes support [dynamic routes](/docs/routing/dynamic-routes.md), and follow the same file naming rules used for `pages`.
For example, the API route `pages/api/post/[pid].js` has the following code:
......@@ -79,3 +86,14 @@ Now, a request to `/api/post/a/b/c` will respond with the text: `Post: a, b, c`.
- `pages/api/post/create.js` - Will match `/api/post/create`
- `pages/api/post/[pid].js` - Will match `/api/post/1`, `/api/post/abc`, etc. But not `/api/post/create`
- `pages/api/post/[...slug].js` - Will match `/api/post/1/2`, `/api/post/a/b/c`, etc. But not `/api/post/create`, `/api/post/abc`
## Related
For more information on what to do next, we recommend the following sections:
<div class="card">
<a href="/docs/routing/dynamic-routes.md">
<b>Dynamic Routes:</b>
<small>Learn more about the built-in dynamic routes.</small>
</a>
</div>
......@@ -4,13 +4,14 @@ description: Next.js supports API Routes, which allow you to build your API with
# API Routes
<details>
<details open>
<summary><b>Examples</b></summary>
<ul>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes">Basic API Routes</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-middleware">API Routes with middleware</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-graphql">API Routes with GraphQL</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-rest">API Routes with REST</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-cors">API Routes with CORS</a></li>
</ul>
</details>
......
......@@ -4,6 +4,14 @@ description: API Routes include a set of Express.js-like methods for the respons
# Response Helpers
<details open>
<summary><b>Examples</b></summary>
<ul>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes">Basic API Routes</a></li>
<li><a href="https://github.com/zeit/next.js/tree/canary/examples/api-routes-rest">API Routes with REST</a></li>
</ul>
</details>
The response (`res`) includes a set of Express.js-like methods to improve the developer experience and increase the speed of creating new API endpoints, take a look at the following example:
```js
......
# API Routes Example with CORS
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 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.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/api-routes-cors)
## How to use
Execute [`create-next-app`](https://github.com/zeit/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
npm init next-app --example api-routes-cors api-routes-cors-app
# or
yarn create next-app --example api-routes-cors api-routes-cors-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
{
"name": "api-routes-cors",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"cors": "2.8.5",
"next": "latest",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"license": "ISC"
}
import Cors from 'cors'
import initMiddleware from '../../lib/init-middleware'
// Initialize the cors middleware
const cors = initMiddleware(
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
Cors({
// Only allow requests with GET, POST and OPTIONS
methods: ['GET', 'POST', 'OPTIONS'],
})
)
export default async function handler(req, res) {
// Run cors
await cors(req, res)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
export default function Index() {
return (
<p>
To test the CORS route, open the console in a new tab on a different
domain and make a POST / GET / OPTIONS request to <b>/api/cors</b>. Using
a different method from those mentioned will be blocked by CORS
</p>
)
}
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