API Gateway for Microservices in JavaScript: Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Your Project Needs an API Gateway in JavaScript?

\n\n

Imagine your backend is a huge shopping mall. Inside it, there are dozens of stores (microservices): one sells books, another sells clothes, a third sells electronics. Each store has its own entrance, its own rules, and its own language. Now imagine that a visitor (client application) has to go through all these entrances just to buy one t-shirt. Chaos, right?

\n\n

In the world of web development, this problem is solved by API Gateway — a single entry point for all microservices. It's like a mall administrator: it directs requests, checks tickets (tokens), collects data from different stores, and returns a ready response to the client. And today we'll break down how to write such a gateway in pure JavaScript using Node.js.

\n\n

This article will be useful both for beginners who are just getting familiar with microservice architecture and for experienced developers who want to see working code examples. Let's go!

\n\n

What is an API Gateway and Why Do You Need It?

\n\n

API Gateway is a server component that acts as an intermediate layer between the client and internal services. It handles:

\n
    \n
  • Routing — directs requests to the appropriate microservice.
  • \n
  • Authentication and authorization — checks whether the user has access.
  • \n
  • Data aggregation — collects responses from multiple services into one.
  • \n
  • Rate limiting — protects the backend from overloads.
  • \n
  • Protocol transformation — for example, converts REST to GraphQL.
  • \n
\n\n

For JavaScript services (especially on Node.js), API Gateway is a natural choice. It is easily written with Express, Koa, or Fastify, and most importantly, it allows you to maintain a consistent code style throughout the project.

\n\n

Designing the API Gateway Structure on Node.js

\n\n

Before writing code, let's define the architecture. Let's say we have three microservices:

\n
    \n
  • users-service — user management (port 3001).
  • \n
  • orders-service — orders (port 3002).
  • \n
  • products-service — product catalog (port 3003).
  • \n
\n\n

The client (frontend) only accesses the Gateway on port 8080. The Gateway itself decides where to route the request.

\n\n

Step 1. Basic Express Setup

\n\n

Let's create a new project and install dependencies:

\n
mkdir api-gateway\ncd api-gateway\nnpm init -y\nnpm install express http-proxy-middleware dotenv
\n\n

Now let's write a simple Gateway that proxies requests to services:

\n
// gateway.js\nconst express = require('express');\nconst { createProxyMiddleware } = require('http-proxy-middleware');\nrequire('dotenv').config();\n\nconst app = express();\nconst PORT = process.env.PORT || 8080;\n\n// Routes for microservices\napp.use('/users', createProxyMiddleware({\n  target: 'http://localhost:3001',\n  changeOrigin: true,\n}));\n\napp.use('/orders', createProxyMiddleware({\n  target: 'http://localhost:3002',\n  changeOrigin: true,\n}));\n\napp.use('/products', createProxyMiddleware({\n  target: 'http://localhost:3003',\n  changeOrigin: true,\n}));\n\napp.listen(PORT, () => {\n  console.log(`API Gateway running on port ${PORT}`);\n});
\n\n

That's it! Now any request to /users is automatically redirected to users-service. But this is just the beginning. A real Gateway should do more.

\n\n

Adding Authentication and Token Verification

\n\n

One of the main tasks of API Gateway is centralized authentication. Instead of checking JWT in each microservice, we do it once in the gateway.

\n\n

Let's add middleware for token verification:

\n
// middleware/auth.js\nconst jwt = require('jsonwebtoken');\n\nconst authMiddleware = (req, res, next) =>                

Blogs

Book Recommendations