Next.js Discord

Discord Forum

Ratelimiting API Route

Unanswered
Tonkinese posted this in #help-forum
Open in Discord
TonkineseOP
Hey,

How can I Ratelimit an API Page from nextjs?
Is there any officiall thing?

Regards

24 Replies

@Tonkinese Hey, How can I Ratelimit an API Page from nextjs? Is there any officiall thing? Regards
you could save identifiers like a key or jus the ip in a hashmap
use ip as the key and the value would be a object with requests and max requests
TonkineseOP
Okay so basically getting the ip, setting a number and if number > 10 for example then dont do anything
requests >= max
deny
TonkineseOP
you are doing this in the middleware or in the route?
u can do this in your api route
have a class that can be instanced and has a getter
as ratelimit
const ratelimit = new Ratelimit()
TonkineseOP
Okay I guess then i am going to look how i do that. I guess it makes sense for login and register api route
ratelimit.getInstance.getHashMap
@Tonkinese keep in mind, that you need a serverfull enviorement, when you want to use this solution. Vercel for example is serverless
TonkineseOP
👍
@Burmese Can we do it in a serverless environment somehow?
Yes, save the data to a server. That can be a database or a cache or …
Burmese
Oh makes sense
@B33fb0n3 <@642807365695176724> keep in mind, that you need a server**full** enviorement, when you want to use this solution. Vercel for example is server**less**
This is not entirely accurate. In memory caching in a serverless env will work, you just have to consider the fact that when your lambda container scales the new one will have an empty cache (or scales down)
Which means your rate limiting isn’t 100%
But for basic api rate limiting for a single user session this is actually not a problem
Because you won’t auto scale horizontally unless you have a lot of concurrent traffic or using edge apis
In other words, ephemeral data in serverless is viable solution if that is acceptable to your use case.