Little bit exploring Mirage JS

I usually work parallel with my colleagues, while doing my work, I have to wait for my colleague to finish their APIs first, but this process will take a long time. To optimize my work I decided to mocks API while waiting for their API to finished.

So after doing my little research, I finally found a tool to mock API. Mirrage JS it seems suitable for my case, as their slogan is:


Build complete frontend features, even if your API doesn't exist.

Then I took an hour to read their documentation and did several tests to ensure this library tool suitable/fit for my project.
Notes: I only test GET & POST method only as my project requirement. for more details, please read their documentation.


Setting up

Add Mirage to your project, install the package first:
npm install --save-dev miragejs

Axios to fetch data
npm install --save-dev axios

And Vite.js to run local development
npm install --save-dev vite


Configure development environment

First create index.html as default document file.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>

And vite.config.js for server configuration.

export default {
  server: {
      port: 3000
  }
}

Then create server.js as a mocking APIs file, we store all routing APIs inside here, We use /movies as example.

import { createServer } from "miragejs"
export function makeServer(){
  createServer({
    routes() {
      this.namespace = "api"

      // GET method
      this.get("/movies", () => {
        return {
          movies: [
            { id: 1, name: "Inception", year: 2010 },
            { id: 2, name: "Interstellar", year: 2014 },
            { id: 3, name: "Dunkirk", year: 2017 },
          ],
        }
      })
      
      // POST method
      let newId = 1
      this.post("/movies", (schema, request) => {
        let attrs = JSON.parse(request.requestBody)
        attrs.id = newId++

        return { reminder: attrs }
      })
    },
  })
}

Call ./server.js from main.js using Axios.

import { makeServer } from "./server";
import axios from "axios";

makeServer();

// Call GET method
axios
  .get("/api/get/movies")
  .then(function (response) {
    // handle success
    console.log(response.data, "my response");
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Call POST method
let request = {
  reminder: {
    id: 4,
    text: "Shop for groceries ",
  },
};
axios
  .post("/api/post/movies", request)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Then lastly run server development by type command npm run dev and navigate your URL to http://localhost:3000/api/get/movies , you will see your API response created before. And you can use http://localhost:3000/api/post/movies for POST method.

Benefit

There are other benefits to using Mirage:

  • Mirage saves development time, especially for front-end teams.
  • Faster response.
  • Can mocks look like actual API structures.

Conclusion

Mirage JS is a powerful JavaScript library designed to mock APIs. With support for HTTP methods like GET, POST, PUT, and DELETE, Mirage JS simplifies the process of simulating server behaviour. It is particularly useful for projects in the early stages, during backend delays, or for testing and debugging front-end code. This tool helps me to increase my development time while waiting for APIs response to be ready.