DEV Community

Cover image for Implementing Microservice Architecture In Node JS
Lovepreet Singh
Lovepreet Singh

Posted on

Implementing Microservice Architecture In Node JS

📍 Introduction

🙂 As we have discussed in our previous blog "Monolithic vs Microservices: A Practical Approach". But today we're going to implement Microservices Architecture in NodeJS.

👉 You can use any technology like Spring, Python, etc. But we are going to demonstrate using NodeJS.

NodeJS Meme

📍 Directory Structure

🙂 You can find the GitHub Repo (Kindly run npm install in Order, Payment, and API-Gateway directories before running) Here. We have two services Order and Payment with API Gateway.

NodeJS_Microservices
|
---> Order
|
------> server.js (Running on PORT 8081)
|
---> Payment
|
------> server.js (Running on PORT 8082)
|
---> API-Gateway
|
------> server.js (Running on Port 9091)

🔥 The structure of our services looks like this:-

📍 Implementation

Microservices Architecture

🙂 Whenever a client makes a request to the API-Gateway, We have defined some routes (Using prefixes) that redirect the request to the appropriate service (Depends which route is called). Payment and Order services are independent means If one fails other will not be affected.

🔥 Also we can add Auth or Middlewares so that no one can call the services directly or without Authentication. We have implemented a very basic architecture.

  • Order Server.js
const express = require("express");
const app = express();

const port = 8081;
app.get("/order-list", (req,res)=>{
    let response = {
        data: {
            item: [
                {
                    id: 1,
                    name: 'order-1'
                },
                {
                    id: 2,
                    name: 'order-2'
                }
            ]
        }
    };
    res.status(200).json(response);
});
app.get("/", (req,res)=>{
    res.send("Order called");
});

app.listen(port, ()=>{
    console.log("Listening at localhost "+ port);    
})
Enter fullscreen mode Exit fullscreen mode
  • Payment server.js
const express = require("express");
const app = express();

const port = 8082;
app.get("/payment-list", (req,res)=>{
    let response = {
        data: {
            item: [
                {
                    id: 1,
                    name: 'Payment-1'
                },
                {
                    id: 2,
                    name: 'Payment-2'
                }
            ]
        }
    };
    res.status(200).json(response);
});

app.get("/", (req,res)=>{
    res.send("Payment called");
});

app.listen(port, ()=>{
    console.log("Listening at localhost "+ port);    
})
Enter fullscreen mode Exit fullscreen mode
  • API-Gateway
const gateway = require("fast-gateway");

const port = 9001;
const server = gateway({
    routes: [
        {
            prefix: "/order",
            target: "http://localhost:8081/",
            hooks: {}
        },
        {
            prefix: "/payment",
            target: "http://localhost:8082/",
            hooks: {}
        }
    ]
});

server.get('/mytesting', (req,res)=> {
    res.send("Gateway Called");
})

server.start(port).then(server=>{
    console.log("Gateway is running "+port);
})

Enter fullscreen mode Exit fullscreen mode

😌 Now, we can start the services including the gateway

Terminal running microservices

📍 And we can request http://localhost:9001/order Or http://localhost:9001/payment


🙋 Follow for more in-depth tutorials. Right now, I am targeting beginners but soon more advanced things we'll discuss.

Drop your views in the Comment Box. Hope It helps.

Oldest comments (59)

Collapse
 
vaibhav68849256 profile image
Vaibhav Khandare

Helpful

Collapse
 
410nidhi profile image
Nidhi Upasani

Great read

Collapse
 
arpitpatel25 profile image
Arpit Patel

Nice and brief

Collapse
 
itsnitinn profile image
Nitin Sharma

Crisp and nice.

Collapse
 
akcgjc007 profile image
anupam

what is the difference between let and const? 🤔

Collapse
 
rxavio profile image
xavier Rucahobatinya

const is a signal that the identifier won't be reassigned. let is a signal that the variable may be reassigned

Collapse
 
light_seekern profile image
Taha Syed

Very well articulated

Collapse
 
adnanafzal565 profile image
Adnan Afzal

You are using prefix as "/order" so I think your order server.js will have:

app.get("/order"

And not:

app.get("/order-list"

Kindly correct me if I am wrong.

Collapse
 
shifi profile image
Shifa Ur Rehman

True

Collapse
 
lovepreetsingh profile image
Lovepreet Singh

You'll type localhost:9091/order and it will redirect you to the localhost:8081/

Collapse
 
pavanbelagatti profile image
Pavan Belagatti

When I call localhost:9091/order on my local, it I am getting 'page can’t be found' error. Am I doing something wrong?

Thread Thread
 
lovepreetsingh profile image
Lovepreet Singh

Start all the services including order payment and gateway

Collapse
 
murilokaos profile image
Murilo Henrique

Eu creio que não, ele vai ter as rotas com o /order como prefixo, ou seja:

/order e /order/order-list

Collapse
 
mohmmadaslam profile image
Mohmmad Aslam

Very insightful

Collapse
 
brense profile image
Rense Bakker

Nice! I used node-http-proxy in the past to create a gateway, didn't realize that fast-gateway existed, it looks very clean 👍

Collapse
 
lovepreetsingh profile image
Lovepreet Singh

Thanks Rense. Highly appreciate 😊

Collapse
 
maurer profile image
Daniel Maurer

Hello, what tool did you use to make the diagram?

Collapse
 
lovepreetsingh profile image
Lovepreet Singh

I did make it in GoodNotes app in ipad

Collapse
 
hartajsinghdev profile image
Hartaj-Singh-Dev

great

Collapse
 
tlylt profile image
Liu Yongliang

Good demo! For simple routing/gateway it can also be done by setting up a reverse proxy with nginx.

Collapse
 
lovepreetsingh profile image
Lovepreet Singh

Already done in the previous blog

Collapse
 
rihernandez profile image
Richard HC

Coul be interesting implement an authentication service to this architecture in order to understand how it works : api_gateway, auth_service, service1, service2.

Collapse
 
lovepreetsingh profile image
Lovepreet Singh

Ok, Richard Noted. Will do it in our next blog. Or maybe I will leave a reference to follow soon. Thanks for your time 🙂

Collapse
 
timhub profile image
Tech Tim (@TechTim42) • Edited

Some comments may only be visible to logged-in visitors. Sign in to view all comments.