Last active
April 23, 2025 04:45
-
-
Save Eddie2111/e0df618cff4a29b5db98f7e135becf3c to your computer and use it in GitHub Desktop.
Rate-limiting-util_for_next-auth.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// !Important: DO NOT IMPLEMENT THIS ON large scale app | |
// this is an implementation for token bucket algorithm | |
const tokenBuckets = new Map(); | |
const RATE_LIMIT = 3; | |
const INTERVAL = 3 * 60 * 1000; | |
export function allowRequest(userId: string) { | |
const now = Date.now(); | |
if (!tokenBuckets.has(userId)) { | |
tokenBuckets.set(userId, { lastRefill: now, tokens: RATE_LIMIT }); | |
} | |
const bucket = tokenBuckets.get(userId); | |
const elapsed = now - bucket.lastRefill; | |
const tokensToAdd = Math.floor(elapsed / INTERVAL); | |
// Refill tokens | |
if (tokensToAdd > 0) { | |
bucket.tokens = Math.min(RATE_LIMIT, bucket.tokens + tokensToAdd); | |
bucket.lastRefill = now; | |
} | |
if (bucket.tokens > 0) { | |
bucket.tokens -= 1; | |
return true; | |
} | |
return false; | |
} | |
/* | |
// to implement this in the callback, | |
if (!allowRequest(user.id)) { | |
console.log("Rate limit exceeded for user:", user.id); | |
return session; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment