CodeBlanks Logo Icon CodeBlanks

Rate limiting

Learn rate limiting with express-rate-limit.

What is rate limiting?

Rate limiting caps how many requests a client can make in a given time window. This stops malicious clients from overloading the server (DDoS).

In Express the express-rate-limit module is a common choice. rateLimit({ windowMs: 60000, max: 100 }) allows each client at most 100 requests per minute. When the limit is exceeded a 429 Too Many Requests response is returned. It is a basic protection for APIs.

Configuring rateLimit

To use express-rate-limit you first import it with const rateLimit = require("express-rate-limit"), then create a limiter. const limiter = rateLimit({ windowMs: 60000, max: 100 }).

Then you apply it to all routes with app.use(limiter). You can customize the message and show limit info in headers with standardHeaders. It counts requests per IP; behind a proxy you need the trust proxy setting.

Practice Log the type of limiter

Import the express-rate-limit module. Create a limiter (windowMs: 1000, max: 5). Log typeof limiter.

Starter code

index.js
// import the module

// create a limiter

// log its type

Sample solution

index.js
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({ windowMs: 1000, max: 5 });
console.log(typeof limiter);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
express-rate-limit Rate limiter
windowMs Window duration
max Max requests
429 Too many requests

2 Complete the max value

Question
const limiter = rateLimit({ max: ____ })
Answer
const limiter = rateLimit({ max: 5 })

Explanation: max: 5 allows 5 requests per window.

3 What does rate limiting prevent?

  • Excessive requests Correct answer
  • Memory leaks
  • CSS errors
  • Slow responses

Explanation: Rate limiting prevents excessive requests.

All lessons in Advanced