Skip to content

Latest commit

 

History

History
84 lines (70 loc) · 2.59 KB

File metadata and controls

84 lines (70 loc) · 2.59 KB
title Analytics
description Analytics helper for recording and aggregating rate limit events.

Analytics in src/analytics.ts wraps @upstash/core-analytics and provides a higher‑level interface tailored to rate limit events. It is created automatically by Ratelimit when analytics: true, but you can also instantiate it directly for custom reporting.

Constructor

new Analytics(config: AnalyticsConfig)

Parameters

Parameter Type Default Description
redis @upstash/redis client Redis REST client used for analytics storage.
prefix string @upstash/ratelimit Namespace for analytics keys.

Methods

extractGeo

extractGeo(req: { geo?: Geo; cf?: Geo }): Geo

Extracts geo metadata from either req.geo (Vercel) or req.cf (Cloudflare). If neither is present, returns an empty object.

Example

const geo = analytics.extractGeo({ cf: { country: "US", city: "NYC" } });

record

record(event: Event): Promise<void>

Records a single event into the events table with identifier, time, success state, and optional geo data.

Example

await analytics.record({
  identifier: "user_123",
  time: Date.now(),
  success: true,
  country: "US"
});

series

series(filter: TFilter, cutoff: number): PromiseAggregate[]>

Aggregates counts over time for a given field (e.g. identifier, country).

getUsage

getUsage(cutoff?: number): PromiseRecord<string, { success: number; blocked: number }>>

Returns allowed vs blocked counts grouped by identifier.

getUsageOverTime

getUsageOverTime(timestampCount: number, groupby: TFilter): PromiseAggregate[]>

Aggregates usage over time for a given field.

getMostAllowedBlocked

getMostAllowedBlocked(timestampCount: number, getTop?: number, checkAtMost?: number): PromiseAggregate[]>

Returns top identifiers by allowed/blocked counts.

Usage with Ratelimit

If you enable analytics in Ratelimit, the library calls analytics.record after each request and attaches the work to the pending promise in the response.

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"),
  analytics: true
});

Related