Rate limit SolidStart API routes

Hello! I was wondering how I can implement an API rate limit solution with the SolidStart API routes.
7 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Vexcited
VexcitedOP2y ago
Thanks you for the suggestions, will look into it! I need a Redis database for this? I actually want a solution without using any database - I was thinking of using a global._ variable that is used to store the IPs
Vexcited
VexcitedOP2y ago
built something like this and tested with a limit of 2requests every 2seconds and seems like it works
Vexcited
VexcitedOP2y ago
implemented a little debug message and I think that I'm done
Vexcited
VexcitedOP2y ago
hope it helps anyone-
Vexcited
VexcitedOP2y ago
im back just to say that i found a way cleaner way to do it with this package https://www.npmjs.com/package/lambda-rate-limiter
npm
lambda-rate-limiter
Simple in-memory rate-limit for Node.. Latest version: 3.0.1, last published: a year ago. Start using lambda-rate-limiter in your project by running npm i lambda-rate-limiter. There are 5 other projects in the npm registry using lambda-rate-limiter.
Vexcited
VexcitedOP2y ago
(since i use vercel, lambda is my way to go) and my code is now looking like this
const ip = evt.request.headers.get("x-real-ip") || evt.request.headers.get("x-forwarded-for") || "127.0.0.1";
const limit_count = 30;

if (!global._rate_limiter) (
global._rate_limiter = rate_limiter({
interval: 1000 * 2, // 2 seconds.
uniqueTokenPerInterval: 500
})
);

try {
await global._rate_limiter.check(limit_count, ip);
}
catch (count) {
return json({
success: false,
code: ResponseErrorCode.RateLimit,
debug: {
current_count: count,
limit_count
}
}, { status: 429 });
}
const ip = evt.request.headers.get("x-real-ip") || evt.request.headers.get("x-forwarded-for") || "127.0.0.1";
const limit_count = 30;

if (!global._rate_limiter) (
global._rate_limiter = rate_limiter({
interval: 1000 * 2, // 2 seconds.
uniqueTokenPerInterval: 500
})
);

try {
await global._rate_limiter.check(limit_count, ip);
}
catch (count) {
return json({
success: false,
code: ResponseErrorCode.RateLimit,
debug: {
current_count: count,
limit_count
}
}, { status: 429 });
}
Want results from more Discord servers?
Add your server