Guides / SaaS

Track API Usage Per Customer with LogIt

4 min read·SaaS

Why Track API Usage

API usage tracking helps you:

  • Identify power users and upsell opportunities
  • Detect abnormal usage patterns before they become abuse
  • Enforce usage limits with Smart Actions alerts
  • Generate per-customer usage reports

Step 1: Log API Calls in Middleware

ts
// middleware/api-usage.ts (Express/Node.js)
import { logit } from "@/lib/logit";

export async function apiUsageMiddleware(req: Request, res: Response, next: NextFunction) {
  const start = Date.now();
  const customerId = req.user?.organizationId ?? "anonymous";
  const plan = req.user?.plan ?? "unknown";

  res.on("finish", async () => {
    const duration = Date.now() - start;

    await logit.now("api-usage", {
      event: "API request",
      description: `${req.method} ${req.path}${res.statusCode} (${duration}ms)`,
      icon: "⚡",
      notify: false,
      tags: {
        customerId,
        plan,
        method: req.method,
        status: res.statusCode.toString(),
        endpoint: req.path,
      },
      metadata: {
        customerId,
        duration,
        statusCode: res.statusCode,
        path: req.path,
        method: req.method,
      },
    }).catch(console.error);  // fire-and-forget
  });

  next();
}

Step 2: Log High-Cost Operations Separately

ts
// For expensive operations (AI calls, large exports), log separately
await logit.now("api-usage-premium", {
  event: "Premium API call",
  description: `Customer ${customerId} — /api/ai/generate (${tokens} tokens)`,
  icon: "🤖",
  notify: false,
  tags: { customerId, plan, operation: "ai-generate" },
  metadata: { customerId, tokens, model, duration },
});

Step 3: Add Usage Spike Detection with Smart Actions

FieldValue
NameCustomer API abuse
Channelapi-usage
Event nameAPI request
Threshold1000
Window1 hour
Cooldown1 hour
ActionPush notification
Push title⚡ API usage spike
Push body1000+ API calls in 1 hour

Step 4: Filter by Customer in the Dashboard

Since customerId is a tag (not just metadata), you can filter the api-usage channel by customer ID in the LogIt dashboard to see their full usage timeline.

Tips

  • Log to api-usage channel with notify: false — you don't want a ping per API call.
  • Use Smart Actions to alert when a single customer's call count spikes, indicating a runaway script.
  • Track duration in metadata to identify slow endpoints alongside usage volume.

Try LogIt free

7-day trial. No credit card required.

Start free