Building an Advanced API Gateway in Node.js, A Step-by-Step Guide with Examples of Rate Limiting and Statistics
First, set up your Node.js project with the Express framework and create a basic API endpoint for handling incoming requests.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Implement rate limiting by using a middleware function that checks the number of requests made by a specific IP address within a certain timeframe. You can use a package like express-rate-limit to handle this.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests, please try again later'
});
// apply the limiter to all requests
app.use(limiter);
Collect statistics on your API's usage by using a middleware function that logs the request method, endpoint, and response status code for each incoming request. You can use a package like morgan to handle this.
const morgan = require('morgan');
app.use(morgan('combined'));
To keep track of all the statistics and also to show the statistics to the client, you can use a package like winston to log all the statistics, which can be saved to a file or a database.
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({
filename: './logs/api.log',
level: 'info'
}),
new winston.transports.Console({
level: 'debug'
})
]
});
app.use(morgan('combined', { stream: { write: (message) => logger.info(message) } }));
To display the statistics, you can create an endpoint that retrieves the statistics from the file or the database and returns them in a JSON format.
app.get('/stats', (req, res) => {
// read statistics from file or database
const stats = {
requests: 1000,
success: 800,
errors: 200
};
res.json(stats);
});
You now have an advanced API gateway that implements rate limiting, collects statistics, and allows clients to view these statistics.