SecurityRate limiting (API Routes)
It is recommended to protect your API routes from abuse by rate limiting them. This tutorial will show you how to rate limit your API routes using Upstash.
We will be protecting API routes /api/oneand /api/two. You can replace them with your own API endpoints.
Setup
- Sign up on Upstash
- Create a new Redis database
- Add the
UPSTASH_REDIS_REST_URLandUPSTASH_REDIS_REST_TOKENto your.env.localfile - Install the packages:terminal
- Create a new
middleware.jsfile in the root directory (the same level as the/appfolder) and add the following content:/middleware.jsLoading code...We are rate limiting the user to 5 requests per minute based on their IP using the sliding window algorithm. You can refer to the Upstash ratelimit SDK documentation for more information on customizing it.
- Create a new
/app/blocked/page.jsfile. This is the page the user will be redirected to when they hit the rate limit. Add the following content:/app/blocked/page.js - That's it! You have successfully rate limited the Magic Link sign-ins. Now, when a user hits the rate limit, they will be redirected to the
/blockedpage.