Skip to main content
Unkey automatically captures detailed analytics for every API key verification, giving you real-time visibility into how your API is being used, who’s using it, and when anomalies occur.

What Gets Tracked

Every key verification generates analytics data:

Verification events

Successful and failed verification attempts with timestamps and outcomes

Usage patterns

Request frequency, peak times, and traffic trends per key or identity

Rate limit violations

When keys hit rate limits and which limits are being exceeded

Credit consumption

Usage limit tracking — how many credits remain and when they’re depleted

Geographic distribution

Where requests are coming from globally (by region)

Error patterns

Failed verifications: expired keys, disabled keys, insufficient permissions

Dashboard Analytics

Access analytics through the Unkey dashboard:
1

Navigate to Analytics

Sign into app.unkey.com and click Analytics in the sidebar
2

Select your API

Choose which API to analyze from the dropdown
3

Choose time range

Filter by last 24 hours, 7 days, 30 days, or custom date range

Available Views

High-level metrics:
  • Total verifications (successful + failed)
  • Success rate percentage
  • Active keys count
  • Top consumers by volume
  • Verification trends over time
Use this to monitor overall API health and identify growth patterns.

Verification Logs

View detailed logs of every verification attempt:
  1. Go to Keys in the dashboard
  2. Click on any key
  3. Navigate to the Verifications tab
Each log entry shows:
  • Timestamp (with millisecond precision)
  • Outcome (VALID, RATE_LIMITED, etc.)
  • Request metadata (if provided during verification)
  • Identity info (if key is linked)
  • Rate limit state
  • Credits consumed

Programmatic Analytics

Query analytics data programmatically via the Unkey API.
The Analytics API is available on Pro and Enterprise plans. It requires a root key with analytics.query permission.
// Get verification count for last 30 days
const response = await fetch("https://api.unkey.com/v1/analytics.getVerifications", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.UNKEY_ROOT_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    apiId: "api_...",
    start: Date.now() - 30 * 24 * 60 * 60 * 1000,
    end: Date.now()
  })
});

const data = await response.json();
console.log(data.verifications);  // Total count

Common Analytics Queries

In the dashboard:
  1. Go to AnalyticsOverview
  2. Check the Top Keys widget
  3. Sort by verification count
Via API: Query all keys and sum their verification counts:
try {
  const { meta, data } = await unkey.keys.list({ apiId: "api_..." });
  
  // Keys are returned with usage stats
  const sorted = data.keys.sort((a, b) => 
    b.verifications - a.verifications
  );
  
  console.log("Top 10 consumers:", sorted.slice(0, 10));
} catch (err) {
  console.error(err);
}
Track which keys are hitting limits:
  1. Go to AnalyticsErrors
  2. Filter by code: RATE_LIMITED
  3. Identify patterns:
    • Same key repeatedly hitting limits → User needs upgrade
    • Sudden spike in violations → Possible abuse or bug
    • Specific time of day → Workload scheduling issue
Set up alerts: Use the Audit Log API to build custom alerting:
// Poll for rate limit events
const logs = await fetch("https://api.unkey.com/v1/auditlog.list", {
  headers: { "Authorization": `Bearer ${rootKey}` }
});

const rateLimitEvents = logs.data.filter(
  e => e.event === "key.verification_failed" && 
       e.meta?.code === "RATE_LIMITED"
);

if (rateLimitEvents.length > threshold) {
  // Send alert
}
Monitor which keys are running out of credits:
try {
  const { meta, data } = await unkey.keys.list({ apiId: "api_..." });
  
  const lowCredit = data.keys.filter(key => 
    key.remaining !== null && key.remaining < 100
  );
  
  // Alert these users to add more credits
  for (const key of lowCredit) {
    console.log(`Key ${key.name}: ${key.remaining} credits left`);
    // Send email notification
  }
} catch (err) {
  console.error(err);
}
Identify anomalies that might indicate compromise:
  • Sudden spike in usage: Key making 10x normal requests
  • New geographic locations: Key suddenly used from different continent
  • Off-hours activity: Key active at unusual times
  • High failure rate: Many INSUFFICIENT_PERMISSIONS errors (possible attack)
