Improve Frontend-Backend development harmony with JSON-Server
Tags: webdev, productivity, json, collaboration
Published: 2023-06-12 20:50:32

---
title: Improve Frontend-Backend development harmony with JSON-Server
published: true
description: Learn how JSON-Server improves collaboration between frontend and backend developers. Discover key steps to simplify coordination, define API endpoints, design object structures, and communicate changes effectively.
tags: webdev, productivity, JSON, collaboration
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iizgdjedgzri0m491gxi.png
---

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](https://xp123.com/articles/invest-in-good-stories-and-smart-tasks/) 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](https://github.com/typicode/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:

```bash
npm i -D json-server concurrently
```

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**

```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"
		}
	]
}

```

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**

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

```

Let's configure our scripts in the **`package.json`** file to launch JSON-Server, to make the process easier we will use [Concurrently](https://www.npmjs.com/package/concurrently), an NPM package that allow us to run multiple commands simultaneously.

**package.json**

```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\""
	}
}

```

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**

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

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

```

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

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

```

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

**blog.service.ts**

```tsx
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);
	}
}
```

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.

```tsx
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)

```

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

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

```

## 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](https://github.com/jeremyben/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.