itzamanjain / TypeArena

TypeAreana is a platform where you can show your typing speed and win money
https://type-arena-two.vercel.app
4 stars 3 forks source link

feat: add rate limiting to /signup route #25

Open itzamanjain opened 5 days ago

itzamanjain commented 5 days ago

this is help us to protect our server from multiple request

itzamanjain commented 4 days ago

we could use this for rate limit

const rateLimitStore = new Map();
const RATE_LIMIT_TIME_FRAME = 15 * 60 * 1000; // 15 minutes
const RATE_LIMIT_MAX_REQUESTS = 13; // Max 3 requests per IP per time frame

function rateLimit(request:NextRequest) {
    const ip = request.headers.get('x-forwarded-for') || request.ip ;
    console.log('IP:', ip);

    const now = Date.now();

    if (!rateLimitStore.has(ip)) {
        rateLimitStore.set(ip, { count: 1, lastRequest: now });
    } else {
        const rateLimitData = rateLimitStore.get(ip);
        if (now - rateLimitData.lastRequest > RATE_LIMIT_TIME_FRAME) {
            // Reset the rate limit for the IP if the time frame has passed
            rateLimitStore.set(ip, { count: 1, lastRequest: now });
        } else {
            // Increment the request count for the IP
            rateLimitData.count++;
            rateLimitData.lastRequest = now;

            if (rateLimitData.count > RATE_LIMIT_MAX_REQUESTS) {
                return false; // Rate limit exceeded
            }
        }
    }

    return true; // Within the rate limit
}