From fda81686903125cea02f92b93f686b00dea5f0ea Mon Sep 17 00:00:00 2001 From: JimmyLv Date: Thu, 2 Mar 2023 19:02:10 +0800 Subject: [PATCH] fix: split the rate limit redis --- .example.env | 2 ++ middleware.ts | 16 +++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.example.env b/.example.env index 68fa1e08..2d112c1c 100644 --- a/.example.env +++ b/.example.env @@ -1,4 +1,6 @@ OPENAI_API_KEY= UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= +UPSTASH_RATE_REDIS_REST_URL= +UPSTASH_RATE_REDIS_REST_TOKEN= USER_LICENSE_KEYS= diff --git a/middleware.ts b/middleware.ts index 01f3c6e2..53db2070 100644 --- a/middleware.ts +++ b/middleware.ts @@ -6,19 +6,17 @@ import { Ratelimit } from "@upstash/ratelimit"; const redis = Redis.fromEnv(); const ratelimit = new Ratelimit({ - redis: redis, + redis: new Redis({ + url: process.env.UPSTASH_RATE_REDIS_REST_URL, + token: process.env.UPSTASH_RATE_REDIS_REST_TOKEN, + }), // 速率限制算法 https://github.com/upstash/ratelimit#ratelimiting-algorithms limiter: Ratelimit.fixedWindow(5, "1 d"), - analytics: true // <- Enable analytics + analytics: true, // <- Enable analytics }); export async function middleware(req: NextRequest, ev: NextFetchEvent) { const { bvId, apiKey } = await req.json(); - // TODO: unique to a user (userid, email etc) instead of IP - const identifier = req.ip ?? "127.0.0.3"; - const { success, remaining } = await ratelimit.limit(identifier); - console.log(`======== ip ${identifier}, remaining: ${remaining} ========`); - const result = await redis.get(bvId); if (result) { console.log("hit cache for ", bvId); @@ -33,6 +31,10 @@ export async function middleware(req: NextRequest, ev: NextFetchEvent) { } } + // TODO: unique to a user (userid, email etc) instead of IP + const identifier = req.ip ?? "127.0.0.3"; + const { success, remaining } = await ratelimit.limit(identifier); + console.log(`======== ip ${identifier}, remaining: ${remaining} ========`); if (!apiKey && !success) { return NextResponse.redirect(new URL("/blocked", req.url)); }