📖 Scenario: You are building a simple Node.js server that needs to protect an API endpoint from too many requests in a short time. This is like a shopkeeper who limits how many customers can enter the shop at once to keep things orderly.
🎯 Goal: Create a basic rate limiting middleware that allows only a certain number of requests per user IP within a time window. This will help prevent abuse and keep the server responsive.
📋 What You'll Learn
Create an object to track request counts per IP
Set a maximum request limit and time window
Write middleware to count requests and block excess
Apply the middleware to a simple Express route
💡 Why This Matters
🌍 Real World
Rate limiting is used in real web servers to prevent abuse, protect resources, and ensure fair use by limiting how often users can make requests.
💼 Career
Understanding rate limiting is important for backend developers and DevOps engineers to build secure and reliable APIs.
Progress0 / 4 steps
1
Create the request tracking object
Create an empty object called requestCounts to store the number of requests per IP address.
Node.js
Hint
Think of requestCounts as a notebook where you write down how many times each visitor has knocked on your door.
2
Set the rate limit configuration
Create two constants: MAX_REQUESTS set to 5 and WINDOW_MS set to 60000 (which is 60 seconds).
Node.js
Hint
These constants are like the rules: only 5 knocks allowed per minute.
3
Write the rate limiting middleware
Write a middleware function called rateLimiter that takes req, res, and next. Inside, get the IP from req.ip. If the IP is not in requestCounts, add it with a count of 1 and set a timeout to reset it after WINDOW_MS. If it is, increment the count. If the count exceeds MAX_REQUESTS, respond with status 429 and message 'Too many requests'. Otherwise, call next().
Node.js
Hint
This function is like a gatekeeper counting knocks and deciding who can enter.
4
Apply the middleware to an Express route
Create an Express app using express(). Use the rateLimiter middleware on a GET route at /api/data that responds with JSON { message: 'Success' }. Export the app.
Node.js
Hint
This step connects your gatekeeper to the door of your API.
Practice
(1/5)
1. What is the main purpose of rate limiting in a Node.js application?
easy
A. To store user data securely
B. To speed up the server response time
C. To control the number of requests a user can make in a set time
D. To automatically restart the server on errors
Solution
Step 1: Understand rate limiting concept
Rate limiting restricts how many requests a user can send to prevent overload.
Step 2: Identify the main goal in Node.js apps
It protects the app by limiting requests per time window, avoiding abuse.
Final Answer:
To control the number of requests a user can make in a set time -> Option C
Quick Check:
Rate limiting = request control [OK]
Hint: Rate limiting controls request count per time window [OK]
Common Mistakes:
Confusing rate limiting with speeding up server
Thinking it stores user data
Assuming it restarts the server automatically
2. Which of the following is the correct way to import the express-rate-limit middleware in a Node.js app?
easy
A. require rateLimit from 'express-rate-limit';
B. const rateLimit = require('express-rate-limit');
C. const rateLimit = import('express-rate-limit');
D. import rateLimit from 'express-rate-limit';
Solution
Step 1: Identify import syntax in Node.js
Node.js commonly uses CommonJS syntax with const rateLimit = require('express-rate-limit'); unless using ES modules.
Step 2: Check each option for syntax correctness
const rateLimit = require('express-rate-limit'); uses correct CommonJS require syntax; import rateLimit from 'express-rate-limit'; is ES module syntax which requires specific setup.
Final Answer:
const rateLimit = require('express-rate-limit'); -> Option B
windowMs expects a number representing milliseconds, not a string.
Step 2: Identify the error in the code
windowMs is given as 'one minute' (string), which causes incorrect behavior or error.
Final Answer:
windowMs should be a number, not a string -> Option A
Quick Check:
windowMs type = number [OK]
Hint: windowMs must be a number, not quoted string [OK]
Common Mistakes:
Passing windowMs as string
Confusing max type
Thinking app.use can't use middleware
5. You want to apply rate limiting only to API routes starting with /api/ in your Express app. Which code snippet correctly applies the limiter only to those routes?
hard
A. app.use('/api/', limiter);
B. app.use(limiter);
C. app.use('/api/*', limiter);
D. app.use('/api', limiter);
Solution
Step 1: Understand Express route prefix matching
Using app.use('/api', limiter); applies middleware to all routes starting with '/api'.
Step 2: Evaluate other options
app.use('/api', limiter); correctly applies limiter to all routes starting with '/api'. app.use('/api/', limiter); applies only to routes starting with '/api/' (with trailing slash), which may exclude '/api' itself.
Final Answer:
app.use('/api', limiter); -> Option D
Quick Check:
Prefix '/api' applies limiter correctly [OK]
Hint: Use app.use('/api', limiter) for route-specific limiting [OK]
Common Mistakes:
Applying limiter globally by mistake
Using invalid route patterns
Confusing trailing slash effects
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.