Secure Storage of Distlang API Tokens: Best Practices 2026


Secure Storage of Distlang API Tokens

TLDR

A Distlang API token is a bearer secret that grants access to your metrics account. Secure storage of Distlang API tokens means keeping the token in a platform secret store or secret manager, injecting it only into server-side or serverless runtime code, and preventing it from appearing in frontend bundles, Git repositories, logs, URLs, or chat messages. The safest defaults are Cloudflare Worker secrets and Vercel sensitive environment variables. If a token leaks, treat it as compromised and rotate it before doing anything else.

What Is a Distlang API Token?

A Distlang API token authenticates ingestion requests to Distlang Metrics. It is a bearer token, which means any system or person that possesses it can use it. RFC 6750 makes this explicit: clients must ensure bearer tokens are not leaked to unintended parties, and requests carrying them should always use TLS (source).

Based on how Distlang Metrics works today, each account has a single long-lived API token. Developers pass this token through the Distlang JS client or the raw Metrics API to send counters and histograms from their application code. That simplicity is a strength for small teams, but it also means one leaked token can affect the entire account.

For deeper guidance on how bearer tokens work in practice, read about bearer token security best practices.

This is why secure storage of Distlang API tokens is not optional. It is the primary defense.

What “Secure Storage” Actually Means

Most guides reduce token security to “use environment variables.” That advice is incomplete. Secure storage covers four surfaces, and all four matter.

Where the token rests. Source code, a .env file, a platform secret store, a vault, or an OS keychain. The resting location determines who can read the token at rest.

Where it is injected. A backend process, a serverless handler, a CI pipeline, or (dangerously) a browser bundle. The injection point determines who can intercept the token at runtime.

Where it travels. An HTTPS Authorization header is correct. A URL query string is not. URLs show up in browser history, server logs, referrer headers, and monitoring tools.

Where it accidentally appears. Logs, error reports, stack traces, screenshots, Slack messages, AI prompts, and Git history. These accidental surfaces cause more real-world leaks than sophisticated attacks.

Encryption alone does not solve any of this. OWASP recommends dedicated secrets-management solutions because they centralize access control, audit trails, and rotation workflows, not just encryption (source). Secure storage of Distlang API tokens requires attention at every surface.

The Token Storage Maturity Ladder

Not every team needs a vault on day one. But every team needs to be above Level 0. Think of secure Distlang token storage as a progression.

Level Storage Pattern When to Use Risk
0 Hardcoded in source code Never Leaks through Git, packages, screenshots, copied code
1 .env.local on a developer machine Local development only Can be committed, copied, or read by other processes
2 Platform secret store Most Distlang serverless apps Runtime reads the token; repo and build artifacts do not contain it
3 Cloud secret manager or vault Teams, production, compliance More setup, but better IAM, audit, and rotation workflows
4 Token proxy or brokered credential High-security or multi-team setups More architecture, but browser/client code never sees the token

Most Distlang users should target Level 2 as a starting point. Cloudflare Worker secrets and Vercel sensitive environment variables both meet this bar with minimal setup.

Ready to instrument your first metrics safely? Follow the metrics quickstart guide once your token is stored properly.

Recommended Storage by Environment

Cloudflare Workers

Cloudflare explicitly states that Worker secrets are designed for sensitive values like API keys and auth tokens, and warns against using plaintext environment variables for sensitive information (source).

Store the token:

npx wrangler secret put DISTLANG_API_TOKEN

Use it in your Worker:

export default {
  async fetch(request, env, ctx) {
    const token = env.DISTLANG_API_TOKEN;
    // Use token only in server-side Worker code.
    // Never return it in a response or log it.
  }
}

Do not put the token in wrangler.toml, source files, or console.log statements. For local development, use .dev.vars (which should also be gitignored).

After storing the token, see how to collect metrics from Cloudflare Workers using the Distlang JS client with ctx.waitUntil.

Vercel and Next.js

Vercel offers sensitive environment variables that become non-readable once created for production and preview environments (source).

Store the token:

vercel env add DISTLANG_API_TOKEN production --sensitive
vercel env add DISTLANG_API_TOKEN preview --sensitive

Access it in server-only code (route handlers, server actions, API routes):

const token = process.env.DISTLANG_API_TOKEN;

