DEV Community

TutsCoder
TutsCoder

Posted on • Originally published at tutscoder.com

How to implement rate limiting in nodejs

In this tutorial, we will implement rate limiting in order to prevent the same IP from making too many requests to our API and that will then help us prevent attacks, like denial of services or brute force attacks.

So, here we will implememnt rate limiter as global middlware, so basically the rate limiter will count the number of

requests comming from one IP and then,when thre are too many requets, block these requetsts.

npm install express-rate-limit
const rateLimit = require('express-rate-limit')
// Middleware

const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per window (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the RateLimit-* headers
legacyHeaders: false, // Disable the X-RateLimit-* headers
message: "Too many requests from this IP, please try again after in an hour",
});

// Apply the rate limiting middleware to all requests

app.use("/api", limiter);

Too many requests from this IP, please try again after in an hour

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay