Home  Tech   How to impl ...

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

  1. 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
    
  2. 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;
    
  3. 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

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.

Published on: Jun 13, 2024, 10:16 PM  
 

Comments

Add your comment