Skip to content

Core API

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

Core API

The root import of cognito-toolkit: the framework-free verifier adapter plus the aws-jwt-verify re-exports. The middleware ports build on it; use it directly when no port fits (queue consumers, WebSocket handshakes, custom protocols).

import {makeGetUser, CognitoJwtVerifier, JwtVerifier, AlbJwtVerifier} from 'cognito-toolkit';

function makeGetUser<Payload extends object = JwtPayload>(verifier: TokenVerifier<Payload>, options?: GetUserOptions): GetUser<Payload>;

interface TokenVerifier<Payload extends object = JwtPayload> {
  verify(jwt: string): Promise<Payload>; // throws on an invalid token
  hydrate?(): Promise<void>; // optional JWKS pre-fetch
}

interface GetUserOptions {
  throwOnError?: boolean; // default false
}

type GetUser<Payload> = ((token: string | null | undefined) => Promise<Payload | null>) & {
  prime(): Promise<void>; // JWKS pre-fetch via the verifier's hydrate()
};

CognitoJwtVerifier, JwtVerifier, and AlbJwtVerifier are re-exported verbatim from aws-jwt-verify for one-stop imports — configure pools, clientId, tokenUse, customJwtCheck, multi-pool setups, non-Cognito OIDC issuers, and ALB-forwarded tokens there.

Example

import {makeGetUser, CognitoJwtVerifier} from 'cognito-toolkit';

const verifier = CognitoJwtVerifier.create({userPoolId: 'us-east-1_MY_POOL', clientId: 'my-app-client', tokenUse: 'access'});
const getUser = makeGetUser(verifier);

const user = await getUser(tokenFromAnywhere); // decoded payload or null — never throws on a bad token
await getUser.prime(); // optional: pre-fetch JWKS (serverless cold starts)

Semantics

  • An absent token (null / '' / undefined) resolves null without touching the verifier — anonymity is a normal state, not an error, so it never throws even under throwOnError.
  • A rejected token resolves null; the reason is logged via NODE_DEBUG=cognito-toolkit. With {throwOnError: true} the aws-jwt-verify error (see aws-jwt-verify/error) is thrown instead, so callers can tell an expired token from a wrong-audience one.
  • Any object satisfying TokenVerifier works — including hand-rolled stand-ins in tests; the payload type flows through the generic.

See also

Clone this wiki locally