ciscoheat / sveltekit-rate-limiter

A modular rate limiter for SvelteKit. Use in password resets, account registration, etc.
MIT License
203 stars 4 forks source link

Q&A: How to get back remaining rates? #8

Closed babakfp closed 4 months ago

babakfp commented 4 months ago

Hi 👋

I'm trying to build a ratelimiter similar to https://anilist.gitbook.io/anilist-apiv2-docs/overview/rate-limiting. My question is, how can I implement "X-RateLimit-Remaining", so the user that accesses the API, can see how many request they have remaining.

This is what I have so far:

import { RetryAfterRateLimiter } from "sveltekit-rate-limiter/server"

const rateLimiter = new RetryAfterRateLimiter({ IP: [1, "m"] })

export const handle = async ({ event, resolve }) => {
    rateLimiter.clear() // TODO: remove this

    const { limited, retryAfter } = await rateLimiter.check(event)

    if (event.url.pathname.startsWith("/api") && limited) {
        const response = new Response("Too Many Requests.", { status: 429 })
        response.headers.set("X-RateLimit-Reset", "0")
        response.headers.set("Retry-After", String(retryAfter))
        return response
    }

    const response = await resolve(event)

    if (event.url.pathname.startsWith("/api")) {
        // I need these to sent back to users that access the API.
        response.headers.set("X-RateLimit-Limit", "90")
        response.headers.set("X-RateLimit-Remaining", "0")
    }

    return response
}

This is the first time that I'm dealing with this sorts of stuff, so feel free to point to all of my mistakes.

Thanks.