Develop a Next.js App against a Shared Mirage Server

Once you're ready to centralize your Mirage server and share it between development and testing, follow these steps.

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: Define your shared server

A common place to define your shared server is mirage.js:

// mirage.js
import { createServer, Model } from "miragejs"

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,

    models: {
      movie: Model,
    },

    seeds(server) {
      server.create("movie", { name: "Inception", year: 2010 })
      server.create("movie", { name: "Interstellar", year: 2014 })
      server.create("movie", { name: "Dunkirk", year: 2017 })
    },

    routes() {
      this.namespace = "api"

      this.get("/movies", (schema) => {
        return schema.movies.all()
      })
    },
  })

  return server
}

Step 3: Start your server in development

Open your Next.js app's initialization file (pages/_app.js), import your makeServer function, and call it in the development environment:

// pages/_app.js
import { makeServer } from "../mirage"

if (process.env.NODE_ENV === "development") {
  makeServer({ environment: "development" })
}

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Now, whenever any page in your application makes a network request in development, Mirage will intercept that request and respond with the data from your server definition.

You now have a central place to define and update your Mirage server as you continue local development on your Next.js app.