The critical rule: never name it NEXT_PUBLIC_DISTLANG_API_TOKEN. Next.js inlines any variable prefixed with NEXT_PUBLIC_ directly into browser JavaScript sent to users (source). This is not a theoretical risk. Practitioners on Reddit and LinkedIn repeatedly warn that NEXT_PUBLIC_, VITE_, and REACT_APP_ prefixes expose values to anyone who opens DevTools.

For a complete walkthrough of server-side instrumentation, see how to instrument Next.js API routes with Distlang.

Local Development

For local work, a .env.local file is acceptable if it is gitignored and never shared. Create a .env.example with placeholder names only, so teammates know which variables to set without seeing real values.

Better alternatives exist for teams that want to avoid scattered .env files entirely. 1Password CLI, for example, lets you inject secrets at runtime using op run so plaintext tokens never sit on disk (source). OS-level credential stores (macOS Keychain, Windows Credential Manager, Linux keyring) are another step up for CLI tools.

A practitioner in a GitHub CLI discussion recommends environment variables as a first layer but says production-ready tooling should use OS credential stores, with strict file permissions as a fallback (source). A LinkedIn practitioner post goes further, arguing that CLIs should avoid plain files and long-lived shell profile exports because these can appear in shell history, telemetry, or logs.

One more thing: do not pass tokens as command-line arguments. They show up in process listings and shell history.

CI/CD Pipelines

Store DISTLANG_API_TOKEN in your CI provider’s encrypted secrets (GitHub Actions secrets, GitLab CI/CD variables, etc.). Restrict secret access to only the workflows and environments that need it.

Avoid printing all environment variables in debug steps. Mask secret values in logs if your CI system supports it. Never store the token in workflow YAML files, and never use it in pull requests from untrusted forks.

If your CI artifacts include .env files, do not upload them. This is a common mistake covered in more detail in the guide on common serverless instrumentation pitfalls.

Where Not to Store Distlang API Tokens

Location Safe for Distlang Token? Why
Cloudflare Worker secret Yes Designed for API keys; hidden after creation; runtime-only access
Vercel sensitive env var Yes Stored in unreadable format for production/preview
Dedicated secret manager Yes (best for teams) Adds IAM, audit, versioning, rotation
.env.local (gitignored) Local dev only Convenient but easy to commit or copy
.env committed to Git No Secrets in Git history should be treated as compromised
NEXT_PUBLIC_* / VITE_* / REACT_APP_* No Bundled into browser JavaScript
Browser localStorage or sessionStorage No Readable by any JavaScript on the page; XSS can steal it
Frontend JavaScript bundle No Users can inspect source and network requests
URL query parameter No URLs appear in browser history, logs, referrers
Logs, traces, error messages No Log stores often have broader access than secret stores
Slack, tickets, AI prompts No These channels are not designed for secret storage

The pattern is simple: if a human or browser can see it without special authorization, the token does not belong there.

Why Browser Storage Is Unsafe for Distlang Tokens

This question comes up constantly. Can browser JavaScript send Distlang metrics directly?

Only if doing so does not require exposing the private account token. And with Distlang’s current single-token model, it does. So the answer is: do not do it. Use a backend handler, serverless function, or Worker as a proxy.

OWASP warns that localStorage is readable by any JavaScript running on the page and that XSS attacks can steal data from it (source). Auth0’s token storage guidance recommends browser memory as the least-bad option for user-facing session tokens, but even that recommendation comes with caveats about page refreshes and XSS.

A highly upvoted thread on r/webdev captures the confusion well. Developers report that managers ask them to “hide” API keys in frontend code, but practitioners point out that anything used in browser requests can be seen in DevTools or network traffic. Another r/webdev discussion emphasizes that public-facing endpoints should rely on backend proxying, rate limiting, and authentication rather than trying to conceal a secret in the client.

For Distlang specifically, the right architecture is clear: send metrics from your server-side handler or Worker, where the token lives in a secret store that the browser never touches.

Secure Transmission and Logging

Storing the token correctly is only half the job. It also has to travel safely and stay out of places it does not belong.

Always use HTTPS. Bearer token specifications require TLS for all requests carrying the token. No exceptions.

Use the Authorization header, not URL query parameters. URLs end up in browser history, HTTP access logs, CDN logs, referrer headers, and monitoring dashboards. A token in a query string can persist in systems you do not control.

Redact tokens from logs. This is where many teams stumble. Serializing a full request object into a log statement can dump the Authorization header into your log store. Log stores typically have broader access than secret stores, which makes them a common leak surface. Avoid console.log(request) or console.log(env) patterns in production code.

