How to implement rate limiting in express app using upstash
We can use @upstash/ratelimit
package to implement rate limiting. To use the @upstash/ratelimit
package for rate limiting in a Node.js application, you first need to install the package and set it up correctly. Below are the steps to integrate and use the Ratelimit
class from the @upstash/ratelimit
package in your application.
Step-by-Step Guide
-
Install the Package:
Make sure you have Node.js and npm installed. You can install the
@upstash/ratelimit
package using npm or yarn:npm install @upstash/ratelimit # or yarn add @upstash/ratelimit
-
Import and Configure the Ratelimit Class:
Create a file (e.g.,
rateLimiter.js
) to configure your rate limiter. Here’s an example configuration using the@upstash/ratelimit
package:// rateLimiter.js import { Ratelimit } from '@upstash/ratelimit' import { Redis } from '@upstash/redis' // Initialize Redis client const redis = new Redis({ url: 'your-upstash-redis-url', token: 'your-upstash-redis-token', }); // Initialize the Ratelimit instance const rateLimit = new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(10, '1m'), // 10 requests per minute prefix: 'my-rate-limit', // Prefix for the rate limit keys in Redis }); export default rateLimit;
-
Use the Rate Limiter in Your Application:
Integrate the rate limiter in your application, such as in an Express.js middleware. Here’s an example:
// server.js import express from 'express'; import rateLimit from './rateLimiter'; const app = express(); const rateLimiterMiddleware = async (req, res, next) => { const identifier = req.ip; // Use IP address as the identifier const { success, remaining, reset } = await rateLimit.limit(identifier); res.set('X-RateLimit-Limit', '10'); res.set('X-RateLimit-Remaining', remaining.toString()); res.set('X-RateLimit-Reset', reset.toString()); if (!success) { res.status(429).send('Too many requests - try again later'); return; } next(); }; app.use(rateLimiterMiddleware); app.get('/', (req, res) => { res.send('Hello, world!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Explanation
- Redis Initialization: The
Redis
client from@upstash/redis
is used to connect to your Upstash Redis instance. - Ratelimit Configuration: The
Ratelimit
class is configured to use a sliding window rate limiting strategy, allowing 10 requests per minute per identifier (e.g., IP address). - Middleware Integration: The middleware checks the rate limit for each incoming request based on the client's IP address. If the rate limit is exceeded, it returns a
429 Too Many Requests
response. Otherwise, it proceeds to the next middleware or route handler.
Upstash Credentials
Replace 'your-upstash-redis-url'
and 'your-upstash-redis-token'
with your actual Upstash Redis URL and token, which you can obtain from your Upstash dashboard.