Setup a Vue app with Mirage for Development

Mock your Vue app's networking code so you can develop your Vue 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 { createServer, Model } from "miragejs"

export function makeServer({ environment = "development" } = {}) {
  let server = createServer({
    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 Vue CLI, put this file in src/server.js so that changes to it trigger rebuilds.

Step 3: Use your server in development

Open your Vue app's bootstrap file (src/main.js in Vue CLI), import your makeServer function, and call it in the development environment:

// src/main.js
import Vue from "vue"
import App from "./App.vue"
import { makeServer } from "./server"

Vue.config.productionTip = false

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

new Vue({
  render: (h) => h(App),
}).$mount("#app")

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.vue -->
<template>
  <ul id="users">
    <li v-for="user in users" v-bind:key="user.id">{{ user.name }}</li>
  </ul>
</template>

<script>
  export default {
    name: "app",

    data() {
      return {
        users: [],
      }
    },

    created() {
      fetch("/api/users")
        .then((res) => res.json())
        .then((json) => {
          this.users = json.users
        })
    },
  }
</script>

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