Firstly we will install express , redis , rete-limiter flexible
npm install express redis rate-limiter flexible
then
we import necessary modules
const express = require('express');
const Redis = require('redis');
const { RateLimiterRedis } = require('rate-limiter-flexible');
in next line create a default Express application
const app = express();
Create a Redis client
```jsx
const redisClient = Redis.createClient({
host: 'localhost',
port: 6379,
});
```
Then :- rate limiter initialize
```jsx
const rateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'rateLimiter',
points: 5, duration: 1, });
```
points: 5 === number of points which we want to allow
duration: 1 === time for window in sec
```jsx
// Middleware to handle rate limiting
const rateLimitMiddleware = (req, res, next) => {
// Get the user's IP address
const userIp = req.ip;
```
```jsx
// Consume a point
rateLimiter
.consume(userIp)
.then(() => {
next(); // Allowed to proceed
})
.catch(() => {
res.status(429).send('Too many requests, please try again later.');
});
};
```
```jsx
to apply use this command
app.use(rateLimitMiddleware);
```
```jsx
then add a sample route
app.get('/', (req, res) => {
res.send('Welcome to the API!');
});
```
```jsx
and in last Start the server
app.listen(3000, () => {
console.log('Server running on [http://localhost:3000](http://localhost:3000/)');
});
```
We can test the rate limiting by sending requests using tools like Postman or URL.
I am using Postman for this
1. Open Postman
2. Set Up the Request
3. Send Multiple Requests
4. Check Rate Limiting Behavior
5. Add Request to Collection:
6. Run and Observe the result
Related Question :How To Implement Caching in Node js Using Redis