bearer
Attach a bearer token resolved at call time from an env var or a secrets file.
Use bearer when an API authenticates with a token sent as
Authorization: Bearer <token>, and you want the token resolved at call time so
the secret stays out of your code and out of the caller's hands.
Example
import { , , } from 'stitchapi';
const = ({
: 'https://api.example.com',
: '/me',
: (('API_TOKEN')),
});The token is read each time me() runs, so a rotated secret takes effect on the
next call with no rewiring.
Options
bearer accepts either a literal string or a resolver thunk (() => string).
Strongly prefer a resolver: it reads the secret per call from the environment or
a secrets file, so nothing is committed and the stitch hands callers a capability,
not the credential — see
Capability, not credential.
Use env('API_TOKEN') for an environment
variable or secretsFile('API_TOKEN') for ~/.stitch/secrets.json; both return a thunk
resolved at call time. See
Reference → Auth strategies for the full auth
table.
Anti-pattern: don't pass a literal token string — it bakes the secret into your source and hands the credential straight to anyone who reads it. Pass a resolver thunk instead, so the secret resolves at call time and the stitch hands callers a capability, not the credential (a literal is fine only for a non-secret placeholder). See Capability, not credential.
Optional credentials with optionalEnv
When you're scripting against an API whose token already sits in your
environment — a local dev run, a notebook, an agent loop — wrap the variable in
optionalEnv('NAME') and hand it to bearer. It resolves the variable's value,
or absent when the variable is unset. Unlike bearer(env('NAME')), which
throws on a missing variable, bearer(optionalEnv('NAME')) attaches the
header only when the token is present — otherwise the request goes out with no
credential.
import { , , } from 'stitchapi';
// Attaches `Authorization: Bearer $GITHUB_TOKEN` when that var is set;
// otherwise sends the request with no credential.
const = ({
: 'https://api.github.com/user/repos',
: (('GITHUB_TOKEN')),
});The outcome announces itself: bearer emits an info event naming the
variable it read — or noting that it was unset — but never the token itself, so
the decision is visible in the trace.
In a browser bundle there is no process environment, so the variable resolves
absent and nothing is attached.
Optional, not required. If the variable is unset,
bearer(optionalEnv(…)) sends no credential rather than failing — the
request goes out unauthenticated. When the call must be authenticated, use
bearer(env('GITHUB_TOKEN')), which throws on a missing variable.