When building REST APIs, one of the common problems developers face is protecting the API from abuse.
Imagine someone starts hitting your server with thousands of requests per minute, your server might crash, your database could slow down, and it becomes a bad experience for everyone.
That's where rate limiting comes in.
In this article, we'll learn:
- What rate limiting is
- Why it's important
- How to implement it in a Node.js (Express) REST API
Letβs get started.
π€ What is Rate Limiting?
Rate limiting means restricting how many requests a client (usually identified by IP address or API key) can make to your server in a certain time window.
For example:
- Allow only 100 requests per 15 minutes per user.
- Block or delay extra requests if the limit is crossed.
This helps prevent spam, DDoS attacks, and overuse of your resources.
π§° Tools Youβll Need
We'll use:
- Node.js with Express for the REST API
- A package called express-rate-limit to handle the rate limiting
π οΈ Step-by-Step: Implementing Rate Limiting
1. Create a New Node.js Project
mkdir rate-limit-api
cd rate-limit-api
npm init -y
npm install express express-rate-limit
2. Basic Express Server
Create a file named index.js
:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Welcome to the API!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
3. Add Rate Limiting Middleware
Now letβs add express-rate-limit
:
const rateLimit = require('express-rate-limit');
// Limit each IP to 100 requests per 15 minutes
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 later.',
});
// Apply to all routes
app.use(limiter);
Your updated index.js
will look like this:
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;
// Rate limiting middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests
message: 'Too many requests from this IP, please try again later.',
});
app.use(limiter);
app.get('/', (req, res) => {
res.send('Welcome to the API!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
π― Testing It
Run the server:
node index.js
Now open your browser and refresh the homepage (http://localhost:3000
) more than 100 times quickly. After the limit is crossed, you'll see the message:
Too many requests from this IP, please try again later.
π‘ Customize It Further
You can adjust the limit for different routes. For example, allow more requests on /public
but restrict /login
:
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // max 5 login attempts
message: 'Too many login attempts. Please try again in 5 minutes.',
});
app.post('/login', loginLimiter, (req, res) => {
res.send('Login route');
});
β Final Tips
- Use environment-based configs: Different limits for dev vs production.
- Consider headers: express-rate-limit adds headers like X-RateLimit-Remaining so clients know how many requests they have left.
- Pair with other security tools: Use rate limiting with helmet, CORS, auth tokens, etc.
π Conclusion
Rate limiting is a simple yet powerful way to protect your REST API from being overwhelmed by too many requests. With just a few lines of code in Node.js and Express, you can safeguard your app and give users a smoother experience.
If you're building public-facing APIs or login systems, add rate limiting today - your server will thank you.
Comments
Please login to publish your comment!
By logging in, you agree to our Terms of Service and Privacy Policy.
No comments here!