0
0
Expressframework~5 mins

Rate limiting with express-rate-limit

Choose your learning style9 modes available
Introduction

Rate limiting helps protect your web app from too many requests at once. It stops overload and keeps your app running smoothly.

To stop users from sending too many requests and slowing down your server.
To protect login pages from repeated password guessing.
To limit API usage for free users in a service.
To prevent spam or abuse on forms or endpoints.
To keep your server stable during traffic spikes.
Syntax
Express
import rateLimit from 'express-rate-limit';

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

app.use(limiter);

windowMs sets the time window for counting requests.

max is the max number of requests allowed in that window.

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

This Express app limits each IP to 5 requests every 15 minutes. If exceeded, it sends a friendly error message.

Express
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // limit each IP to 5 requests per windowMs
  message: 'Too many requests, please try again later.',
});

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 by tracking requests per IP address.

You can customize the error message to be user-friendly.

Use rate limiting especially on login and API routes to improve security.

Summary

Rate limiting protects your app from too many requests at once.

Use express-rate-limit to easily add limits in Express.

Set windowMs and max to control request limits.