Skip to content

Instantly share code, notes, and snippets.

@lahin31
Created November 14, 2023 05:38
Show Gist options
  • Save lahin31/d3af47927bd865052e42332ab6de8d3e to your computer and use it in GitHub Desktop.
Save lahin31/d3af47927bd865052e42332ab6de8d3e to your computer and use it in GitHub Desktop.
Rate Limit for a Nextjs Serverless API
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