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_URL and UPSTASH_REDIS_REST_TOKEN to your .env.local file
  • Install the packages:
    terminal
  • Create a new middleware.js file in the root directory (the same level as the /app folder) and add the following content:
    /middleware.js
    Loading 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.js file. 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 /blocked page.