An API gateway acts like a front door for all client requests to your backend services. It helps manage, secure, and route these requests easily.
API gateway concept in Express
const express = require('express'); const app = express(); // Middleware to handle authentication app.use((req, res, next) => { // check auth next(); }); // Route to service A app.use('/serviceA', (req, res) => { // forward request to service A }); // Route to service B app.use('/serviceB', (req, res) => { // forward request to service B }); app.listen(3000);
This example shows a simple API gateway using Express.js.
Middleware can be used to add common features like authentication or logging.
app.use('/users', (req, res) => {
// forward to user service
});app.use('/orders', (req, res) => {
// forward to order service
});app.use((req, res, next) => {
console.log(`Request to ${req.url}`);
next();
});This is a simple API gateway using Express and http-proxy.
It logs every request, then forwards requests starting with /users to a user service on port 4000, and requests starting with /orders to an order service on port 5000.
const express = require('express'); const httpProxy = require('http-proxy'); const app = express(); const apiProxy = httpProxy.createProxyServer(); // Middleware for simple logging app.use((req, res, next) => { console.log(`Incoming request: ${req.method} ${req.url}`); next(); }); // Route /users to User Service app.all('/users/*', (req, res) => { apiProxy.web(req, res, { target: 'http://localhost:4000' }); }); // Route /orders to Order Service app.all('/orders/*', (req, res) => { apiProxy.web(req, res, { target: 'http://localhost:5000' }); }); app.listen(3000, () => { console.log('API Gateway listening on port 3000'); });
API gateways help keep backend services simple by handling common tasks centrally.
Use proxy libraries like http-proxy to forward requests easily.
Be careful to handle errors and timeouts in the gateway to avoid client confusion.
An API gateway is a single entry point for multiple backend services.
It helps with routing, security, logging, and request management.
Express with proxy middleware is a common way to build a simple API gateway.