Skip to content

Commit

Permalink
Merge branch 'canary' into update/rewrite-query-appending
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] authored Aug 14, 2020
2 parents 021febf + 746000e commit fddd30b
Show file tree
Hide file tree
Showing 12 changed files with 402 additions and 0 deletions.
4 changes: 4 additions & 0 deletions examples/with-msw/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Enable API mocking in all environments, this is only for the sake of the example.
# In a real app you should move this variable to `.env.development`, as mocking the
# API should only be done for development.
NEXT_PUBLIC_API_MOCKING="enabled"
34 changes: 34 additions & 0 deletions examples/with-msw/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel
29 changes: 29 additions & 0 deletions examples/with-msw/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Mock Service Worker Example

[Mock Service Worker](https://github.com/mswjs/msw) is an API mocking library for browser and Node. It provides seamless mocking by interception of actual requests on the network level using Service Worker API. This makes your application unaware of any mocking being at place.

In this example we integrate Mock Service Worker with Next by following the next steps:

1. Define a set of [request handlers](./mocks/handlers.js) shared between client and server.
1. Setup a [Service Worker instance](./mocks/browser.js) that would intercept all runtime client-side requests via `setupWorker` function.
1. Setup a ["server" instance](./mocks/server.js) to intercept any server/build time requests (e.g. the one happening in `getServerSideProps`) via `setupServer` function.

Mocking is enabled using the `NEXT_PUBLIC_API_MOCKING` environment variable, which for the sake of the example is saved inside `.env` instead of `.env.development`. In a real app you should move the variable to `.env.development` because mocking should only be done for development.

## 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/vercel/next.js/tree/canary/examples/with-msw)

## How to use

Execute [`create-next-app`](https://github.com/vercel/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
npx create-next-app --example with-msw with-msw-app
# or
yarn create next-app --example with-msw with-msw-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)).
4 changes: 4 additions & 0 deletions examples/with-msw/mocks/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { setupWorker } from 'msw'
import { handlers } from './handlers'

export const worker = setupWorker(...handlers)
26 changes: 26 additions & 0 deletions examples/with-msw/mocks/handlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { rest } from 'msw'

export const handlers = [
rest.get('https://my.backend/book', (req, res, ctx) => {
return res(
ctx.json({
title: 'Lord of the Rings',
imageUrl: '/book-cover.jpg',
description:
'The Lord of the Rings is an epic high-fantasy novel written by English author and scholar J. R. R. Tolkien.',
})
)
}),
rest.get('/reviews', (req, res, ctx) => {
return res(
ctx.json([
{
id: '60333292-7ca1-4361-bf38-b6b43b90cb16',
author: 'John Maverick',
text:
'Lord of The Rings, is with no absolute hesitation, my most favored and adored book by‑far. The triology is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!',
},
])
)
}),
]
7 changes: 7 additions & 0 deletions examples/with-msw/mocks/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
if (typeof window === 'undefined') {
const { server } = require('./server')
server.listen()
} else {
const { worker } = require('./browser')
worker.start()
}
4 changes: 4 additions & 0 deletions examples/with-msw/mocks/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
16 changes: 16 additions & 0 deletions examples/with-msw/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "with-msw",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"license": "MIT",
"dependencies": {
"msw": "^0.20.4",
"next": "latest",
"react": "^16.13.1",
"react-dom": "^16.13.1"
}
}
7 changes: 7 additions & 0 deletions examples/with-msw/pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
if (process.env.NEXT_PUBLIC_API_MOCKING === 'enabled') {
require('../mocks')
}

export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
43 changes: 43 additions & 0 deletions examples/with-msw/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useState } from 'react'

export default function Home({ book }) {
const [reviews, setReviews] = useState(null)

const handleGetReviews = () => {
// Client-side request are mocked by `mocks/browser.js`.
fetch('/reviews')
.then((res) => res.json())
.then(setReviews)
}

return (
<div>
<img src={book.imageUrl} alt={book.title} width="250" />
<h1>{book.title}</h1>
<p>{book.description}</p>
<button onClick={handleGetReviews}>Load reviews</button>
{reviews && (
<ul>
{reviews.map((review) => (
<li key={review.id}>
<p>{review.text}</p>
<p>{review.author}</p>
</li>
))}
</ul>
)}
</div>
)
}

export async function getServerSideProps() {
// Server-side requests are mocked by `mocks/server.js`.
const res = await fetch('https://my.backend/book')
const book = await res.json()

return {
props: {
book,
},
}
}
Binary file added examples/with-msw/public/book-cover.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit fddd30b

Please sign in to comment.