-
Notifications
You must be signed in to change notification settings - Fork 13
express rate limit
Vijay Pratap edited this page Jul 20, 2024
·
2 revisions
Rate limiting is a way to control how often a user can make requests to a server. It helps stop misuse, protect against attacks, and make sure resources are used fairly.
- Prevent Abuse: Stop APIs from being overloaded by too many requests from one user.
- Enhance Security: Reduce the risk of attacks by limiting how many requests an IP address can make.
- Resource Management: Ensure fair use of resources by controlling the rate of requests.
mkdir express-rate-limit-demo
cd express-rate-limit-demo
npm init -y
npm install express express-rate-limit
Create a file named server.js
and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Welcome to Express Rate Limit Demo');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Add rate limiting middleware to the sample route:
const rateLimit = require('express-rate-limit');
// Define rate limiting rule
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again after 15 minutes',
});
// Apply rate limiting middleware to all requests
app.use(limiter);
Here is the complete code combining all steps:
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
app.use(express.json());
const PORT = 3000;
// Define rate limiting rule
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again after 15 minutes',
});
// Apply rate limiting middleware to all requests
app.use(limiter);
app.get('/', (req, res) => {
res.send('Welcome to Express Rate Limit Demo');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});