Skip to content

express rate limit

Vijay Pratap edited this page Jul 20, 2024 · 2 revisions

Express Rate Limit

Table of Contents

  1. About Rate Limit
  2. Implementation of Rate Limit

1. About Rate Limit

1.1 What is Rate Limit

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.

1.2 Use Cases of Rate Limit

  • 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.

2. Implementation of Rate Limit

2.1 Setup Fresh NodeJS Project

mkdir express-rate-limit-demo
cd express-rate-limit-demo
npm init -y

2.2 Install Packages expressjs, express-rate-limit

npm install express express-rate-limit

2.3 Create Sample Route

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}`);
});

2.4 Use Rate Limit

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);

2.5 Complete Code Example

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}`);
});