Setup a React App with Mirage for Development

Mock your React app's networking code so you can develop your React app without any backend services.

This is a quickstart guide for people familiar with Mirage. If you're brand new to Mirage, take a look at the Overview.

Step 1: Install Mirage

First, make sure you have Mirage installed:

# Using npm
npm install --save-dev miragejs

# Using Yarn
yarn add --dev miragejs

Step 2: Define your server

Create a new server.js file and define your mock server.

Here's a basic example:

// src/server.js
import { Server, Model } from "miragejs"

export function makeServer({ environment = "development" } = {}) {
  let server = new Server({
    environment,

    models: {
      user: Model,
    },

    seeds(server) {
      server.create("user", { name: "Bob" })
      server.create("user", { name: "Alice" })
    },

    routes() {
      this.namespace = "api"

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

  return server
}

In a Create React App, put this file in src/server.js so that changes to it trigger rebuilds.

Step 3: Start your server in development

Open your React app's bootstrap file (src/index.js in a Create React App), import your makeServer function, and call it in the development environment:

// src/index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { makeServer } from "./server"

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

ReactDOM.render(<App />, document.getElementById("root"))

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

For example, given the server definition above, the following component would fetch the users Bob and Alice that we defined in seeds:

// src/App.js
import { useState, useEffect } from "react"

export default function App() {
  let [users, setUsers] = useState([])

  useEffect(() => {
    fetch("/api/users")
      .then(res => res.json())
      .then(json => {
        setUsers(json.users)
      })
  }, [])

  return (
    <ul data-testid="users">
      {users.map(user => (
        <li key={user.id} data-testid={`user-${user.id}`}>
          {user.name}
        </li>
      ))}
    </ul>
  )
}

You can now continue to develop your React app, mocking out your backend API endpoints with Mirage as you go.