Improve Frontend-Backend development harmony with JSON-Server

mino89

pierdomenico reitano

Posted on June 12, 2023

Improve Frontend-Backend development harmony with JSON-Server

As a frontend developer, one of the main challenges I have encountered in my work is finding the best way to coordinate and collaborate with the backend development team when working on a feature. This challenge becomes even more complex when collaborating with external companies or clients.

Often, requests come in the form of user stories, and one of the fundamental principles that make them well-formulated is the INVEST principle, acronym for Independent Negotiable, Valuable, Estimable, Small, Testable. Independent means that each user story should have the ability to be worked on independently, avoiding issues of dependencies or cascading delays.

To achieve this goal, I have learned that taking some organizational actions with the team is crucial. When developing a feature that involves both frontend and backend, following key steps can simplify synchronization and reduce complications:

  1. Clearly define API endpoints: First and foremost, it is crucial to clearly define and share the names of the API endpoints with all team members.
  2. Collaboratively design object structures: Another important practice is to collaboratively design the structure of objects exchanged between the frontend and backend. This helps create a common guide for development and ensures that everyone is aware of the necessary information to work effectively.
  3. Communicate any changes promptly: During development, changes or updates to the frontend interface or backend business logic may occur. It is essential to promptly communicate such changes to everyone involved in the collaboration. This way, we can make the necessary adjustments in a timely manner and reduce obstacles that may arise due to discrepancies between frontend and backend.

Who can help us?

JSON-Server creates fake REST API with a minimum amount of configuration, it provides a simple way to create mock RESTful APIs and easily define the required endpoints, allows easy definition of the data schema in a JSON file and can serve as a reference for each figure in the project.

Hands-on with JSON-Server

Now let's take a deep look at how this tool works and can help in our projects.

First, let's proceed with installing the modules:

npm i -D json-server concurrently
Enter fullscreen mode Exit fullscreen mode

JSON-Server uses .json files to simulate the behaviour of a real database. So, let's create a db.json in the root folder of our project, with a data structure that we have agreed upon and shared with the team or backend developer.

db.json

{
    "categories":[
        {
            "id":1,
            "name":"tech"
        },
        {
            "id":2,
            "name":"music"
        }
    ],
    "posts":[
        {
            "id":1,
            "categoryId":1,
            "title": "How to get started with Docker",
            "content": "content of the article about Docker"
        },
        {
            "id":2,
            "categoryId":2,
            "title": "New Iron Maiden's album is out",
            "content": "content of the article about the new Iron Maiden's album"
        }
    ]
}

Enter fullscreen mode Exit fullscreen mode

To keep everything clear and easy to maintain, let's create a json-server.json file in the root folder of our project. This file allows us to define a default configuration. We will include the watch:true option to ensure that the server updates when we modify the db.json file, and delay:1000 to simulate the latency of a real server and a the port where our server will run.

json-server.json

{
  "delay": 1000,
  "middlewares": [],
  "watch": true,
  "port": 3000
}

Enter fullscreen mode Exit fullscreen mode

Let's configure our scripts in the package.json file to launch JSON-Server, to make the process easier we will use Concurrently, an NPM package that allow us to run multiple commands simultaneously.

package.json

{
    "name": "My Amazing Project",
    "version": "0.0.1",
    "scripts":{
        "start": "<your-serve-command>",
        "mock-api": "json-server db.json",
        "dev": "concurrently \"npm run mock-api\" \"npm run start\""
    }
}

Enter fullscreen mode Exit fullscreen mode

By running npm run dev, we will start both our app and the mock server at http://localhost:3000

As mentioned earlier, we need to be able to handle our code development with simplicity and avoid time-consuming tasks that distract us from our main objectives.

At this point, all that's left is to save our URL in a configuration variable that we can use within our projects.

mock-server.config.ts

import * as jsonServerConfig from './json-server.json';

export const mockServerConfig = {
    apiUrl: `http://localhost:${jsonServerConfig.port}`
};

Enter fullscreen mode Exit fullscreen mode

With JSON-Server, you can use all available HTTP methods:

bashCopy code
GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

Enter fullscreen mode Exit fullscreen mode

Let's implement our service that we will use to manage our posts.

blog.service.ts

export class BlogService {

    constructor(apiUrl) {
        this.apiUrl = apiUrl
    }

    private apiUrl = mockServerConfig.apiUrl;
    private headers = { 'Content-Type': 'application/json' };

    private async handleResponse(res: Response) {
        if (!res.ok) {
            throw new Error(`Error: ${await res.text()}`);
        } else {
            return res.json();
        }
    }

    async getPosts() {
        const url = `${this.apiUrl}/posts`;
        const res = await fetch(url);
        return this.handleResponse(res);
    }

    async createPost() {
        const url = `${this.apiUrl}/posts`;
        const body = {
            categoryId: 1,
            title: 'json-server is cool',
            content: 'content of the article about json server'
        };
        const res = await fetch(url, {
            method: 'POST',
            body: JSON.stringify(body),
            headers: this.headers
        });
        return this.handleResponse(res);
    }
}
Enter fullscreen mode Exit fullscreen mode

We can use mockServerConfig as the default option in our development environment, while relying on environment variables for the production environment. This approach eliminates the need to manually change configurations during development or deployment, ensuring a smoother workflow.

import { mockServerConfig } from './mock-server.config.ts'
import { BlogService } from './blog.service.ts'

const apiUrl = process.env.PRODUCTION 
                        ? process.env.API_URL 
                        : mockServerConfig.apiUrl

const blogService = new BlogService(apiUrl)

Enter fullscreen mode Exit fullscreen mode

The createPost() method updates our db.json file. If we check it, we will find a new object inside the posts array:

{
...
    "posts":[
            {
                "id":1,
                ...
            },
            {
                "id":2,
                ...
            },
            {
                "id":3,
                "categoryId":1,
                "title": "json-server is cool",
                "content": "content of the article about json server"
            }
        ]
}

Enter fullscreen mode Exit fullscreen mode

Conclusions

In addition to allowing us to easily manage our endpoints and data structures, JSON-Server offers a range of interesting features. These include the ability to customize URLs with minimal configuration and create custom middleware. I have used JSON-Server-Auth to quickly add an authentication and authorization system to some of my projects.

Furthermore, it can be useful for multiple purposes. For example, you could create a dedicated file to be used as a data mock during the execution of End-to-End tests, eliminating the need to create a separate database version specifically for this purpose.

It is crucial to keep in mind that the decision to adopt these features should be based on the unique requirements of your project and the dynamics of your team.

💖 💪 🙅 🚩
mino89
pierdomenico reitano

Posted on June 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related