Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rate limiter on all APIs #10 #28

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,42 @@ import Express from "express";
import bodyParser from "body-parser";
import cors from "cors"; // Import cors package

// Basic rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset
import Routes from "./api/routes";
import rateLimit from "express-rate-limit";
import startServer from "./startServer";

const app = new Express();

//added cors to avoid cors error
app.use(cors());

const limiter = rateLimit({
windowMs: 1000, // 1 second window
max: 5, // limit each IP to 5 requests per windowMs (adjust this as needed)
message: "Too many requests from this IP, please try again after a second",
headers: true, // Sends rate limit info in response headers
handler: (req, res) => {
// Custom error response
return res.status(429).json({
error: "Rate limit exceeded",
message:
"You have exceeded the number of allowed requests. Please try again later.",
});
},
});
// apply limit to all request
app.use(limiter);

// log the changes
// app.use((req, res, next) => {
// console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl}`);
// next();
// });

// Support parsing of application/json type post data
app.use(bodyParser.json());
// Rate limiting middleware

// Support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Expand Down
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"helmet": "^3.21.2",
"json2csv": "^5.0.6",
"jsonwebtoken": "^9.0.2",
"express-rate-limit": "^7.4.1",
"mongodb": "^6.8.1",
"mongoose": "^8.6.1",
"nodemailer": "^6.9.15"
Expand Down