10 Secure API Token Practices for Client-Side Telemetry


Why Telemetry Tokens Deserve Their Own Security Playbook

In 2025, 28.6 million new secrets were exposed on public GitHub repositories, a 34% increase year over year. That same year, GitHub disclosed that 39 million secrets leaked across its platform in 2024 alone. And 70% of secrets leaked back in 2022 are still active today.

Telemetry tokens sit in a strange middle ground. They’re non-human credentials, often a single long-lived API token per account, that authenticate your application’s metrics and traces on their way to an ingestion endpoint. They’re not user passwords. They’re not admin keys. But they carry real blast radius when mishandled, from data poisoning to metered billing abuse to, in the worst case, full data exfiltration if the token isn’t properly scoped.

The problem compounds in client-side environments. Whether your telemetry originates from a browser single-page app, a Cloudflare Worker, or a Vercel edge function, the code runs closer to the user than to your infrastructure. Standard API security advice (“store it in a vault”) doesn’t map cleanly onto these runtimes.

If you’re setting up metrics ingestion for the first time, the developer onboarding checklist covers the basics of token-based setup.

No existing guide on the web focuses specifically on secure API token practices for client-side telemetry. General API security listicles treat all tokens the same. They shouldn’t. Telemetry ingest tokens have a specific threat model and specific mitigations.

At-a-Glance: Token Security by Runtime Environment

Environment Can Token Stay Server-Side? Recommended Pattern Blast Radius if Leaked
Browser (SPA/RUM) No Reverse proxy + server-injected auth header High: any visitor can extract via DevTools
Edge Worker (Cloudflare Workers) Partially (runtime secrets) wrangler secret + env binding Medium: deploy-time access only, users can’t see it
Serverless Function (Vercel, Lambda) Yes Env var or secrets manager Low: server-only access
CI/CD Pipeline Yes Vault or secrets manager Medium: risk if build logs leak
Mobile App No Short-lived tokens minted server-side High: binary can be decompiled

This table drives the rest of the article. Each practice below maps back to one or more of these environments.

1. Scope Tokens to Write-Only Ingest

Scope Tokens to Write-Only Ingest Screenshot

Best for: Every telemetry setup, regardless of runtime.

Telemetry tokens should do exactly one thing: write data to your ingestion endpoint. They should never read metrics, modify dashboards, or access account settings. This is the single most important practice because it defines the ceiling of damage if a token leaks.

A write-only token limits the worst case to data poisoning (an attacker sending garbage metrics), not data exfiltration. That’s a meaningful difference.

The real-world evidence is clear. An adversarial security review of the open-source “apo” project found that ingest-scoped API keys weren’t actually confined to telemetry. A credential that was supposed to be write-only could read all project data. Similarly, a pull request against OneUptime revealed that its TelemetryIngestionKey was a single unscoped, non-expiring bearer credential, meaning anyone who scraped it could write arbitrary traces, logs, and metrics, leading to poisoned dashboards, forged spans, and billing burn.

Observability practitioners recommend treating ingest tokens as “non-human identities: one per environment or team, scoped write-only, stored in a secret store and rotated, not pasted into every deployment manifest.”

For guidance on how bearer token authentication works in practice for metrics APIs, see security best practices for bearer token usage.

2. Never Embed Long-Lived Tokens in Client-Side Bundles

Never Embed Long-Lived Tokens in Client-Side Bundles Screenshot

Best for: Browser SPAs, frontend frameworks, any JavaScript shipped to end users.

This rule is absolute. Any secret in a JavaScript bundle is public. It doesn’t matter how you obfuscate it, minify it, or split it across chunks. Anyone with browser DevTools can find it.

In 2022, RedHunt Labs scanned client-side web applications across the top one million internet domains and captured 395,713 secrets, many of them API keys and cryptographic credentials. The Manchester Airports Group breach illustrates what happens next: airport-specific Iterable API credentials exposed in client-side JavaScript enabled 86 GB of data theft.

A common mistake with modern frameworks: developers assume that environment variable prefixes like NEXT_PUBLIC_ or VITE_ provide some protection. They don’t. Those prefixes exist to signal that the value will be bundled into client-side code. Use them only for non-sensitive identifiers, never for secrets.

// BAD: Token embedded in client bundle
const TELEMETRY_TOKEN = "dstl_live_abc123xyz789";

fetch("https://api.example.com/v1/ingest", {
  headers: { Authorization: `Bearer ${TELEMETRY_TOKEN}` }
});
// GOOD: Token injected server-side, never reaches the browser
// (See Practice 3: Reverse Proxy Pattern)
fetch("/api/telemetry-proxy", {
  method: "POST",
  body: JSON.stringify(metrics)
});

