Skip to content
Merged
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
1 change: 0 additions & 1 deletion apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"cors": "^2.8.5",
"drizzle-orm": "^0.40.0",
"express": "^5.0.1",
"express-rate-limit": "^7.5.0",
"http-status-codes": "^2.3.0",
"jsonwebtoken": "^9.0.2",
"morgan": "^1.10.0",
Expand Down
7 changes: 6 additions & 1 deletion apps/backend/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { z, ZodError } from "zod";

const timeSpanType = z
.string()
.regex(/^\d+[smhd]$/, "Invalid format. Use formats like '15m', '1h', '7d'.")
.transform((val) => val as `${number}${"s" | "m" | "h" | "d"}`);

const environmentVariableSchema = z.object({
// Node Environment
NODE_ENV: z.enum(["development", "test", "production"]),
Expand Down Expand Up @@ -70,7 +75,7 @@ const environmentVariableSchema = z.object({
TWILIO_PHONE_NUMBER: z.string(),

// Rate limit
WINDOW_SIZE_IN_MINUTES: z.coerce.number().positive().int().default(15),
WINDOW_SIZE_IN_MINUTES: timeSpanType.default("15m"),
MAX_NUMBER_OF_REQUESTS_PER_WINDOW_SIZE: z.coerce
.number()
.positive()
Expand Down
38 changes: 38 additions & 0 deletions apps/backend/src/middlewares/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response, NextFunction } from "express";
import redis from "@repo/backend/redis";
import { parseTimeSpan, type TimeSpan } from "@repo/backend/utils/time";
import { RateLimitError } from "@repo/backend/utils/errors";

const rateLimitHandler = ({
endpoint = "global",
timeSpan,
limit,
message,
}: {
timeSpan: TimeSpan;
limit: number;
endpoint?: string;
message?: string;
}) => {
return async (request: Request, response: Response, next: NextFunction) => {
const { ip } = request;
const redisId = `rate-limit:${endpoint}/${ip}`;

const requests = await redis.incr(redisId);
if (requests === 1) await redis.expire(redisId, parseTimeSpan(timeSpan));

limit = process.env.NODE_ENV === "development" ? Infinity : limit;
if (requests > limit) {
next(
new RateLimitError(
message ?? "Too many requests, please try again later",
),
);
return;
}

next();
};
};

export default rateLimitHandler;
10 changes: 5 additions & 5 deletions apps/backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import express, { type Express } from "express";
import morgan from "morgan";
import cors from "cors";
import rateLimit from "express-rate-limit";
import cookieParser from "cookie-parser";
import { NotFoundError } from "@repo/backend/utils/errors";
import rootRouter from "@repo/backend/modules";
import errorHandler from "@repo/backend/middlewares/error";
import rateLimitHandler from "@repo/backend/middlewares/rate-limit";

export const createServer = (): Express => {
const app = express();
Expand All @@ -17,10 +17,10 @@ export const createServer = (): Express => {
.use(cookieParser())
.use(cors())
.use(
rateLimit({
windowMs: process.env.WINDOW_SIZE_IN_MINUTES * 60 * 1000,
max: process.env.MAX_NUMBER_OF_REQUESTS_PER_WINDOW_SIZE,
}),
rateLimitHandler({
timeSpan: process.env.WINDOW_SIZE_IN_MINUTES,
limit: process.env.MAX_NUMBER_OF_REQUESTS_PER_WINDOW_SIZE,
})
)
.get("/healthcheck", (_req, res) => {
res.json({
Expand Down
16 changes: 0 additions & 16 deletions package-lock.json

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

Loading