Reputation: 15
is there a way to use different rate limit for each api key in express nodejs?
for example api key "guest" has a rate limit of 500 requests per day and api key "key" has a rate limit of 1000 requests per day.
Upvotes: 0
Views: 1632
Reputation: 1
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Define rate limit middleware for API1
const api1Limiter = rateLimit({
max: 50, // Maximum requests
windowMs: 60 * 60 * 1000, // 1 hour window
message: 'Too many requests from this IP for API1, please try again in an hour!',
});
// Define rate limit middleware for API2
const api2Limiter = rateLimit({
max: 100, // Maximum requests
windowMs: 60 * 60 * 1000, // 1 hour window
message: 'Too many requests from this IP for API2, please try again in an hour!',
});
// Apply rate limit middleware to specific routes
app.use('/api/api1', api1Limiter);
app.use('/api/api2', api2Limiter);
// Your API routes go here...
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Upvotes: 0
Reputation: 275
the simple solution is to use an npm package called express-rate-limit, it's a popular one and express recommend to use it.
If the package doesn't work for you, it can be implemented using redis, redis is a memory database, so you can create a record with a sliding time. When a request come in you can update or create the record, if the limit was reached you block the request, that logic can be implemented in a middleware.
Upvotes: 1