Skip to content

Commit ec06479

Browse files
refactor: replace custom rate limiter with express-rate-limit
1 parent b225132 commit ec06479

File tree

3 files changed

+42
-12
lines changed

3 files changed

+42
-12
lines changed

dev-server/index.js

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import formidable from "formidable";
1+
import cors from "cors";
22
import express from "express";
3+
import rateLimit from "express-rate-limit";
4+
import formidable from "formidable";
35
import fs from "fs";
46
import http from "http";
57
import https from "https";
6-
import cors from "cors";
7-
import path from "path";
88
import os from "os";
9+
import path from "path";
910
import { fileURLToPath } from "url";
1011

1112
const __filename = fileURLToPath(import.meta.url);
@@ -23,17 +24,15 @@ if (!fs.existsSync(distPath)) {
2324

2425
const app = express();
2526

26-
// Rate limit to 100 req/min per IP (dev-only implementation)
27-
const rateLimit = new Map();
28-
setInterval(() => rateLimit.clear(), 60000); // Clear every minute to prevent memory growth
29-
app.use((req, res, next) => {
30-
const ip = req.ip;
31-
const count = (rateLimit.get(ip) || 0) + 1;
32-
rateLimit.set(ip, count);
33-
if (count > 100) return res.status(429).send("Too many requests");
34-
next();
27+
// Rate limiting
28+
const limiter = rateLimit({
29+
windowMs: 15 * 60 * 1000, // 15 minutes
30+
max: 100, // Limit each IP to 100 requests per windowMs
31+
message: "Too many requests from this IP, please try again later.",
3532
});
3633

34+
app.use(limiter);
35+
3736
app.use(
3837
cors({
3938
origin: (origin, callback) => {

package-lock.json

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"cors": "^2.8.5",
5656
"dynamsoft-capture-vision-bundle": "3.2.4000",
5757
"express": "^4.21.2",
58+
"express-rate-limit": "^8.2.1",
5859
"formidable": "^3.5.2",
5960
"rollup": "^4.9.5",
6061
"rollup-plugin-dts": "^6.1.1",

0 commit comments

Comments
 (0)