Skip to content

Commit

Permalink
fix: add ratelimit to reactions endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
CaliCastle committed May 21, 2023
1 parent 4ac480a commit 50635c7
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions app/api/reactions/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Ratelimit } from '@upstash/ratelimit'
import { revalidateTag } from 'next/cache'
import { type NextRequest, NextResponse } from 'next/server'

Expand All @@ -19,6 +20,18 @@ export async function GET(req: NextRequest) {
await redis.set(getKey(id), [0, 0, 0, 0])
}

const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(30, '10 s'),
analytics: true,
})
const { success } = await ratelimit.limit(getKey(id))
if (!success) {
return new Response('Too Many Requests', {
status: 429,
})
}

return NextResponse.json(value ?? [0, 0, 0, 0])
}

Expand All @@ -32,6 +45,18 @@ export async function PATCH(req: NextRequest) {

const key = getKey(id)

const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(50, '10 s'),
analytics: true,
})
const { success } = await ratelimit.limit(key)
if (!success) {
return new Response('Too Many Requests', {
status: 429,
})
}

let current = await redis.get<number[]>(key)
if (!current) {
await redis.set(key, [0, 0, 0, 0])
Expand Down
8 changes: 8 additions & 0 deletions lib/redis.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'

import { env } from '~/env.mjs'
Expand All @@ -6,3 +7,10 @@ export const redis = new Redis({
url: env.UPSTASH_REDIS_REST_URL,
token: env.UPSTASH_REDIS_REST_TOKEN,
})

// Create a new ratelimiter, that allows 30 requests per 10 seconds
export const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(30, '10 s'),
analytics: true,
})
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@sanity/image-url": "^1.0.2",
"@sanity/ui": "^1.3.3",
"@sanity/vision": "^3.11.1",
"@upstash/ratelimit": "^0.4.3",
"@upstash/redis": "^1.20.6",
"@vercel/analytics": "^1.0.1",
"@vercel/edge-config": "^0.1.11",
Expand Down
20 changes: 20 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 50635c7

Please sign in to comment.