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

Example for API routes with middleware #7958

Merged
merged 1 commit into from
Jul 15, 2019
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
42 changes: 42 additions & 0 deletions examples/api-routes-middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# API routes with middleware

## How to use

### Using `create-next-app`

Execute [`create-next-app`](https://github.com/segmentio/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-middleware api-routes-middleware-app
# or
yarn create next-app --example api-routes-middleware api-routes-middleware-app
```

### Download manually

Download the example:

```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/api-routes-middleware
cd api-routes-middleware
```

Install it and run:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

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 to implement simple `middleware` to wrap around your `API` endpoints.
17 changes: 17 additions & 0 deletions examples/api-routes-middleware/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "api-routes-middleware",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"cookie": "0.4.0",
"isomorphic-unfetch": "3.0.0",
"next": "latest",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
8 changes: 8 additions & 0 deletions examples/api-routes-middleware/pages/api/cookies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import cookies from '../../utils/cookies'

const handler = (req, res) => {
res.cookie('Next.js', 'api-middleware!')
res.end('Hello Next.js middleware!')
}

export default cookies(handler)
12 changes: 12 additions & 0 deletions examples/api-routes-middleware/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import fetch from 'isomorphic-unfetch'

const Index = ({ cookie }) => <div>{`Cookie from response: ${cookie}`}</div>

Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/cookies')
const cookie = response.headers.get('set-cookie')

return { cookie }
}

export default Index
27 changes: 27 additions & 0 deletions examples/api-routes-middleware/utils/cookies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { serialize } from 'cookie'

/**
* This sets `cookie` on `res` object
*/
const cookie = (res, name, value, options = {}) => {
const stringValue =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)

if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge)
options.maxAge /= 1000
}

res.setHeader('Set-Cookie', serialize(name, String(stringValue), options))
}

/**
* Adds `cookie` function on `res.cookie` to set cookies for response
*/
const cookies = handler => (req, res) => {
res.cookie = (name, value, options) => cookie(res, name, value, options)

return handler(req, res)
}

export default cookies
2 changes: 2 additions & 0 deletions packages/next/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,8 @@ export default withRouter(MyLink)
<ul>
<li><a href="/examples/api-routes">Basic API routes</a></li>
<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>
</ul>
</details>

Expand Down