A very Simple Rate Limiting App ( Node.JS )

●2 ●4
calendar_today • schedule1 min read
enter code here

const express = require("express");

const app = express();

const requests = new Map();

const LIMIT = 5;
const WINDOW = 60 * 1000; // 1 minute

app.use((req, res, next) => {
  const ip = req.ip;
  const now = Date.now();

  let data = requests.get(ip);

  // First request or expired time window
  if (!data || now - data.startTime >= WINDOW) {
    data = {
      count: 1,
      startTime: now,
    };

    requests.set(ip, data);
    return next();
  }

  // Rate limit exceeded
  if (data.count >= LIMIT) {
    return res.status(429).json({
      message: "Too many requests. Try again later.",
    });
  }

  data.count++;
  next();
});

app.get("/", (req, res) => {
  res.json({ message: "Request successful!" });
});

app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

Want more #backend & #nodejs deep dives?

Join 6,126+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

3 Comments

2 votes
0
1 vote

More Posts

Stop Turning Every REST Endpoint into an MCP Tool: A Better Approach to AI Tool Design

zeekwrites - Nov 30

XML Sitemap Generator: What Broke in a 52,500-URL Node.js Test

danielmartintech - Nov 16

How to Configure Rate Limiting with a WAF Without Guessing the Ceiling

Muzilla - Oct 25

How to Configure Rate Limiting with a WAF: A Checklist Before You Enforce Limits

Lia - Oct 25

Building a Robust Webhook Handler in Node.js: Validation, Queuing, and Retry Logic

Dumebi Okolo - Apr 7
chevron_left
152 Points • 6 Badges
1Posts
0Comments

Commenters (This Week)

9 comments
4 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!