SecurityRate limiting (Magic Links)

NextAuth does not have a built-in functionality to rate limit magic link emails.

Instead, you can use a service like Upstash to secure your /api/auth/signin/email endpoint (responsible for signing up with magic links).

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.