Skip to main content

Implement a rate limiting on Spells

You may want to restrain your users accessing your Spell, especially if they are exposed publicly.

Implement a rate limiting based on IP address

This code will allow you to implement a rate limiting based on user's IP address with a limit of requests every day (understand for 24h starting at the first request).

You can customize the number of requests allowed every day by changing the REQUESTS_PER_DAY variable's value.

//Code to create a rate limiting by IP
const REQUESTS_PER_DAY = 30;
const userIp = params.headers["x-forwarded-for"];

const limitedIps = (await metaStorage.get("rate_limiting")) || {};

if (limitedIps[userIp]) {
//Reset limitation
if (dayjs().diff(limitedIps[userIp].firstDate, "hours") > 24) {
limitedIps[userIp] = {
firstDate: dayjs().toDate(),
requests: 1,
};
} else if (limitedIps[userIp].requests > REQUESTS_PER_DAY) {
//User has already consumed all allow requests
return {
success: false,
message: "You have already exceeded all your requests for the day",
};
} else {
//Increment requests
limitedIps[userIp].requests++;
}
} else {
limitedIps[userIp] = {
firstDate: dayjs().toDate(),
requests: 1,
};
}

await metaStorage.set("rate_limiting", limitedIps);