forked from reworkd/AgentGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
38 lines (32 loc) · 944 Bytes
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import type { NextRequest } from "next/server";
import { ipAddress } from "@vercel/edge";
import { isAllowed } from "./server/redis";
export const config = {
// Only run the middleware on agent routes
matcher: "/api/agent/:path*",
};
function ipFallback(request: Request) {
const xff = request.headers.get("x-forwarded-for");
return xff
? Array.isArray(xff)
? (xff[0] as string)
: xff.split(",")[0]
: "127.0.0.1";
}
async function shouldRateLimit(request: NextRequest): Promise<boolean> {
const ip = ipAddress(request) || ipFallback(request);
if (!ip) {
return false;
}
return !(await isAllowed(ip));
}
const rateLimitedResponse = () =>
new Response("Too many requests, please try again later.", {
status: 429,
});
// noinspection JSUnusedGlobalSymbols
export async function middleware(request: NextRequest) {
if (await shouldRateLimit(request)) {
return rateLimitedResponse();
}
}