Build your first Microservice application with Node Js
Published: 2024-01-14 16:51:20







Back in the early days of making software, a common practice was to tightly connect all the different parts, forming what we call a monolithic application. But there was a problem – when something went wrong in one part, the whole system felt the impact, like a domino effect.

Nowadays, we've got a smarter approach called microservices. Instead of bundling everything tightly, we build our software in separate pieces. So, if one piece has a hiccup, it doesn't mess up the entire software.

In this article, we're going to explore microservices. We'll see how to create one using Node.js, a tool that works with JavaScript. And, as a bonus, we'll talk about how this new way of doing things is changing how people make software. Ready to learn?

Before we start, make sure you have Node.js installed on your computer and have a basic understanding of JavaScript and Node.js.

**Table of Contents**

- Monolithic applications vs microservices
- Communications between microservices
- Using Node js for microservices
- Building an application with Node and Express Js !!!!

<u>**Monolothic applications vs microservices**</u>

**Understanding Monolithic applications**

Imagine constructing a car from scratch where the engine, wheels, and navigation system are all tightly integrated into a single unit. If there's an issue with any part, fixing it means shutting down the entire car.

This approach, similar to a monolithic application, is not flexible or easily scalable. You can't upgrade individual features or make continuous improvements. While it might be cheaper to initially build, managing and adapting such a system becomes expensive over time.

Recognizing these challenges, developers sought a better way – a system where a problem in one part doesn't disrupt the entire vehicle.

**Understanding Microservices**

Microservices became necessary due to the shortcomings of the monolithic pattern of software development. In a microservice, each software application feature is separated from the other, in most cases with their respective servers and databases. Applications built with this kind of architecture are loosely coupled, also referred to as distributed applications.

Imagine we’re building an ecommerce store. We’ll need models for a payment feature, cart, customers, admin, and order. Each of these features will have its own separate servers and databases.

Our ecommerce microservices will communicate with each other using the REST API framework. Because we’ll develop our store features independently from each other, if our system develops a fault, we can easily identify which feature to debug and avoid having to bring down the entire application.

In contrast to monolithic applications, applications developed using microservices are scalable. You can use any programming language to develop a microservice; in fact, you can use different languages to develop different features in a microservice application.

Overall, microservices offer a better developer experience. A new developer joining the team won’t have to understand the entire codebase, but rather just the features they are working on, increasing overall productivity. Lastly, unit testing is encouraged in microservices; you can write a unit test to test any particular functionality.

It’s important to keep in mind that building a microservice requires expertise because integration and end-to-end testing can be very challenging. Additionally, microservices can become very bulky, resulting in high maintenance costs. Lastly, it’s not always easy to migrate software already developed using monolithic architecture to a microservice, and it can be challenging for applications to locate each other within a complex network.

<u>**Communication between microservices**</u>

Embracing a microservice architectural pattern presents its own set of challenges, and one of these challenges revolves around how different services communicate with each other. Services, which are essentially independent parts of an application, collaborate to enhance the overall performance of the application.

For optimal performance, it's crucial to establish a communication mechanism between these microservices. In a microservice application, this communication is facilitated by an inter-service communication protocol, such as HTTP(s), gRPC, or through the use of message brokers.

Now, let's delve into various methods through which services establish communication within the framework of a microservice architecture.

**HTTP communication**

HTTP communication is a kind of synchronous communication pattern where a service is dependent on another to perform:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzvlfreundui929nzkuu.jpeg)

The image above represents the HTTP request-response cycle, where the client makes a request and waits for a response from the server-side application.

**Event-driven communication pattern**

The event-driven communication pattern entails an interaction between a service provider and a service consumer. The service consumer requires a resource from an external source. It then performs some computations and relays the response to the client:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fnpg0gg6a9t4j8n77ho.jpeg)

<u>**Using Node.js for our microservice**</u>

You can use any programming language to develop a microservice, like Java, C#, Python, or Lambo winning PHP but Node.js is an outstanding choice for a few reasons.

For one, Node.js uses an event-driven architecture and enables efficient, real-time application development. Node.js single-threading and asynchronous capabilities enable a non-blocking mechanism. When building a microservice with Node.js, developers will experience an uninterrupted flow and enjoy Node’s speed, scalability, and easy maintenance.

<u>**Build a simple microservice application with Node.js**</u>

