Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Rate limiting function for route handlers

Richie McIlroy03957acf5fef
diff --git a/apps/web/utils/helpers.ts b/apps/web/utils/helpers.ts
index 0ed2c8c85..d9c49534b 100644
--- a/apps/web/utils/helpers.ts
+++ b/apps/web/utils/helpers.ts
@@ -1,5 +1,7 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
+import { type NextRequest } from "next/server";
+import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
export function classNames(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -20,3 +22,41 @@ export function getHeaders(origin: string) {
"Access-Control-Allow-Methods": "GET, OPTIONS",
};
}
+
+const rateLimitMap = new Map();
+
+export function rateLimitMiddleware(
+ limit: number,
+ request: NextRequest | Promise<Response>,
+ headersList: ReadonlyHeaders
+) {
+ const ip = headersList.get("x-forwarded-for");
+ const windowMs = 60 * 1000;
+
+ if (!rateLimitMap.has(ip)) {
+ rateLimitMap.set(ip, {
+ count: 0,
+ lastReset: Date.now(),
+ });
+ }
+
+ const ipData = rateLimitMap.get(ip) as {
+ count: number;
+ lastReset: number;
+ };
+
+ if (Date.now() - ipData.lastReset > windowMs) {
+ ipData.count = 0;
+ ipData.lastReset = Date.now();
+ }
+
+ if (ipData.count >= limit) {
+ return new Response("Too many requests", {
+ status: 429,
+ });
+ }
+
+ ipData.count += 1;
+
+ return request;
+}