Created
November 14, 2023 05:38
-
-
Save lahin31/d3af47927bd865052e42332ab6de8d3e to your computer and use it in GitHub Desktop.
Rate Limit for a Nextjs Serverless API
This file contains 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
import { LRUCache } from 'lru-cache'; | |
const rateLimit = (options) => { | |
const tokenCache = new LRUCache({ | |
max: options?.uniqueTokenPerInterval || 500, | |
ttl: options?.interval || 60000, | |
}) | |
return { | |
check: (res, limit, token) => | |
new Promise((resolve, reject) => { | |
const tokenCount = (tokenCache.get(token)) || [0] | |
if (tokenCount[0] === 0) { | |
tokenCache.set(token, tokenCount) | |
} | |
tokenCount[0] += 1 | |
const currentUsage = tokenCount[0] | |
const isRateLimited = currentUsage >= limit | |
res.setHeader('X-RateLimit-Limit', limit) | |
res.setHeader( | |
'X-RateLimit-Remaining', | |
isRateLimited ? 0 : limit - currentUsage | |
) | |
return isRateLimited ? reject("Too many request. Please try after some time.") : resolve() | |
}), | |
} | |
} | |
export default rateLimit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment