0
0
Node.jsframework~5 mins

Rate limiting in Node.js

Choose your learning style9 modes available
Introduction

Rate limiting helps control how many times someone can use a service in a set time. It stops too many requests that can slow down or break your app.

To stop users from sending too many requests to your server quickly.
To protect your app from being overwhelmed by bots or attacks.
To make sure everyone gets fair access to your service.
To avoid extra costs from too many API calls.
To keep your app running smoothly during high traffic.
Syntax
Node.js
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // time window in milliseconds
  max: 100, // max requests per window per IP
  message: 'Too many requests, please try again later.',
});

app.use(limiter);

windowMs sets the time frame for counting requests.

max is how many requests are allowed in that time.

Examples
Limits to 10 requests per minute per IP.
Node.js
const limiter = rateLimit({ windowMs: 60000, max: 10 });
Limits to 50 requests per 5 minutes with a custom message.
Node.js
const limiter = rateLimit({ windowMs: 5 * 60 * 1000, max: 50, message: 'Slow down!' });
Applies rate limiting only to routes starting with /api/.
Node.js
app.use('/api/', rateLimit({ windowMs: 60000, max: 20 }));
Sample Program

This simple Express server limits each user to 3 requests per minute. If they try more, they get a message telling them to wait.

Node.js
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();

const limiter = rateLimit({
  windowMs: 60000, // 1 minute
  max: 3, // limit each IP to 3 requests per windowMs
  message: 'Too many requests, please wait a minute.',
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Rate limiting works best with user IP addresses to track requests.

Adjust windowMs and max to fit your app's needs.

Use custom messages to inform users politely when they hit the limit.

Summary

Rate limiting protects your app from too many requests.

It controls traffic by setting request limits per time window.

Easy to add in Node.js apps using middleware like express-rate-limit.