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.
Practice
API gateway in a system using Express?Solution
Step 1: Understand the role of API gateway
An API gateway acts as a single entry point that routes client requests to appropriate backend services.Step 2: Eliminate incorrect roles
Storing data, replacing databases, or serving static files are not responsibilities of an API gateway.Final Answer:
It acts as a single entry point to route requests to multiple backend services. -> Option CQuick Check:
API gateway = single entry point [OK]
- Thinking API gateway stores data
- Confusing API gateway with database
- Assuming it serves static files directly
Solution
Step 1: Identify middleware for proxying requests
Thehttp-proxy-middlewarepackage is used to forward requests from the gateway to backend services.Step 2: Differentiate from other middleware
express.static()serves static files,body-parserparses request bodies, andcorsmanages cross-origin requests, none forward requests.Final Answer:
http-proxy-middleware -> Option AQuick Check:
Proxy middleware = http-proxy-middleware [OK]
- Using express.static() to proxy requests
- Confusing body-parser with proxying
- Assuming cors forwards requests
/api/users?
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api/users', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true }));
app.listen(3000);Solution
Step 1: Analyze the proxy middleware setup
The middleware forwards requests matching/api/userstohttp://localhost:5000, preserving the path.Step 2: Understand request forwarding behavior
The request/api/userson port 3000 is proxied tohttp://localhost:5000/api/users.Final Answer:
The request is forwarded to http://localhost:5000/api/users -> Option DQuick Check:
Proxy forwards /api/users to target URL [OK]
- Assuming Express serves the request itself
- Expecting 404 without backend running
- Confusing CORS blocking with proxy behavior
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api', createProxyMiddleware({ target: 'http://localhost:4000' }));
app.listen(3000);
// Client requests /api/users but gets no responseSolution
Step 1: Check proxy middleware options
WithoutchangeOrigin: true, the Host header sent to backend remains the gateway's, which may cause backend to reject requests.Step 2: Verify other parts
The target URL and path are correct, and app listens on port 3000, so those are not errors.Final Answer:
Missing changeOrigin: true causes backend to reject requests -> Option AQuick Check:
changeOrigin fixes Host header issues [OK]
- Ignoring changeOrigin option
- Assuming wrong target URL without checking
- Thinking app.listen is missing
Solution
Step 1: Identify routing and logging needs
The API gateway must route requests to multiple backends and log method and URL of each request.Step 2: Choose appropriate middleware
http-proxy-middlewarehandles routing, and a custom Express middleware can log requests before proxying.Step 3: Eliminate incorrect options
express.static()serves static files only, backend routing skips gateway, andbody-parserparses bodies but does not route or log.Final Answer:
Use http-proxy-middleware for routing and add a custom middleware before it to log requests. -> Option BQuick Check:
Proxy + custom middleware = routing + logging [OK]
- Using express.static() for routing
- Skipping gateway for routing
- Confusing body-parser with routing
Ready to prove it?
Pass the test and this pattern moves unknown
