Develop a Next.js page with Mirage
Mock out client-side API requests directly within a page of your Next.js app so you can continue local development without any backend services.
Note: At this time, Mirage only runs in the browser, meaning it will not mock out any server-side network calls your Next.js app makes via hooks like getServerSideProps.
Step 1: Install Mirage
First, make sure you've added Mirage to your project:
# Using npm
npm install --save-dev miragejs
# Using Yarn
yarn add --dev miragejs
Step 2: Create a Server in a page
Within a page file, import Server
from Mirage, create a server, and start mocking out API endpoints that your code needs:
// pages/index.js
import { useState, useEffect } from "react"
import { createServer } from "miragejs"
createServer({
routes() {
this.get("/api/movies", () => ({
movies: [
{ id: 1, name: "Inception", year: 2010 },
{ id: 2, name: "Interstellar", year: 2014 },
{ id: 3, name: "Dunkirk", year: 2017 },
],
}))
},
})
export default function Index() {
let [movies, setMovies] = useState([])
useEffect(() => {
fetch("/api/movies")
.then((res) => res.json())
.then((json) => {
setMovies(json.movies)
})
}, [])
return (
<ul>
{movies.map((movie) => (
<li key={movie.id}>
{movie.name} ({movie.year})
</li>
))}
</ul>
)
}
You can now continue to develop your page, mocking out your backend API endpoints with Mirage as you go.
Note: You can only have one Mirage Server instantiated at a time, so if you want to share your mocking code across multiple pages, check out the guide on centralizing and sharing your Mirage server.