Skip to content

Commit

Permalink
fix: split the rate limit redis
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 2, 2023
1 parent a0ae9c3 commit fda8168
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
2 changes: 2 additions & 0 deletions .example.env
Original file line number Diff line number Diff line change
@@ -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=
16 changes: 9 additions & 7 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>(bvId);
if (result) {
console.log("hit cache for ", bvId);
Expand All @@ -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));
}
Expand Down

1 comment on commit fda8168

@vercel
Copy link

@vercel vercel bot commented on fda8168 Mar 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.