-
Notifications
You must be signed in to change notification settings - Fork 1
utils lazy access token
Eugene Lazutkin edited this page Jul 17, 2026
·
1 revision
On-demand, cached OAuth2 client_credentials access tokens from a Cognito user-pool domain's /oauth2/token — for calling other services machine-to-machine. Unrelated to request verification.
import {createLazyAccessToken} from 'cognito-toolkit/utils/lazy-access-token';
function createLazyAccessToken(options: AccessTokenOptions): LazyAccessToken;
interface AccessTokenOptions {
url: string; // https://<domain>/oauth2/token
clientId?: string; // HTTP Basic username
secret?: string; // HTTP Basic password
fetch?: typeof fetch; // custom fetch, defaults to the global
}
interface LazyAccessToken {
authorize(): Promise<AccessToken>; // cached until ~5 min before expiry, then refetches
getToken(): AccessToken | null; // current token, never fetches
}
interface AccessToken {
access_token: string;
token_type: string;
expires_in: number;
[key: string]: unknown;
}import {createLazyAccessToken} from 'cognito-toolkit/utils/lazy-access-token';
const auth = createLazyAccessToken({
url: 'https://auth.my-domain.com/oauth2/token',
clientId: process.env.AUTH_CLIENT_ID,
secret: process.env.AUTH_CLIENT_SECRET
});
const token = await auth.authorize(); // fetches once, then serves the cache
await fetch('https://api.example.com/x', {headers: {authorization: token.access_token}});-
authorize()returns the cached token while fresh (refreshes ~5 minutes beforeexpires_inelapses) and fetches otherwise; it throws on a non-2xx token response and on a malformed 2xx body — a broken auth server is an error, not a "no token" state. - State is per-instance: create one holder per credential set.
- Prefer utils renewable access token when you want the token refreshed proactively on a timer instead of on demand.
Start here
Reference
Under the hood