Skip to content

utils renewable access token

Eugene Lazutkin edited this page Jul 17, 2026 · 3 revisions

utils/renewable-access-token

Timer-renewed OAuth2 client_credentials access tokens from a Cognito user-pool domain's /oauth2/token — the proactive sibling of utils lazy access token.

import {createRenewableAccessToken} from 'cognito-toolkit/utils/renewable-access-token';

function createRenewableAccessToken(options: RenewableAccessTokenOptions): RenewableAccessToken;

interface RenewableAccessTokenOptions {
  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
  retryInterval?: number; // ms before retrying a failed scheduled renewal; default 60000
  onError?: (error: unknown) => void; // observe failed scheduled renewals
}

interface RenewableAccessToken {
  retrieveToken(): Promise<AccessToken>; // fetch + schedule automatic renewal
  cancelRenewal(clearToken?: boolean): void; // stop renewing (incl. pending retries); true also drops the token
  getToken(): AccessToken | null; // always read the live token through this
}

Example

import {createRenewableAccessToken} from 'cognito-toolkit/utils/renewable-access-token';

const auth = createRenewableAccessToken({
  url: 'https://auth.my-domain.com/oauth2/token',
  clientId: process.env.AUTH_CLIENT_ID,
  secret: process.env.AUTH_CLIENT_SECRET
});

await auth.retrieveToken(); // fetch once; auto-renews ~5 min before each expiry
const token = auth.getToken(); // read the live token at call sites

// on shutdown:
auth.cancelRenewal(true);

Semantics

  • The renewal timer is unrefed — it never keeps the process alive on its own.
  • Renewal replaces the token over time, so always read it fresh via getToken() rather than holding a reference.
  • Fetch failures throw from direct retrieveToken() calls. A failure inside a scheduled renewal keeps the previous token and retries every retryInterval ms (default one minute) until a fetch succeeds or cancelRenewal() is called; each failure is reported to onError (or, without one, to the NODE_DEBUG=cognito-toolkit channel).
  • cancelRenewal() is final even mid-flight: a renewal already awaiting the token endpoint when you cancel neither stores its late result nor reschedules.
  • State is per-instance: create one holder per credential set.

Clone this wiki locally