As one security blog put it: “If the key is in client-side code, treat it as already compromised.”

A related issue surfaces when AI coding tools generate functional code with API keys embedded in frontend files. What these tools don’t do is flag that the key is sitting in a client-side JavaScript file that any user can read.

For common mistakes like this in serverless environments, see common pitfalls when instrumenting serverless handlers.

3. Use a Reverse Proxy for Browser-Based Telemetry

Use a Reverse Proxy for Browser-Based Telemetry Screenshot

Best for: Browser RUM, single-page applications, any telemetry originating from end-user browsers.

When telemetry originates in the browser, the only truly secure pattern is a server-side proxy that injects the authentication header before forwarding data to the ingestion endpoint. The browser never sees the token.

Elastic’s documentation for browser OpenTelemetry states this explicitly: “Because the SDK runs in the browser, it is recommended to avoid holding credentials there. The recommended approach is to place a reverse proxy that adds API keys or other auth headers before sending data.”

The architecture is straightforward:

  1. Browser SDK sends telemetry to your own domain (e.g., /api/telemetry)
  2. A reverse proxy (NGINX, Cloudflare Worker, or serverless function) receives the request
  3. The proxy validates the request origin, attaches the Authorization: Bearer <token> header, and forwards to the ingestion API
  4. The token lives only on the server or edge worker, never in the bundle
