Security Best Practices for Bearer Token Usage: 2026
What Is a Bearer Token?
A bearer token is a security credential that grants access to whoever possesses it. The name says it all: the “bearer” of the token gets in. No additional proof of identity is required. If you have the token, the server trusts you.
Defined in RFC 6750, bearer tokens are most commonly used with OAuth 2.0. In practice, you present them in an HTTP header like this:
Authorization: Bearer <token>
The server receives the request, checks the token’s validity, and either grants or denies access. It does not verify who is holding the token in that moment. It only checks whether the credential is still trusted, still valid for this API, and still permitted for the requested action.
This is the fundamental property that makes understanding security best practices for bearer token usage so important. Possession equals authority.
Bearer Token vs. JWT vs. API Key
These three terms get confused constantly. Here’s the distinction:
- Bearer token describes how a token is presented. It’s a method of authentication.
- JWT (JSON Web Token) describes what a token contains. It’s a structured format with claims, signed cryptographically.
- API key is a simple credential, usually a long random string, used for server-to-server authentication.
A JWT can be used as a bearer token. An API key can also be used as a bearer token. “Bearer” refers to the presentation mechanism, not the token’s internal structure. A bearer token can be opaque (a random string the server looks up) or self-contained (a JWT the server can verify without a database call).
For developers building telemetry and observability pipelines in serverless apps, bearer tokens are the standard way to authenticate API calls for metrics ingestion, logging, and tracing.
Why Bearer Token Security Matters
Think of a bearer token like a hotel key card. Anyone who picks it up off the lobby floor can walk into your room. The door doesn’t check fingerprints. It checks the card.
This makes bearer tokens both convenient and dangerous. The convenience is obvious: no complex handshake, no client certificates, just a header and you’re in. The danger is equally clear: if someone steals the token, they have full access until it expires or gets revoked.
The Numbers Are Alarming
The scale of token and credential exposure is staggering. GitGuardian’s 2026 report found that 28.65 million new hardcoded secrets appeared in public GitHub commits in 2025, a 34% year-over-year increase and the largest single-year jump on record. Even worse, more than 64% of credentials confirmed valid in 2022 were still valid at retest in January 2026, four years after exposure.
Broken authentication ranks as the second most critical API vulnerability in the OWASP API Security Top 10 (2023). In 2024, infostealer malware exfiltrated over 17 billion browser cookies, many of them authentication tokens.
Real Breaches, Real Consequences
When attackers compromised Salesloft in early 2025, they didn’t need malware or backdoors. They simply used refresh tokens already stored in Salesloft’s environment, tokens that connected to customer Salesforce instances. Those tokens had been authorized months or years earlier by users who had since moved on. The tokens remained active, granting access to over 700 organizations.
In May 2026, GitHub confirmed that a threat actor cloned roughly 3,800 of its own internal repositories. A malicious VS Code extension harvested GitHub OAuth tokens and cloud credentials from a developer machine. In one case, a stolen CLI token remained live for seven days before anyone noticed.
These aren’t edge cases. They’re the predictable outcome of treating bearer tokens casually.
Core Security Best Practices for Bearer Token Usage
The following practices form a comprehensive defense. No single measure is sufficient on its own. They work together.
Enforce HTTPS Everywhere
This is non-negotiable. Bearer tokens transmitted over plain HTTP can be intercepted by anyone on the network path. Always use HTTPS to encrypt traffic, and enable HTTP Strict Transport Security (HSTS) to force secure connections.
Every API endpoint that accepts bearer tokens should reject non-TLS connections outright. If you’re working with metrics APIs that use rate limiting and backoff, those protections mean nothing if the token itself travels in cleartext.
Use Short Token Lifetimes
Short-lived tokens reduce the blast radius of a compromise. If an attacker steals a token that expires in 10 minutes, the window for abuse is narrow.
RFC 9700, the OAuth 2.0 Security Best Current Practice published as BCP 240 in January 2025, provides specific guidance. Sensitive APIs handling financial data, healthcare information, or regulated content should use access token expirations as short as 5 to 15 minutes. General-purpose APIs can extend to 30 to 60 minutes.
The long-lived token trade-off. Most guides stop here, but real-world systems are more nuanced. For server-to-server API tokens used in confidential contexts (where the token never touches a browser or user device), long-lived tokens are standard practice. Metrics ingestion APIs, CI/CD systems, and infrastructure automation commonly use them. The trade-off is valid when combined with secure storage, rotation capability, and HTTPS. The key distinction: short-lived tokens matter most for user-facing, public client scenarios. Server-side, confidential contexts can safely use longer lifetimes with compensating controls.
Store Tokens in Secure Locations
Never hardcode tokens in source code. Environment variables and secrets managers exist for exactly this purpose. Environment variables aren’t embedded in the codebase, they sit outside the repository, and they can be rotated without code changes.
For Cloudflare Workers, secrets must never appear in your Wrangler configuration or source code. Use wrangler secret put to store them securely and access them through env at runtime. Cloudflare encrypts these secrets at rest and treats them as write-only, meaning their values cannot be retrieved after creation.
For local development, .dev.vars and .env files should never be committed to git. Add them to your .gitignore immediately. Practitioners in DevSecOps communities have started reframing this: treat your .gitignore not just as a convenience file but as an access control list for your repository. That mental shift helps.
If you’re setting up a new project, the developer onboarding checklist covers the initial steps for configuring tokens and environment variables properly.
Never Log or Expose Tokens
A bearer token leak often looks mundane: a token copied into a support ticket, left in a client-side log, or hardcoded during a late-night test and committed by accident.
Application logs frequently capture full HTTP headers, including Authorization headers containing bearer tokens. CVE-2020-15125 demonstrated this directly: the widely used Auth0 library logged Authorization header values in error objects, leaking tokens to log files. Sanitize your logs. Strip Authorization headers before writing anything to disk or a log aggregation service.
Never include tokens in URLs. Query parameters end up in server logs, browser history, proxy logs, and referrer headers. The Authorization header exists specifically to avoid this problem.
Implement Token Rotation and Revocation
Periodically rotate API tokens to minimize the risk of long-term exposure. RFC 9700 states that refresh tokens issued to public clients must either be sender-constrained or rotated on every use.
Without a revocation mechanism, attackers can continue using stolen tokens until natural expiry. For long-lived server tokens, pair them with a revocation endpoint or at minimum a manual rotation process.
The Salesloft breach illustrates what happens when rotation is ignored: tokens authorized years earlier by departed employees remained active and became the attack vector for hundreds of organizations.
Validate Tokens Thoroughly on the Server
Server-side validation is where many implementations fall short. For JWTs used as bearer tokens, the resource server must validate:
- Signature integrity using RS256, ES256, or similar algorithms
- Expiration (
expclaim) - Audience (
audclaim), confirming the token was issued for this API - Issuer (
issclaim), confirming the token came from a trusted authority
Implementations that accept alg: none are inexcusable. An attacker can forge a token or modify an existing one (extending expiration, escalating scope) if the server doesn’t enforce signature verification. This is one of the most common security best practices for bearer token usage that gets skipped during rapid prototyping and then never revisited.
Apply Least-Privilege Scopes
Define scopes (like read:data, write:data) to restrict what a token can do. A token that can read metrics shouldn’t be able to delete accounts.
Implement the principle of least privilege by assigning the minimum required permissions. For serverless functions, this applies doubly: each function should have only the permissions it actually needs for its specific task.
Bearer Tokens in Serverless and Edge Environments
Generic bearer token guides assume a traditional server with persistent processes, a filesystem, and long-running memory. Serverless and edge runtimes break those assumptions in ways that directly affect token security.
Why Serverless Changes the Picture
Cloudflare Workers use V8 isolates that spin up almost instantly. There’s no persistent process, no traditional filesystem, and no long-running memory to cache secrets in. Vercel Edge Functions operate under similar constraints.
This means the traditional pattern of fetching secrets from an external vault on every request doesn’t work well. The latency for secret delivery would be noticeably longer than the isolate startup itself, creating an unacceptable performance hit. Pre-loaded environment variable secrets become the practical pattern.
For Cloudflare Workers, the workflow is straightforward:
- Store secrets with
wrangler secret put MY_API_TOKEN - Access them at runtime via
env.MY_API_TOKEN - Use
.dev.varsfor local development (and gitignore it)
For Vercel, environment variables configured in project settings are injected at build and runtime. The same principles apply: never hardcode, always gitignore local env files.
When you’re instrumenting Cloudflare Workers with waitUntil, the bearer token used for API calls inside ctx.waitUntil() needs to come from the environment, not from a hardcoded string in your handler. The same applies when using after() in Vercel Edge Functions for async metrics flushes.
The Flush Path and Token Exposure
In serverless metrics pipelines, the flush path is where your application sends buffered data to an ingestion API. This is typically an HTTP POST with an Authorization: Bearer <token> header. The token travels in the flush call, which often happens asynchronously after the main response is sent.
This creates a specific risk: if the flush fails and you log the error (a natural instinct), you might accidentally capture the Authorization header in your logs. Configure your buffering and flush behavior to sanitize error output, and never log the full request headers of failed flush attempts.
Common Mistakes and How to Avoid Them
Knowing the best practices matters. Knowing the failure modes matters more.
Hardcoded tokens in test code. A developer adds a token inline to test a feature, commits it, and pushes to a public or shared repository. GitGuardian’s data shows this is the single most common source of credential leaks. AI-assisted coding makes it worse: commits generated with AI assistance leak secrets at a 3.2% rate, roughly double the baseline.
Tokens in localStorage. Browser localStorage is accessible to any JavaScript running on the page. A single XSS vulnerability gives an attacker every token stored there. Use httpOnly cookies or in-memory storage for browser-based tokens instead.
Logging full HTTP headers. This captures the Authorization header. Configure your logging library to redact sensitive headers before writing logs. This is especially relevant when debugging missing metrics and ingestion failures, where the temptation to log everything is highest.
Long-lived tokens without a revocation plan. A long-lived token is fine if you can rotate or revoke it when needed. A long-lived token with no revocation mechanism is a ticking time bomb.
Not gitignoring .env files. This should be the first line in every new repository’s .gitignore. It’s a 10-second task that prevents catastrophic exposure.
Skipping validation in development. Turning off signature checks or expiry validation during development creates muscle memory (and code paths) that leak into production. Validate from day one.
If you’re building a serverless pipeline from scratch, the guide on common pitfalls when instrumenting serverless handlers covers the instrumentation-specific mistakes that compound these security issues.
The Future: Beyond Bearer Tokens
Bearer tokens have a fundamental limitation: they can’t prove who is using them. Emerging standards aim to fix this.
DPoP (Demonstrating Proof-of-Possession)
DPoP, defined in RFC 9449, is an OAuth 2.0 security enhancement that binds tokens to a specific client. The client generates a public/private key pair and presents a cryptographically signed proof with each request. If an attacker steals the token, they can’t use it without also stealing the private key.
This is a significant improvement over pure bearer semantics. Bearer tokens provide no cryptographic guarantee of ownership. DPoP tokens require proof of possession for every use.
Sender-Constrained Tokens and OAuth 2.1
The OAuth 2.1 direction makes PKCE mandatory and explicitly forbids bearer tokens in URLs. The broader industry trend is toward sender-constrained tokens, whether through DPoP, Mutual TLS, or other binding mechanisms.
When Simple Bearer Auth Is Sufficient
Not every system needs DPoP. For server-to-server API authentication in trusted environments (like a Cloudflare Worker calling a metrics ingestion API over HTTPS with a pre-loaded secret), standard bearer token security with proper storage, rotation, and HTTPS is appropriate. The complexity of proof-of-possession adds value primarily in public client scenarios where tokens traverse untrusted environments.
Behavioral Monitoring as the Final Layer
No cryptographic control detects a token being actively abused once stolen. Behavioral monitoring fills that gap by establishing baselines for normal token use and flagging deviations: impossible travel, abnormal request volumes, unexpected network origins. For high-value APIs, this is often the only signal that catches a compromised token before expiry.
Quick-Reference Checklist
| Practice | Priority | Key Detail |
|---|---|---|
| Enforce HTTPS/TLS | Critical | Reject non-TLS connections; enable HSTS |
| Short token lifetimes | High | 5-15 min for sensitive APIs; 30-60 min general purpose |
| Secure storage | Critical | Environment variables, wrangler secret put, never in code |
| Never log tokens | Critical | Sanitize Authorization headers from all log output |
| Token rotation | High | Rotate periodically; rotate refresh tokens on every use |
| Server-side validation | Critical | Verify signature, expiry, audience, issuer; reject alg: none |
| Least-privilege scopes | High | Grant only the permissions each token needs |
| Gitignore env files | Critical | Add .env* and .dev.vars* to .gitignore immediately |
| Revocation mechanism | High | Ability to invalidate compromised tokens before expiry |
| Behavioral monitoring | Medium | Baseline normal use; alert on anomalies |
For teams getting started with serverless metrics, the metrics quickstart guide walks through the full setup from code to dashboard, including proper token configuration.
Want to compare plan options for your metrics pipeline? Check out the Distlang plan features comparison.
Frequently Asked Questions
What makes bearer tokens different from other authentication methods?
Bearer tokens grant access based solely on possession. Unlike methods that require a cryptographic proof (like Mutual TLS or DPoP), anyone holding a valid bearer token can use it. This simplicity makes them easy to implement but demands careful security practices for storage, transport, and lifecycle management.
Should I store bearer tokens in localStorage?
No. Browser localStorage is accessible to any JavaScript on the page, making it vulnerable to XSS attacks. For browser-based applications, use httpOnly cookies or keep tokens in memory. For server-side and serverless applications, use environment variables or platform-specific secrets managers like wrangler secret put for Cloudflare Workers.
How long should a bearer token live?
It depends on the context. RFC 9700 recommends 5 to 15 minutes for sensitive APIs and 30 to 60 minutes for general-purpose APIs. Server-to-server tokens in confidential environments can use longer lifetimes when paired with secure storage, HTTPS, and rotation capability. The key is matching lifetime to risk: shorter for public clients, longer (with compensating controls) for server-side use.
What is the biggest risk with bearer tokens in serverless environments?
The biggest risk is accidental exposure through logs, error output, or misconfigured environment variables. Serverless functions often have aggressive logging enabled for debugging, and the Authorization header can easily end up in log aggregation systems. Sanitize all log output and never include tokens in error messages or URL parameters.
Can a JWT and a bearer token be the same thing?
Yes. A JWT is a token format. “Bearer” is a presentation method. When you send a JWT in an Authorization: Bearer <token> header, it’s functioning as a bearer token. The JWT provides structure (claims, signature), while the bearer mechanism provides the transport convention.
What is DPoP and should I use it?
DPoP (Demonstrating Proof-of-Possession) binds a token to a specific client’s cryptographic key pair. It prevents stolen tokens from being used by attackers who don’t have the private key. Use DPoP when tokens traverse untrusted environments (mobile apps, SPAs). For server-to-server API calls in trusted infrastructure, standard bearer token security is typically sufficient.
How do I handle bearer tokens in Cloudflare Workers?
Store them using wrangler secret put, access them via env at runtime, and use .dev.vars for local development. Never hardcode tokens in your Worker script or Wrangler configuration. Cloudflare encrypts secrets at rest and treats them as write-only. For detailed patterns, including how tokens interact with ctx.waitUntil() for async operations, see the Cloudflare Workers instrumentation guide.
How often should I rotate bearer tokens?
For refresh tokens in public client scenarios, RFC 9700 mandates rotation on every use. For long-lived server tokens, establish a regular rotation schedule (monthly or quarterly at minimum) and rotate immediately after any suspected compromise. The GitGuardian data showing 64% of leaked credentials still valid after four years makes the case clearly: rotation is not optional.