Rate Limit
Better Auth includes a built-in rate limiter to help manage traffic and prevent abuse. By default, in production mode, the rate limiter is set to:
- Window: 60 seconds
- Max Requests: 100 requests
You can easily customize these settings by passing the rateLimit object to the betterAuth function.
In addition to the default settings, Better Auth provides custom rules for specific paths. For example:
/sign-in/email
: Is limited to 3 requests within 10 seconds.
In addition, plugins also define custom rules for specific paths. For example, twoFactor
plugin has custom rules:
/two-factor/verify
: Is limited to 3 requests within 10 seconds.
These custom rules ensure that sensitive operations are protected with stricter limits.
Configuring Rate Limit
Rate Limit Window
You can also pass custom rules for specific paths.
Storage
By default, rate limit data is stored in memory, which may not be suitable for many use cases, particularly in serverless environments. To address this, you can use a database, secondary storage, or custom storage for storing rate limit data.
Using Database
Make sure to run migrate
to create the rate limit table in your database.
Using Secondary Storage
If a Secondary Storage has been configured you can use that to store rate limit data.
Custom Storage
If none of the above solutions suits your use case you can implement a customStorage
.
Handling Rate Limit Errors
When a request exceeds the rate limit, Better Auth returns the following header:
X-Retry-After
: The number of seconds until the user can make another request.
To handle rate limit errors on the client side, you can manage them either globally or on a per-request basis. Since Better Auth clients wrap over Better Fetch, you can pass fetchOptions
to handle rate limit errors
Global Handling
Per Request Handling
Schema
If you are using a database to store rate limit data you need this schema:
Table Name: rateLimit
Field Name | Type | Key | Description |
---|---|---|---|
key | string | Unique identifier for each rate limit key | |
count | integer | - | Time window in seconds |
lastRequest | bigint | - | Max requests in the window |