Rate Limits (API Calls)
For plans that introduce a rate limit (e.g. allowing a user to upload 50 files per month), it’s recommended to limit the number of API calls a user can perform in a given time frame based on their IP address. In this example, we’ll be limiting it to 5 API calls per minute using Upstash.
You can find an example of how the middleware.ts
file should look like at the end of this
page.
-
You can create a new Upstash account here.
-
Create a Redis database.
-
In the details section of the dashboard, get the
UPSTASH_REDIS_REST_URL
andUPSTASH_REDIS_REST_TOKEN
. -
Let’s now update the following variables inside the
.env.local
in the codebase:
In the codebase, run the following command to install the @upstash/ratelimit package:
In the middleware.ts file, add an RATE_LIMITED_URLS arr outside of the middleware function. This arr contains the URLs that will be rate limited.
Then, initialise the redis client with the .env variables we just copied:
You can now add the rateLimit outside of the middleware function. In our case, we’ll be limiting it to 5 API calls per minute (60 seconds). If a user makes more than 5 API calls in a minute, a 429 response will be returned.
You’ll just have to add this if statement to check if the URL is rate limited and return the appropriate response and then we’re done.
Please add this if statement inside the middleware function BUT before the
supabaseClient.auth.getUser()
function. Otherwise, the rate limit will not work as it will be
executed after all the API calls have been made.
Here’s an example of how the middleware.ts file should look like: