Skip to content

Commit

Permalink
Fixing rate limit for API routes.
Browse files Browse the repository at this point in the history
  • Loading branch information
david emioma committed Mar 31, 2024
1 parent b507502 commit 3826d85
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
12 changes: 3 additions & 9 deletions app/api/cart/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import prismadb from "@/lib/prisma";
import { redis } from "@/lib/redis";
import { UserRole } from "@prisma/client";
import { NextResponse } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { apiRatelimit } from "@/lib/redis";
import { currentRole, currentUser } from "@/lib/auth";
import { CartItemSchema } from "@/lib/validators/cart-item";

const cartRatelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(5, "1 m"),
});

export async function POST(request: Request) {
try {
//Check if there is a current user
Expand All @@ -33,9 +27,9 @@ export async function POST(request: Request) {
);
}

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

if (!success) {
if (!success && process.env.VERCEL_ENV === "production") {
return new NextResponse("Too Many Requests! try again in 1 min", {
status: 429,
});
Expand Down
5 changes: 5 additions & 0 deletions lib/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,8 @@ export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL as string,
token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
});

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

0 comments on commit 3826d85

Please sign in to comment.