Rate Limiting in NextJs with Middleware, Vercel KV Storage & Upstash
Vložit
- čas přidán 2. 08. 2024
- In this video, we'll look at rate limiting your NextJs application using edge middleware functions, Vercel KV (Kay value storage), and the Upstash rate limiting package.
👉🏼 The Ultimate NextJs Course (75% Off)
→ www.hamedbahram.io/courses/ne...
👉🏼 Project source code
→ github.com/HamedBahram/next-r...
👉🏼 Vercel KV Quickstart
→ vercel.com/docs/storage/verce...
👉🏼 Upstash Rate Limit package
→ github.com/upstash/ratelimit-js
👉🏼 Work with me
→ www.hamedbahram.io/hire - Věda a technologie
THank you so much hamed
You are welcome!
Hey great video , how can i rate limit a server action?
That's a good question! you can implement the same logic inside the server action and limit the response based on the user specific ID or the request.
I'm confused; does this really help? If we're doing rate limiting at our own application level, the requests will be considered traffic to our application, and we WILL be charged for those.
Also, we're redirecting again at our own app level, so technically they could [D]DOS us by sending millions of requests.
In my mind, the rate limiting part should be done BEFORE traffic reaches our app to avoid charges and our sever going down
Am I missing something?
That's a good question, you can apply rate limiting at different layers such as a proxy server before you reach your application server, here we're using the edge middleware which runs before and separate from the application (nextjs) server. As far as the response, it's up to you how to handle; you can block with a 429 response instead of redirecting, this was just an example.
Thanks, that's true. My main concern is that it is OUR part of the infra that's handling things
The middleware is still running as part of our application, so if someone starts constantly sending requests, and say we're charged based on RPS, they can easily bankrupt us!
and how can i rate limit all my application routes?
Without the config matcher, the middleware function runs for every request. Read more here to exclude static paths from the running the middleware → nextjs.org/docs/app/building-your-application/routing/middleware#matcher
Hey Hamed my kv daily request keep getting exceeded. Just 3 users and its exceeding 3000 limit
Look at your implementation. You can clone my code and compare.
@@hamedbahram Thanks for your reply hamed.......Luv your content and that problem I changed kv to redis, Now its give me 10k dailylimit
Is it work without vercel? It's paid
You can use it on the free hobby plan as well.