If metrics stop arriving after changing secrets, the issue is usually a stale environment value, not a logging problem. The guide on debugging missing metrics covers common ingestion failure patterns.

If a Distlang API Token Leaks

Secret leaks are common. GitHub detected more than 39 million leaked secrets across GitHub in 2024 (source). Truffle Security scanned 224 million public repositories in 2026 and found 543,699 credentials that still authenticated when tested (source). These numbers reflect different methodologies, but the takeaway is the same: leaks happen, and most leaked credentials are never revoked.

If your Distlang API token is exposed, follow this checklist:

  1. Stop using the exposed token immediately.
  2. Rotate, revoke, or replace the token wherever your Distlang account flow allows. If you cannot do this yourself, contact the account owner.
  3. Remove the token from source code, documentation, screenshots, issues, Slack messages, or AI chat history where possible.
  4. Purge or rewrite Git history only after rotation. Cleaning history does not make the old token safe; it only reduces future exposure.
  5. Update platform secrets in Cloudflare, Vercel, CI/CD providers, and any secret manager.
  6. Redeploy affected applications so old environment values are no longer in memory.
  7. Search logs and error trackers for the old token value or any token prefix.
  8. Review recent Distlang usage for unexpected ingestion volume or unfamiliar metric sets, if dashboard data makes that visible.
  9. Add prevention measures: secret scanning, .gitignore rules, pre-commit hooks, safer example files, and log redaction.

Practitioners on Reddit consistently emphasize that rotating the credential must come before history cleanup. Deleting a file from a repository does not remove it from Git history, and anyone who cloned the repo before the deletion still has the token.

For teams standardizing their setup, the developer onboarding checklist covers how to share token access safely during team growth.

Putting It All Together

Secure storage of Distlang API tokens is not a single action. It is a set of decisions about where the token rests, how it reaches your code, how it travels over the network, and where it might accidentally appear.

The practical defaults are straightforward:

  • Use wrangler secret put for Cloudflare Workers.
  • Use vercel env add --sensitive for Vercel.
  • Use .env.local (gitignored) for local development.
  • Use encrypted secrets in your CI provider.
  • Never prefix the variable with NEXT_PUBLIC_, VITE_, or REACT_APP_.
  • Never log it, paste it in chat, or put it in a URL.

For teams moving to production, compare Distlang plan features to understand how row limits and retention interact with your metrics volume.

Once the token is stored safely, walk through the end-to-end example to see the full flow from app instrumentation to dashboard.

FAQ

Where should I store a Distlang API token in Cloudflare Workers?

Use npx wrangler secret put DISTLANG_API_TOKEN to store it as a Worker secret. Access it through env.DISTLANG_API_TOKEN in your handler code. Do not put it in wrangler.toml or source files.

Can I put a Distlang API token in .env?

For local development, yes, if the file is .env.local and gitignored. For production, use your platform’s secret store or a dedicated secret manager. A .env file is a convenience format, not a security boundary.

Is NEXT_PUBLIC_DISTLANG_API_TOKEN safe?

No. Next.js replaces NEXT_PUBLIC_ references with hardcoded values in browser JavaScript. Anyone visiting your site can read it. Use a server-only variable name without the prefix.

Can I store a Distlang token in localStorage?

No. OWASP warns that localStorage is readable by any JavaScript on the page and vulnerable to XSS attacks. A Distlang API token is an account-level secret that should never be accessible to browser code.

Can browser JavaScript send Distlang metrics directly?

Only if doing so does not require exposing the private account token. Since Distlang currently uses a single long-lived token per account, sending metrics from the browser would expose that token. Use a serverless function or backend handler as a proxy instead.

What should I do if I committed a Distlang API token to GitHub?

Treat the token as compromised. Rotate or replace it through your Distlang account first, then update all platform secrets, redeploy affected apps, clean the Git history, and scan logs for the old value.

Should I use a secret manager for Distlang tokens?

For solo developers or small projects, platform secret stores (Cloudflare Worker secrets, Vercel sensitive env vars) are sufficient. For teams managing multiple apps or environments, a secret manager like AWS Secrets Manager or HashiCorp Vault adds access controls, audit logging, and rotation capabilities that platform secrets typically lack.

How do I keep Distlang tokens out of logs?

Avoid serializing full request objects or environment variables into log output. Redact or mask the Authorization header and any variable containing DISTLANG_API_TOKEN in your logging configuration. Test your log output in staging to confirm the token does not appear.