diff --git a/examples/with-msw/.env b/examples/with-msw/.env deleted file mode 100644 index f2f2baa1e38d..000000000000 --- a/examples/with-msw/.env +++ /dev/null @@ -1,4 +0,0 @@ -# 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" \ No newline at end of file diff --git a/examples/with-msw/package.json b/examples/with-msw/package.json index d55b6641ec28..967337fb2234 100644 --- a/examples/with-msw/package.json +++ b/examples/with-msw/package.json @@ -8,7 +8,7 @@ }, "license": "MIT", "dependencies": { - "msw": "^0.21.0", + "msw": "^0.21.2", "next": "latest", "react": "^16.13.1", "react-dom": "^16.13.1" diff --git a/examples/with-msw/pages/_app.js b/examples/with-msw/pages/_app.js index b20c39be7b76..5202969b2f60 100644 --- a/examples/with-msw/pages/_app.js +++ b/examples/with-msw/pages/_app.js @@ -1,4 +1,6 @@ -if (process.env.NEXT_PUBLIC_API_MOCKING === 'enabled') { +// Enable API mocking in all environments except production. +// This is recommended for real-world apps. +if (process.env.NODE_ENV !== 'production') { require('../mocks') } diff --git a/examples/with-msw/pages/index.js b/examples/with-msw/pages/index.js index f22c03b0b41f..823fba68a1f4 100644 --- a/examples/with-msw/pages/index.js +++ b/examples/with-msw/pages/index.js @@ -1,6 +1,6 @@ import { useState } from 'react' -export default function Home({ book }) { +export default function Home({ book, inProduction }) { const [reviews, setReviews] = useState(null) const handleGetReviews = () => { @@ -10,6 +10,18 @@ export default function Home({ book }) { .then(setReviews) } + if (inProduction) { + return ( +
+

+ This example does not work in production, as MSW is not intended for + use in production. In a real-world app, your request will hit the + actual backend instead. +

+
+ ) + } + return (
{book.title} @@ -32,12 +44,21 @@ export default function Home({ book }) { 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() + // In a real-world app this request would hit the actual backend. + try { + const res = await fetch('https://my.backend/book') + const book = await res.json() - return { - props: { - book, - }, + return { + props: { + book, + }, + } + } catch (error) { + return { + props: { + inProduction: true, + }, + } } }