Build custom monitoring:
// Compare today's usage to 7-day average
const todayVerifications = /* query today */;
const avgVerifications = /* query last 7 days */ / 7;

if (todayVerifications > avgVerifications * 3) {
  // Alert: 3x normal usage
}
Generate usage-based invoices:
try {
  // Get verifications for billing period
  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);
  
  const { meta, data } = await fetch(
    "https://api.unkey.com/v1/analytics.getVerifications",
    {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${rootKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        apiId: "api_...",
        start: startOfMonth.getTime(),
        end: Date.now()
      })
    }
  ).then(r => r.json());
  
  // Calculate bill
  const costPerRequest = 0.001;  // $0.001 per request
  const totalCost = data.verifications * costPerRequest;
  
  console.log(`Usage: ${data.verifications} requests`);
  console.log(`Bill: $${totalCost.toFixed(2)}`);
} catch (err) {
  console.error(err);
}

Custom Dashboards

Build custom analytics dashboards for your users:
// Example: User-facing usage dashboard
import { Unkey } from "@unkey/api";

const unkey = new Unkey({ rootKey: process.env.UNKEY_ROOT_KEY });

export async function getUserUsageStats(userId: string) {
  try {
    // Get all keys for this user
    const { meta, data } = await unkey.keys.list({
      apiId: "api_...",
      externalId: userId
    });
    
    // Aggregate usage across keys
    const totalVerifications = data.keys.reduce(
      (sum, key) => sum + (key.verifications || 0),
      0
    );
    
    const totalRemaining = data.keys.reduce(
      (sum, key) => sum + (key.remaining || 0),
      0
    );
    
    return {
      totalKeys: data.keys.length,
      totalVerifications,
      totalRemaining,
      keys: data.keys.map(key => ({
        name: key.name,
        verifications: key.verifications,
        remaining: key.remaining,
        lastUsed: key.lastUsed
      }))
    };
  } catch (err) {
    console.error(err);
    throw err;
  }
}

Alerting & Monitoring

Set up automated alerts for critical events:

Credit depletion

Alert users when credits drop below threshold:
if (key.remaining < 100) {
  await sendEmail({
    to: key.meta.email,
    subject: "Low API credits",
    body: `You have ${key.remaining} credits left`
  });
}

Rate limit violations

Notify when users consistently hit limits:
if (rateLimitedCount > 100) {
  await sendEmail({
    subject: "Upgrade for higher limits",
    body: "You're hitting rate limits. Upgrade?"
  });
}

Unusual activity

Detect potential security issues:
if (verifications > avgVerifications * 5) {
  await sendSlackAlert({
    channel: "#security",
    message: `Unusual activity on key ${keyId}`
  });
}

Failed verifications

Track authentication failures:
if (failureRate > 0.5) {
  await logAlert({
    level: "warning",
    message: `High failure rate: ${failureRate * 100}%`
  });
}

Analytics Best Practices

Check these metrics every day:
  • Total verifications: Are they growing?
  • Success rate: Should be >99%
  • Top consumers: Who are your power users?
  • Error trends: Are failures increasing?
Generate weekly/monthly reports:
  • Email stakeholders with usage summaries
  • Track growth trends
  • Identify opportunities for upsells
  • Spot potential churn (declining usage)
Store context in key metadata for better analytics:
meta: {
  plan: "pro",
  industry: "fintech",
  company: "Acme Corp"
}
Then segment analytics by industry, plan, etc.
Connect API usage to business outcomes:
  • Do power users have higher retention?
  • Does usage predict upsells?
  • Which features drive the most API calls?
Automate responses to usage patterns:
  • Low usage → Re-engagement email
  • High usage → Upsell offer
  • Depleted credits → Prompt to add more
  • Rate limits hit → Upgrade prompt

Compliance & Data Privacy

Data retention: Analytics data is retained according to your plan. For GDPR/CCPA compliance, you can request deletion of specific key analytics.PII handling: Unkey does not capture request payloads or response bodies — only metadata. Never store PII in key names or metadata unless encrypted.

Next Steps

Audit Logs

Track who made changes to keys and configuration

Rate Limiting

Understand how rate limit analytics work

API Reference

Complete analytics API documentation

Webhooks

Receive real-time notifications for key events

Build docs developers (and LLMs) love