Function: tokenAuth()
tokenAuth(
opts):AuthProvider
Defined in: src/core/auth.ts:240
A minted token, cached in-process and re-minted skewSeconds before
expiresAt (unix epoch SECONDS, like a JWT exp; omit for "until a 401").
Concurrent requests share one in-flight mint. refresh forces a re-mint.
mint throws on failure (and retries internally if it wants to); an empty
token throws an SdvError naming the family.
Parameters
opts
Minting options.
header?
string
Header to set (default "Authorization").
scheme?
string
Value prefix (default "Bearer"; "" sends the bare token).
skewSeconds?
number
Re-mint this many seconds before expiry (default 60).
mint
Mints a token (ctx.transport is the family's transport for the mint call).
expiresAt in unix epoch seconds; omitted means the token is kept until a 401. The other
options (header, scheme, skewSeconds) are documented on the parameter type below.
Returns
An AuthProvider. apply sets <header>: <scheme> <token> unless the request
already carries that header; refresh drops the cache and mints again — unless the 401
was for a header the caller set themselves, in which case it does nothing.
Throws
SdvError (from apply / refresh) when mint resolves without a token:
"<family>: no credential — the token returned by tokenAuth mint() is empty. …".
Example
import { configure, tokenAuth } from 'sportsdataverse';
configure({
auth: {
nfl_api: tokenAuth({
mint: async (ctx) => {
const url = 'https://api.nfl.com/identity/v3/token';
const res = await ctx.transport({ method: 'POST', url, body });
const { accessToken, expiresIn } = res.data as { accessToken: string; expiresIn: number };
return { token: accessToken, expiresAt: Date.now() / 1000 + expiresIn };
},
}),
},
});
Remarks
Concurrent requests share one in-flight mint; the cache is per provider instance, not per
process. A mint that throws is not retried by request(); a non-SdvError becomes
AssetFetchError("<family>: auth failed (apply|refresh)"). The nfl_api family already
registers a provider of this shape (nflTokenGen); this example is the pattern only.