// Cloudflare Worker acting as a telemetry reverse proxy
export default {
  async fetch(request, env) {
    // Validate origin
    const origin = request.headers.get("Origin");
    if (!origin || !origin.endsWith(".yourdomain.com")) {
      return new Response("Forbidden", { status: 403 });
    }

    // Forward to ingestion API with token injected
    const upstream = new Request("https://ingest.example.com/v1/metrics", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${env.TELEMETRY_INGEST_TOKEN}`,
        "Content-Type": "application/json"
      },
      body: request.body
    });

    return fetch(upstream);
  }
};

This pattern adds minimal latency (especially when the proxy runs at the edge) and completely eliminates token exposure to end users.

4. Inject Tokens via Runtime Secrets in Edge Workers

Inject Tokens via Runtime Secrets in Edge Workers Screenshot

Best for: Cloudflare Workers, Deno Deploy, and similar edge runtime environments.

Edge workers occupy a middle ground between browsers and traditional servers. Users can’t inspect your Worker’s source code through DevTools, but the token still needs to stay out of your codebase and version control.

Cloudflare Workers solve this with wrangler secret, which injects sensitive values at deploy time and makes them available through environment bindings. Security practitioners on Cloudflare-focused blogs emphasize this: “Use wrangler secrets to inject sensitive credentials into Workers without exposing them in source code or logs.”

# Set the secret once via CLI (never committed to git)
wrangler secret put DISTLANG_API_TOKEN
// Access the secret in your Worker handler
export default {
  async fetch(request, env, ctx) {
    const token = env.DISTLANG_API_TOKEN;

    // Use token for telemetry flush
    ctx.waitUntil(
      fetch("https://api.distlang.com/v1/ingest", {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${token}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify(metricsPayload)
      })
    );

    return new Response("OK");
  }
};

Additional best practices for edge token handling include validating and periodically refreshing tokens, avoiding storage of tokens in Workers KV unencrypted, and scoping Cloudflare API tokens to minimum required permissions with separate tokens for deploy-only operations.

For the full walkthrough on instrumenting Workers with waitUntil semantics, see how to instrument Cloudflare Workers and the broader Cloudflare Worker instrumentation guide.

5. Enforce TLS on Every Telemetry Request

Enforce TLS on Every Telemetry Request Screenshot

Best for: Every environment, no exceptions.

Bearer tokens sent over plaintext HTTP are trivially sniffable by anyone on the network path. This sounds obvious, but it’s easy to overlook during local development when http://localhost is the default.

Every telemetry request carrying an API token must use HTTPS. The good news: serverless platforms like Cloudflare Workers and Vercel enforce HTTPS by default for production deployments. You can’t accidentally expose tokens over plaintext on these platforms unless you’re routing through a custom domain with misconfigured TLS.

The risk is higher in self-managed environments, staging setups using HTTP for convenience, or internal networks where “it’s behind the firewall” becomes an excuse. If your ingestion endpoint accepts HTTP at all, token interception is a matter of when, not if.

The OWASP recommendation is clear: tokens must always be transmitted over encrypted channels, and endpoints should reject plaintext connections entirely.

6. Rate-Limit Your Ingestion Endpoints

Rate-Limit Your Ingestion Endpoints Screenshot

Best for: Any publicly accessible telemetry API, especially when tokens grant write access.

Even a correctly scoped write-only token can cause damage if rate limits are absent. An attacker (or a buggy client) with a valid ingest token can flood your telemetry endpoint with garbage data, poisoning dashboards, triggering false alerts, and burning through metered billing.

The OneUptime security review highlighted this risk explicitly: anyone who scraped an unscoped telemetry key could write arbitrary traces, logs, and metrics, leading to metered billing burn and corrupted observability data.

Practical rate-limiting patterns for telemetry ingestion include:

  • Per-token limits: Cap the number of requests per minute per token. This prevents a single compromised token from overwhelming the system.
  • Per-IP limits: A secondary check, useful for browser-proxied telemetry where multiple clients share a proxy token.
  • Token bucket algorithms: One implementation uses a limit of 10 error reports per minute per client IP, returning 429 responses in under 2ms.
  • Retry-After headers: Always include them in 429 responses so well-behaved clients back off gracefully.

For a deeper look at handling backoff in your metrics client, see rate limiting and backoff strategies and how Distlang’s plan tiers handle row-based metering.

7. Rotate Tokens on a Schedule, Not Just After Incidents

Rotate Tokens on a Schedule, Not Just After Incidents Screenshot

Best for: All environments, especially teams using long-lived tokens.

The statistic bears repeating: 70% of secrets leaked in 2022 are still active three years later. Static tokens accumulate risk over time. They get copied into Slack messages, pasted into documentation, committed to private repos that later go public. Scheduled rotation limits the window of exposure.

For small teams using a single API token per account, rotation doesn’t need to be complex. Build it into a quarterly calendar event:

  1. Generate a new token
  2. Deploy it to your edge workers and serverless functions
  3. Verify ingestion is flowing with the new token
  4. Revoke the old token
  5. Confirm no ingestion failures (check your dashboards)

The key is making rotation routine, not reactive. If you only rotate after a known compromise, you’re already behind.

For teams running on Distlang Metrics, this also means checking that the old token’s ingestion has fully stopped before revoking. The debugging missing metrics guide covers how to verify ingestion flow.

8. Redact Tokens from Logs and Telemetry Payloads

Redact Tokens from Logs and Telemetry Payloads Screenshot

Best for: Any system with logging or distributed tracing enabled.

This is the practice most teams overlook. Your telemetry pipeline, the very system designed to give you visibility, can become the leak vector for the tokens it’s supposed to protect.

The problem is specific and documented: instrumentation that captures full HTTP request headers will capture Authorization: Bearer <token> along with everything else. Traces that record query strings will capture tokens passed as URL parameters. Error logs that dump request objects will include credentials.

Practitioners writing about observability security warn that “tokens everywhere: backend API keys in every agent’s environment, never rotated; one leaked key exposes all ingest or, worse, query access” and that telemetry itself is a data leak when instrumentation captures Authorization headers or query strings with tokens.

Concrete steps:

  • Strip Authorization headers from trace span attributes before export
  • Use OpenTelemetry span processors to redact sensitive fields
  • Never log full request objects in production; allowlist specific fields instead
  • Audit your telemetry payloads by inspecting what actually arrives at your ingestion endpoint
// Example: Redacting sensitive headers before recording a span
function sanitizeHeaders(headers) {
  const safe = { ...headers };
  delete safe["authorization"];
  delete safe["x-api-key"];
  return safe;
}

The guidance from API security practitioners is unambiguous: “Tokens should never appear in application logs or server logs. If debugging requires visibility, mask or redact them.”

9. Use Environment-Specific Tokens, Not One Token Everywhere

Use Environment-Specific Tokens, Not One Token Everywhere Screenshot

Best for: Teams with multiple deployment stages (dev, staging, production).

One shared token across dev, staging, and production means a leak in any environment compromises all of them. A developer accidentally commits the token from a staging deploy? Production ingestion is now at risk.

The fix is simple: issue separate tokens for each environment. Even two tokens (dev and prod) is a significant improvement over one.

This also gives you audit clarity. When you see unexpected ingestion traffic, environment-specific tokens tell you exactly which deployment is affected. Without them, you’re investigating across every service and environment simultaneously.

OWASP’s guidance on non-human identity management recommends binding tokens to specific contexts: “Issue short-lived, scoped tokens aligned with least privilege principles. Bind tokens to the specific agent, tool, or session context.”

For teams building out their instrumentation across Cloudflare and Vercel simultaneously, the application instrumentation guide covers how to structure environment-specific configurations.

10. Monitor Token Usage for Anomalies

Monitor Token Usage for Anomalies Screenshot

Best for: Production environments with active ingestion.

The previous nine practices are preventive. This one is detective. You need to know when a token is being misused, not just hope that your preventive controls held.

What to monitor:

  • Ingestion volume per token: A sudden spike from a token that normally sends 1,000 rows per hour suggests compromise or a runaway client.
  • Geographic origin of requests: If your Workers run in specific regions but you see ingestion from unexpected locations, investigate.
  • Error rates per token: A flood of malformed payloads from a single token may indicate an attacker probing your ingestion API.
  • Token activity after scheduled rotation: If an old token is still sending data after you’ve rotated, something didn’t deploy correctly, or someone is using a stale credential.

One security practitioner recommends you “build telemetry that tells you which keys are still in use so you can retire them confidently.” This is meta-telemetry: using your observability system to observe the security of your observability system.

Rate-limit events (429 responses) double as security telemetry. A token hitting rate limits repeatedly is either a misconfigured client or an abuse attempt. Either way, it warrants investigation.

Putting It All Together

These ten practices follow a hierarchy: scope the token narrowly (practice 1), isolate it from hostile environments (practices 2 through 5), limit abuse even with a valid token (practice 6), reduce the window of exposure (practices 7 through 9), and detect misuse when it happens (practice 10).

Not every team needs all ten on day one. If you’re a solo developer shipping metrics from a Cloudflare Worker, start with practices 1, 4, and 5. They take five minutes and eliminate the most common risks. As your deployment grows, layer on environment-specific tokens, rotation schedules, and monitoring.

The broader point is that secure API token practices for client-side telemetry aren’t generic API security advice repackaged. Telemetry tokens have a specific shape (write-only, non-human, high-volume) and specific failure modes (data poisoning, billing abuse, dashboard corruption). Treat them accordingly.

Ready to set up secure metrics ingestion? The quickstart guide walks through going from code to dashboard in minutes, with token-based authentication built in from the start.

Frequently Asked Questions

What makes telemetry ingest tokens different from regular API keys?

Telemetry ingest tokens are purpose-built for writing data (metrics, traces, logs) to an ingestion endpoint. Unlike general API keys, they should never grant read access, admin access, or the ability to modify configurations. This write-only scope means the worst case if a token leaks is data poisoning, not data exfiltration. General API keys often have broader permissions that make leaks far more dangerous.

Can I safely put a telemetry token in my JavaScript frontend bundle?

No. Any token embedded in client-side JavaScript is effectively public. Browser DevTools, view-source, and automated scanners can all extract it. Research across the top one million internet domains found nearly 400,000 exposed secrets in client-side applications. For browser-based telemetry, use a reverse proxy that injects the token server-side.

How often should I rotate telemetry API tokens?

At minimum, quarterly. The finding that 70% of secrets leaked in 2022 are still active years later shows that most teams never rotate at all. For small teams with a single token per account, put rotation on a calendar. Generate a new token, deploy it, verify ingestion, then revoke the old one.

Is it safe to store tokens in Cloudflare Workers environment variables?

Yes, when done correctly. Use wrangler secret put to inject the token at deploy time rather than hardcoding it in your source code or wrangler.toml. The secret is encrypted at rest and available only through the env binding in your Worker handler. Users cannot access it through the network, though anyone with deploy access to your Worker can read it.

What’s the risk of a leaked write-only telemetry token?

A leaked write-only token can be used to send garbage data to your ingestion endpoint, corrupting dashboards, triggering false alerts, and burning through metered billing quotas. It cannot be used to read your existing metrics or access account settings (assuming the token is properly scoped). Rate limiting and usage monitoring are your defenses against write-abuse.

Should I use short-lived tokens for client-side telemetry?

For browser environments, short-lived tokens minted server-side are a strong pattern. Security practitioners recommend configuring expiration times of 15 to 60 minutes to limit the window if a token is intercepted. For edge workers and serverless functions where the token stays server-side, long-lived tokens with scheduled rotation are usually sufficient and simpler to manage.

How do I prevent my own telemetry from leaking tokens?

Strip Authorization headers from trace span attributes, never log full request objects in production, and use span processors or middleware to redact sensitive fields before export. Audit what your telemetry pipeline actually captures by inspecting raw payloads at the ingestion endpoint. Your observability system should never become the vector that exposes the credentials it depends on.

Do serverless platforms like Vercel enforce HTTPS automatically?

Yes. Both Vercel and Cloudflare Workers enforce HTTPS for production deployments by default. You cannot accidentally send bearer tokens over plaintext HTTP on these platforms unless you’ve configured a custom domain with broken TLS. This is one of the security advantages of serverless and edge runtimes over self-managed infrastructure.