NS

Setup Node Express Server to mock APIs response locally

In this article, You and I will work together on spinning up an Express Server locally. Let’s say you are a front end developer and started building a skeleton React App. The next thing you would do is ask your back end buddy when the back end is ready so your UI has APIs ready to hit to integrate your front end with the back end. However, at scale, the back end could be complicated and not every time, you would have the APIs ready to work with. Let’s look at it in detail.

Why do we need to Mock an API?

  1. Development: If back end and front end development is being worked upon in parallel, then your UI would require dummy data to build your UI against. Something like a dummy response will help render your UI.
  2. Testing: You could manually test your UI when your back end is not available.
  3. Let’s say you want to manually test scenarios to see how your UI performs when supplied with inconsistent data.
  4. If you don’t have internet for whatever reason, your app would still work given that it is mocking data locally.
  5. My Absolute Favorite: YOU COULD CODE IN THE AIR (ON THE PLANE) — Assuming you haven’t purchased WiFi in the air!!!!

Hopefully, that was enough to convince you that it is very useful to mock API response locally. Let’s get on to how we would do it.

Let us start with creating a React App using create-react-app

create-react-app MyExpressApp  
cd MyExpressApp  
npm start

This should bring up your web app locally on http://localhost.com:3000 (mostly port is 3000).

Now we will build an express server locally. To understand the code better, I will create separate files so it is easy to follow. Let us start with a simple JSON file to mock data from.

data.json — This is where you should put the response you want to mock.

[
  {
    "id": 1,
    "name": "sample-name-1"
  },
  {
    "id": 2,
    "name": "sample-name-2"
  },
]

dataController.js — We will set up a very simple logic in this file to read from the data file you created in the previous step

const path = require('path');
const fs = require('fs');

const basePathToData = path.join(__dirname, 'path-to-your-json-data-file');

const getJsonData = function (basePathToData, filename) {
  var filename = path.join(basePathToData, filename);
  return JSON.parse(fs.readFileSync(filename, 'utf-8'));
};

exports.getData = function (request, response) {
  var data = getData(basePathToData, 'data.json');
  setTimeOut(function() {
    return response.send(data);
  }, 100);
};

server.js — This is the gist of everything. This is the file we will execute to mock the server. It listens to the port and the API string you have in your “app.get”. If you hit “localhost:3002/api/data”, your dataController will call getData which would fetch the data from the data.json file in JSON format.

const express = require('express')
const app = express()
var path = require('path')
var bodyParser = require('body-parser')
app.use(express.static(path.join(__dirname, 'build')));

var dataController = require('./dataController');

app.get('/api/data', dataController.getData);

const port = 3002;

app.listen(process.env.PORT || port);

Finally, to start your server, run

node server.js

That’s it !! Your API is mocked locally now.

Let us Test it

  1. Open up your favorite browser
  2. Navigate to “http://localhost:3002/api/data”,
  3. You should see the response.

Note: You must be wondering, your web app is hosted on port 3000 while your API is hosted on port 3002. Exactly, your web app currently does not know that your API is mocked on a different port. Fortunately, this problem has a very simple solution. Just add port 3002 as a proxy to your web app.

Alright, so in your package.json, add a proxy so your web app knows that the API is mocked at a different port.

**Filename: package.json**"proxy": "http://localhost:3002"

Feel free to disconnect from the internet, go to space, etc., your API will always respond and your web app is always listening to the mocked API.

I am very passionate about helping more and more people learn how to code. If you have ideas on what I should write next, please comment. Hope you enjoyed reading it. Happy Hacking!