How to create a Mock Server using Faker.js and JSON server
By: Shivaraj Bakale
Tags: Angular, Frontend, React, Frontend Development, React Native

This post is aimed towards Front-end Engineers. By the end of this post, you’ll be able to use faker.js and JSON-server to create a mock server that you can use and consume from any application. Basic knowledge of javascript is assumed.

Problem

As Frontend Engineers, it’s quite often we come across a scenario where we want to get started on a feature but are blocked on the backend team providing the API’s. Or maybe we just want to get started with the Frontend Prototyping and don’t have the backend ready yet. If that resonates with you, know that I’ve been there too. After reading this post you’ll be able to set up a mock server that can act as a backend, so you can start building right away.

What we’re going to use

Faker.js

faker. js is a JavaScript library for generating fake data. The fake data can include images, text in various formats, names etc.

JSON Server

Once we have created our fake data using faker.js we’ll need a way to host our data so our application(Frontend) is able to start consuming it. This is provided by json-server

Setup

Step 1: Initialize an npm project

npm init

Provide the following details

project-name (mock-server)

version (1.0.0)

description

entry-point (app.js)

This creates the package.json file with all of the above details. Now, create the app.js file which is an entry point for the project.

Step 2: Install the dependencies

npm i faker

The above command will install the faker library in the project.

npm install -g json-server

This will install JSON-server globally so you can control the server using the CLI.

Step 3: Generating the fake data

Now, we can start using the faker.js library to generate mock data for us. You can find a list of the things you can generate using faker on the official website. As an example, let’s use it to generate images, colors, and paragraphs.

Generating Images using Faker

We’ll start by creating a file app.js.

const faker=require('faker'); /* Generate Images */

const generateImages = (number) => {

const images = [];

while (number !== 0) {

const value = faker.image.image();

images.push(value);

number--;

}

return images;

};

This function takes in the number as a parameter and generates those many images. The generated images are random images. Alternatively, you can use the imageUrl(width, height) method on faker.image to generate images of specific width and height.

Running the above code results in the following output

Generating Dates

const faker=require("faker"); /* Generate the Date */

const generateDate = () => {

return faker.date.future();

};

To generate the dates, we’re going to use the date utility provided by faker. We can choose to generate dates of different which are in the past, future, in-between two dates, etc.

For the sake of this example, I’ll be generating a future date using the future method. This is how the output looks like.

Great!! Similarly, We’ll now see how we can go about generating paragraphs of text using the lorem methods in faker.

Generating Paragraphs, Sentences, Lines

const generateParagraphs = (number) => {

return faker.lorem.paragraphs(number);

};

The above method is used to generate paragraphs of text. Note that we’re using the paragraphs(number) method in faker. Similar to generating paragraphs, we can also generate sentences, lines, text, etc.

Generating Mock User Data

Now that we’ve got a drift of how to go about using faker, we can start generating mock data using faker. Let’s create Mock data for 20 users with the following schema

{

"id":number

"name":<String>,

"description":<String(paragraph)>,

"country":<String(country)>,

"picture":<String (Profile image url)>,

"joining_date":<Date>

}

Code

// Code to generate User Mock data

const generatePersonsData = (number) => {

const persons = [];

while (number >= 0) {

persons.push({

id:number,

name: faker.name.firstName(),

description: faker.lorem.paragraphs(2),

picture: faker.image.avatar(),

country: faker.address.country(),

joining_date: faker.date.future(),

});

number--;

}

return persons;

};

Running the above code yields the following result

node app.js

As we can see from the image, we’re able to generate the user details. But wait, we need a way to consume this from our Frontend application, and we’re not there yet. To do that we’re going to make use of json-server what we had installed previously. Let's see how that works.

How does JSON Server serve our data?

The way the json-server utility works is very simple. Once installed, we need to create a JSON file that will act as a database for our frontend to consume.

Let's create a db.json file that stores users' information that we want to serve.

{

"users": [{

"id":1,

"name": "Rupert",

"description":"Some description",

"picture":"

<https://cdn.fakercloud.com/avatars/andysolomon_128.jpg>",

"country": "Malaysia",

"joining_date": "2021-11-11T06:58:41.548Z"

},

{

"id":2,

"name": "Lester",

"description":"Some description",

"picture": "<https://cdn.fakercloud.com/avatars/jamiebrittain_128.jpg>",

"country": "Bouvet Island (Bouvetoya)",

"joining_date": "2021-08-07T18:40:37.096Z"

},

{

"id":3,

"name": "Florencio",

"description":"Some description",

"picture": "<https://cdn.fakercloud.com/avatars/cocolero_128.jpg>",

"country": "Singapore",

"joining_date": "2022-03-24T23:44:34.413Z"

},

{

"id":4,

"name": "Margret",

"description":"Some description",

"picture": "<https://cdn.fakercloud.com/avatars/akashsharma39_128.jpg>",

"country": "Jamaica",

"joining_date": "2021-04-18T17:01:03.477Z"

},

{

"id":5,

"name": "Rachelle",

"description":"Some description",

"picture": "<https://cdn.fakercloud.com/avatars/victor_haydin_128.jpg>",

"country": "Cameroon",

"joining_date": "2022-03-15T16:15:56.038Z"

}]

}

Once the file has been created, we can then go ahead and type in the following command.

json-server --watch db.json --port 3004

This will start serving the data in the db.json file on localhost:3004.

We can visit the following route in the browser to see the results

http://localhost:3004/users

Final Step

Now, let's make changes to our app.js file to generate a db.json file when the server is run.

const faker = require("faker");

const fs = require("fs"); const generatePersonsData = (number) => {

const persons = [];

while (number >= 0) {

persons.push({

id: number,

name: faker.name.firstName(),

description: faker.lorem.paragraphs(2),

picture: faker.image.avatar(),

country: faker.address.country(),

joining_date: faker.date.future(),

});

number--;

}

return persons;

}; fs.writeFileSync(

"./db.json",

JSON.stringify({ users: generatePersonsData(20) })

);

This code will generate the db.json file with our user details, with the users as the key. For our example, I’ve just added one property, but we can always come back to this file and create properties with different schemas.

Now, let's write a script in bash to run this code and start the json-server.

mock_server.sh

#!/bin/bash

node app.js

json-server --watch db.json --port=3004

That's about it. You have your mock data ready to consume on port 3004 .

Note that you can make all the CRUD operations on the mock-server as you would normally do with an actual database.

Examples

Fetching the details of a specific user

We can use the following format to get the details of a specific user from the user's array

GET <http://localhost:3004/users/{id} >

Example Curl Request

curl --location --request GET 'localhost:3004/users/1' \\

--header 'Content-Type: application/json'

Deleting a specific user

We can use the following format to get the delete of a specific user from the users array

DELETE <http://localhost:3004/users/{id} >

Example Curl Request

curl --location --request DELETE 'localhost:3004/users/1'

Updating a specific user

We can use the id field on the user object to make changes to a specific use

PUT <http://localhost:3004/users/{id} >

Example Curl Request

curl --location --request PUT 'localhost:3004/users/16' \\

--header 'Content-Type: application/json' \\

--data-raw '{

"id": 16,

"name": "Harry"

}'

Conclusion

In this tutorial, we have seen how to use the faker library and json-server to create a mock server which we can use to prototype our frontend application quickly. Great software engineers need to be creative in how to unblock themselves from their dependencies. If that sentence resonates well with you, maybe you’ll have a lot of fun as I am in creating world-class apps. Thanks for reading until the very end. If this post was in any way helpful to you, do give me a clap, that’ll keep me motivated to keep writing :)