Skip to content

Commit

Permalink
Testing Rate Limiting for add to cart API #2.
Browse files Browse the repository at this point in the history
  • Loading branch information
david emioma committed Apr 2, 2024
1 parent ebac9f8 commit 5df081b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
16 changes: 12 additions & 4 deletions app/api/cart/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ export async function POST(request: Request) {
);
}

const { success } = await apiRatelimit?.limit(user.id ?? "");
try {
const { success } = await apiRatelimit?.limit(user.id ?? "");

if (!success && process.env.VERCEL_ENV === "production") {
return new NextResponse("Too Many Requests! try again in 1 min", {
status: 429,
});
}
} catch (err) {
console.error("Rate Limiting Error:", err);

if (!success && process.env.VERCEL_ENV === "production") {
return new NextResponse("Too Many Requests! try again in 1 min", {
status: 429,
return new NextResponse("An error occurred. Please try again later.", {
status: 503,
});
}

Expand Down
2 changes: 1 addition & 1 deletion lib/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ export const redis = new Redis({

export const apiRatelimit = new Ratelimit({
redis: redis ?? Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(5, "1 m"),
limiter: Ratelimit.slidingWindow(10, "1 m"),
});

0 comments on commit 5df081b

Please sign in to comment.