**Install Dependencies**
To illustrate how to develop microservices with Node.js, we’ll use the OpenWeather API service. First, create a free account and get your api key.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20epcy12bqz011qgcvur.png)

Create a new folder on your computer, preferably on your desktop for easy access, and name it weathermicroservice. Open weathermicroservice in your code editor and confirm that you have Node.js installed on your computer by running the command below:

`node -v`

If Node.js is not installed, go ahead and download it. In weathermicroservice, run the command below to initialize the package.json:

`npm init -y`

With npm init, you can customize the setting or fields to create the package.json file. On the other hand, npm init -y uses the default setting or fields to create the package.json file.

Now, let’s install the required dependencies with the command below:

`npm i nodemon express dotenv body-parser`

your package.json should now look like this , also just setup the nodemon in the scripts , like in the image below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1srmiuofqv55hs7n4qi.png)

Directly inside the main folder, create a file called server.js. Inside, write the following code:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qf8wx0cum69xtz5i0lc5.png)

server.js is the main file for our basic weather microservice app, as indicated in our package.json file. We’ll create another folder inside the weathermicroservice folder named routes.

Also your filetree should look like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zuxx9t0zphnr1yn5swj.png)

Inside the routes folder, create two files named about.js and weather.js. Inside the about.js file, write the following code:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzvijun4cdb1ekq1ld8g.png)

In the code above, we first require or import the express module, followed by the package.json file, which we assign to the variable named properties.

Then, we invoke the express.Router function. Finally, we implement our GET route, which returns an aboutInfo  containing information about our application, as contained in the package.json file. Remember, we imported our package.json file on the second line of code in the about.js file.

**Creating the client side**

Now that we’re done with the about.js route module, we’ll create the route that handles the weather info request. Before we do that, let’s create the client-side of our application.

First, we’ll create a basic HTML file that receives user input. Under your main project folder, create a folder called client. Inside it, create an index.html file and add the code below to it:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/url9gesetjwzzfa1b46f.png)

This is a basic HTML form that allows you to input your city name and metric units, as well as submit the inputs as a POST request to the weather route.

To create the route that handles the weather info, create a file called weather.js inside the route folder and add the following code to it:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhnqk3daqy9hkltxrlw0.png)

First, we required Express and the native https Node.js modules. We then created an instance of Express and invoked the Express router function. Using the Express instance, we created our first route that sends a response to the client when a request hits the server.

The response should serve a basic form like the one below to the client:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mtp1e9cbdv2jjn322vj.jpeg)


`res.sendFile(__dirname, + "index.html")`

We then send the index.html file to the client. When the submit button is clicked, a POST request is made by the client to the server. The server accesses the body of the request through the request object and saves it into the variables:

`const city = req.body.cityName
const unit = req.body.unit`

Now that we have these parameters, we can easily access the OpenWeather API. The URL below helps us connect to the Weather API:

`const url = "https://api.openweathermap.org/data/2.5/weather?q="+ city + "&amp;appid="+appiKey+"&amp;units="+unit+""`

Using the Node.js native https module, we perform a GET request to the Weather API. We then parse the data from the response body into an object using JSON.parse().

We’ll need the following as part of the response data for our application:

- Temperature
- Weather description: weatherDes
- Icon
- Image
- City Name

Finally, we used the res.write function from the Node.js writeable interface to send the response back to the client. Now, to run this application, run the following command in your root folder:

`npm start`

On your console, you should have something like this below:

```
 npm start

> microservice@1.0.0 start
> nodemon server.js

[nodemon] 3.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js`
Listening on http://localhost:3000
```

Then, go to your favourite browser, brave preferably, and make a request to port 3000:

You should have a response like the one below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5if16607kfio44xissh.jpeg)

In the City name field, type in the name of your city, and in the Unit field, type in metric to convert the default temperature unit to celsius. The default temperature unit in the Weather API is Kelvin.

If you do everything correctly, then you have a response with the temperature reading in your city, and the icon to represent it:

<u>**Conclusion**</u>

In this tutorial, we learned about the important differences between microservices and monolithic applications. We learned why Node.js is a great choice for building microservices, and we ran through an example using the OpenWeather API.

Using a microservice offers flexibility and performance benefits that can’t be achieved with a monolithic application. The event-driven architecture of Node.js makes it a perfect choice for microservices, being fast, highly scalable, and easy to maintain.