Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions examples/api-routes-rest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# API routes with REST

## How to use

### Using `create-next-app`

Execute [`create-next-app`](https://www.npmjs.com/package/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:

```bash
npx create-next-app --example api-routes-rest api-routes-rest-app
# or
yarn create next-app --example api-routes-rest api-routes-rest-app
```

### Deploy to Now

Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))

```bash
now
```

## The idea behind the example

Next.js ships with [API routes](https://github.com/zeit/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.
16 changes: 16 additions & 0 deletions examples/api-routes-rest/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "api-routes-rest",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
20 changes: 20 additions & 0 deletions examples/api-routes-rest/pages/api/user/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default (req, res) => {
const {
query: { id, name },
method
} = req

switch (method) {
case 'GET':
// Get data from your database
res.status(200).json({ id, name: `User ${id}` })
break
case 'PUT':
// Update or create data in your database
res.status(200).json({ id, name: name || `User ${id}` })
break
default:
res.setHeader('Allow', ['GET', 'PUT'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
13 changes: 13 additions & 0 deletions examples/api-routes-rest/pages/api/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Fake users data
const users = [
{
id: 1
},
{ id: 2 },
{ id: 3 }
]

export default (req, res) => {
// Get data from your database
res.status(200).json(users)
}
23 changes: 23 additions & 0 deletions examples/api-routes-rest/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import fetch from 'isomorphic-unfetch'
import Link from 'next/link'

const Index = ({ users }) => (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href='/user/[id]' as={`/user/${user.id}`}>
<a>{`User ${user.id}`}</a>
</Link>
</li>
))}
</ul>
)

Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/users')
const users = await response.json()

return { users }
}

export default Index
12 changes: 12 additions & 0 deletions examples/api-routes-rest/pages/user/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import fetch from 'isomorphic-unfetch'

const User = ({ user }) => <div>{user.name}</div>

User.getInitialProps = async ({ query: { id } }, res) => {
const response = await fetch(`http://localhost:3000/api/user/${id}`)
const user = await response.json()

return { user }
}

export default User
13 changes: 13 additions & 0 deletions packages/next/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,7 @@ export default withRouter(MyLink)
<li><a href="/examples/api-routes-micro">API routes with micro</a></li>
<li><a href="/examples/api-routes-middleware">API routes with middleware</a></li>
<li><a href="/examples/api-routes-graphql">API routes with GraphQL server</a></li>
<li><a href="/examples/api-routes-rest">API routes with REST</a></li>
</ul>
</details>

Expand All @@ -1064,6 +1065,18 @@ export default (req, res) => {

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

To handle different HTTP methods for API calls you can access `req.method` in your resolver function:

```js
export default (req, res) => {
if (req.method === 'POST') {
// Process your POST request
} else {
// Handle the rest of your HTTP methods
}
}
```

> **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).
Expand Down