Credence ID Orchestrator - Integration

Integrate the @credenceid/verifier-sdk npm package: activation, QR-based verification sessions, SSE subscriptions, credential parsing, and error handling.

01Overview

The @credenceid/verifier-sdk package enables web applications to request, receive, and process verified digital identity credentials from end users through the Credence Cloud verification infrastructure. A single verification session can return one or multiple credentials (e.g. a mobile driver's licence and a Photo ID presented together), depending on how your Profile is configured. The SDK manages session lifecycle, real-time event streaming, and credential data retrieval.

The SDK implements a QR-based orchestrator verification flow:

  1. Your application calls createVerificationSession() and receives a QR code image.
  2. The end user scans the QR code with their phone, which opens an orchestrator landing page hosted by Credence ID.
  3. That orchestrator page automatically detects the user's device and platform (iOS, Android, Samsung, or desktop) and presents only the credential-presentation methods their device supports — Apple Wallet via DC API on iOS, Google Wallet via OpenID4VP on Android, the Samsung Wallet Annex B flow, and the W3C State Wallet flow as a cross-platform fallback. This device-aware selection is fully managed by Credence and is transparent to your application.
  4. After the user presents a credential, your application receives the result asynchronously via Server-Sent Events (SSE).

Your application does not need to know which wallet the user has, which platform they are on, or how credential presentation works. You create a session, show a QR code, and receive a result.

Backend configuration — Profile, trust. All verification behaviour is configured server-side in the Verify with Credence portal before integration, not in the SDK or your application code. This includes:

  • Profile — defines which credential types are accepted, which claims are requested, and whether derived attributes (e.g. age_over_21) are returned instead of raw data fields. A profile may request more than one document type in a single session — the wallet holder presents whichever of the requested documents they hold, and each is verified and returned individually.
  • Trust settings — the issuer trust list and accepted certificate authorities are all managed in the portal.

Contact Credence ID to set up or modify any of these settings for your account.

Trust and audit. The orchestrator performs the full verification chain server-side — issuer/MSO signature, trust list, device binding, expiry, and revocation. Per-transaction evidence is retained in the Verify with Credence portal and can be exported.


02Sequence Diagram

The diagram below shows the complete data flow from your web application through the SDK, the CloudSDK backend, and Verify with Credence (VwC) for a full verification session.

sequenceDiagram
  participant User as End User
  participant App as Your Web App
  participant SDK as verifier-sdk
  participant Cloud as CloudSDK Backend
  participant VwC as Verify with Credence
  participant Wallet as Digital Wallet

  App->>SDK: new CredenceVerifier({ baseUrl })
  App->>SDK: activate({ licenseKey, profileId })
  SDK->>Cloud: POST /v1/auth/token { licenseKey, profileId }
  Cloud->>VwC: validate licenseKey + profileId<br/>(customer identity + domain check)
  VwC-->>Cloud: valid — customer confirmed, domain matched
  Cloud-->>SDK: 200 OK — Bearer token
  SDK-->>App: activate() resolves

  App->>SDK: createVerificationSession({ purpose, referenceId? })
  SDK->>Cloud: POST /v1/orchestrator/sessions (Bearer token)
  Cloud-->>SDK: { sessionId, qrUrl, qrImageBase64, expiresAt }
  SDK-->>App: VerificationSession

  App->>SDK: subscribeToVerificationResult(sessionId, cb)
  SDK->>Cloud: GET /v1/orchestrator/sessions/{id}/events<br/>(SSE, token in URL)
  Cloud-->>SDK: SSE connection established
  SDK-->>App: unsubscribe function

  App->>User: render QR code
  User->>Cloud: scan QR -> orchestrator landing page opens
  Note over User, Wallet: Device-aware wallet flow<br/>(OpenID4VP / DC API / Annex-B)<br/>handled entirely by Credence
  Cloud->>Wallet: wallet credential request<br/>(OpenID4VP / DC API / Annex-B)
  Wallet->>User: consent prompt shown
  User->>Wallet: user approves presentation
  Wallet->>Cloud: signed credential presentation (mDL / VC)

  Cloud->>Cloud: full ISO 18013-5 verification<br/>(issuer signature, IACA trust chain,<br/>device binding, MSO digest, expiry)
  Cloud-->>SDK: SSE event: { status, credentialData }
  SDK-->>App: callback fires with VerificationResult
  App->>SDK: unsubscribe()

The diagram covers six phases:

  1. SDK Initialisation — new CredenceVerifier() → activate() → CloudSDK validates licenseKey + profileId against VwC (customer identity + domain check) → Bearer token returned.
  2. Create Verification Session — createVerificationSession() → CloudSDK generates the session and QR internally → VerificationSession returned to your app.
  3. Subscribe to Results (SSE) — subscribeToVerificationResult() establishes the SSE connection before the QR is shown to the user.
  4. User Scans QR — the orchestrator landing page handles wallet detection and credential request (OpenID4VP / DC API / Annex-B) → signed credential sent to CloudSDK.
  5. Credential Verification — CloudSDK performs full ISO 18013-5 verification in-process (issuer signature, IACA trust chain, device binding, MSO digest integrity, expiry). When the profile requests multiple document types, each presented document is verified independently and the results are aggregated into a single payload → result pushed via SSE. There is no per-document SSE event — the complete set arrives in one terminal event.
  6. Application Processes Result — parseCredentialData() extracts typed CredentialClaims from the primary document; parseCredentialDocuments() extracts all returned documents → unsubscribe() closes the SSE connection.

03Quick Start

This is a complete, self-contained example showing the full lifecycle. Read this first; the sections below explain each step in detail.

import { CredenceVerifier, TERMINAL_STATUSES, parseCredentialData, parseCredentialDocuments } from '@credenceid/verifier-sdk';
import type { VerificationResult, CredentialClaims, CredentialDocument, TerminalStatus } from '@credenceid/verifier-sdk';

// ── 1. Credentials from environment variables ────────────────────────────────
// Vite: VITE_ prefix, import.meta.env  (see Configuration section)
// Next.js: NEXT_PUBLIC_ prefix, process.env
// CRA: REACT_APP_ prefix, process.env
const BASE_URL     = import.meta.env.VITE_BASE_URL        as string;
const LICENSE_KEY  = import.meta.env.VITE_SDK_LICENSE_KEY as string;
const PROFILE_ID   = import.meta.env.VITE_SDK_PROFILE_ID  as string;

// ── 2. Instantiate and activate ───────────────────────────────────────────────
const verifier = new CredenceVerifier({ baseUrl: BASE_URL });

// Fire activation at startup without awaiting — it runs in the background.
// Await this promise just before creating a session (startup latency optimization).
const activationPromise = verifier.activate({
  licenseKey: LICENSE_KEY,
  profileId:  PROFILE_ID,
});

// ── 3. Create a session and subscribe ─────────────────────────────────────────
async function startVerification() {
  // Await activation before proceeding (fast no-op if it already resolved).
  await activationPromise;

  const session = await verifier.createVerificationSession({
    purpose: 'identity_check',
  });

  // qrImageBase64 is guaranteed trimmed and non-empty by the SDK.
  // Handle both bare base64 and data: URI prefixed formats.
  const qrSrc = session.qrImageBase64.startsWith('data:')
    ? session.qrImageBase64
    : `data:image/png;base64,${session.qrImageBase64}`;

  // Open the SSE stream BEFORE showing the QR — ensures you cannot miss a result.
  // subscribeToVerificationResult is async: await it so the connection is
  // established before the user has a chance to scan.
  const unsubscribe = await verifier.subscribeToVerificationResult(
    session.sessionId,
    (result: VerificationResult) => {
      if (TERMINAL_STATUSES.includes(result.status as TerminalStatus)) {
        unsubscribe();          // close the SSE stream immediately
        handleResult(result);
      }
    }
  );

  // Only now show the QR — the SSE stream is already open.
  renderQrCode(qrSrc); // your UI
}

// ── 4. Handle the result ──────────────────────────────────────────────────────
function handleResult(result: VerificationResult) {
  if (result.status !== 'verified') {
    showError(`Verification ended: ${result.status}`);
    return;
  }

  // parseCredentialDocuments() returns one entry per presented credential.
  // Single-document profiles get a one-element array — safe to use unconditionally.
  // Throws a typed SessionError on malformed input.
  let documents: CredentialDocument[];
  try {
    documents = parseCredentialDocuments(result.credentialData);
  } catch {
    showError('Credential data could not be parsed — do not proceed.');
    return;
  }

  for (const doc of documents) {
    console.log('Document type:', doc.docType);          // e.g. 'org.iso.18013.5.1.mDL', null for legacy single-doc
    console.log('Given name:',    doc.claims.given_name);
    console.log('Family name:',   doc.claims.family_name);
  }
}

// ── 5. Cancel if the user dismisses the UI ────────────────────────────────────
// Always close SSE before cancelling — order matters.
async function cancelVerification(sessionId: string, unsubscribe: () => void) {
  unsubscribe();
  await verifier.cancelVerificationSession(sessionId).catch(() => {});
}

04Prerequisites

Runtime requirements

RequirementMinimumNotes
Node.js14.0+Build environment only
BrowserChrome 67+, Firefox 60+, Safari 12+, Edge 79+Requires async/await, Promises, EventSource, fetch
EventSource APINativeRequired for SSE. Polyfillable — see note below.
Fetch APINativeRequired for session management

EventSource and authentication headers. The native browser EventSource API does not support custom request headers. The SDK handles SSE authentication internally (via session tokens embedded in the stream URL). You do not need to configure this — but if you need to polyfill EventSource for legacy targets, use a polyfill that preserves the URL-based auth mechanism. event-source-polyfill is a compatible option.

Running outside the browser. When window is undefined (Node.js or another server runtime), subscribeToVerificationResult() polls the session status every 2 seconds instead of opening an SSE stream. The SDK works there, but a server-side integration should normally receive results by webhook instead of holding a subscription open. renderQRCode() and openVerificationTab() do nothing outside the browser.

Required credentials

All three values are issued by Credence ID at account provisioning. Separate credentials are required for each environment (development, staging, production).

CredentialDescriptionReference
Base URLHTTPS endpoint of the Credence Cloud backendFor a baseUrl, contact Credence ID
License KeyAuthentication key bound to your verification accountGenerate Cloud SDK Key →
Profile IDUUID identifying the verification policy and accepted credential typesWhat a Profile is →

Your licenseKey and profileId must be created at midqa.credenceid.com for the test/playground environment.

Domain-bound license testing. A license key is bound to a single registered domain, so verification must be tested on a deployed site at that domain. Register the domain you will test on and deploy your integration there.

Profile configuration

Before integrating, you need to set up a profile on the VwC portal. A profile controls which credential types are accepted, which attributes are returned, and whether derived booleans (e.g. age_over_21) are used in place of raw fields.

Multiple document types per session. A profile can request more than one document type (for example, an mDL and a Photo ID). When it does, the wallet prompts the holder for each requested document they hold. Presentation of each document type is optional at the wallet level — the holder may present a subset of the requested types. Your application must therefore validate that every document type it requires is actually present in the result (see Multi-document verification below). Single-document profiles are unaffected.

For a full explanation of what a profile is and how to find your Profile ID, see What a Profile is.

Profiles are configured in the VwC portal. Attributes are organised into groups — only the attributes you enable are returned in credentialData:

  • Demographic: Given Name (given_name), Family Name (family_name), Birth Date (birth_date), Birth Year, Birth Place, Gender (sex / gender), Nationality
  • Address: Address (resident_address), City, State, Postal Code, Country
  • Document / Issuer: Doc # (document_number / doc_number), Issuing Authority, Issuing Country, Issuing Jurisdiction, Issue Date, Expiry Date, Admin Number
  • Biometrics: Portrait (portrait, base64 JPEG), Signature, Height, Weight, Eye Color, Hair Color

Age attestation: configure the profile to return a derived boolean — the age math runs server-side and your application receives a simple yes/no:

Portal optionReturned claim keyValue
18+age_over_18true / false
21+age_over_21true / false
Custom ageage_over_NNtrue / false

Example — name verification profile: enable Given Name, Family Name, Birth Date:

const claims = parseCredentialData(result.credentialData)
// { given_name: "Jane", family_name: "Doe", birth_date: "1990-01-15" }

Example — age-gate profile (21+): enable only age_over_21, disable everything else:

const claims = parseCredentialData(result.credentialData)
if (claims.age_over_21 === true) { /* user is 21+ */ }

Profiles are created and managed directly in the VwC portal. Once a profile is created, copy the profileId from the portal and use it in your SDK configuration.


05Installation

@credenceid/verifier-sdk is published to the public npm registry. No .npmrc configuration or authentication is required before installing.

npm install @credenceid/verifier-sdk

Then import it in your code:

import { CredenceVerifier } from '@credenceid/verifier-sdk';
import type { VerificationResult } from '@credenceid/verifier-sdk';

06Configuration

Injecting credentials via environment variables

Never hardcode credentials in source code. Always inject them through your build system's environment variable mechanism and exclude credential files from version control (add .env to .gitignore).

Vite

# .env
VITE_BASE_URL=CLOUDSDK_BASE_URL
VITE_SDK_LICENSE_KEY=CS_xxxx
VITE_SDK_PROFILE_ID=xxxx-xxxx-xxxx-xxxx
// Access in browser code:
const baseUrl    = import.meta.env.VITE_BASE_URL;
const licenseKey = import.meta.env.VITE_SDK_LICENSE_KEY;
const profileId  = import.meta.env.VITE_SDK_PROFILE_ID;

Next.js

# .env.local
NEXT_PUBLIC_BASE_URL=CLOUDSDK_BASE_URL
NEXT_PUBLIC_SDK_LICENSE_KEY=CS_xxxx
NEXT_PUBLIC_SDK_PROFILE_ID=xxxx-xxxx-xxxx-xxxx
// Access in client components:
const baseUrl    = process.env.NEXT_PUBLIC_BASE_URL;
const licenseKey = process.env.NEXT_PUBLIC_SDK_LICENSE_KEY;
const profileId  = process.env.NEXT_PUBLIC_SDK_PROFILE_ID;

Create React App

# .env
REACT_APP_BASE_URL=CLOUDSDK_BASE_URL
REACT_APP_SDK_LICENSE_KEY=CS_xxxx
REACT_APP_SDK_PROFILE_ID=xxxx-xxxx-xxxx-xxxx
const baseUrl    = process.env.REACT_APP_BASE_URL;
const licenseKey = process.env.REACT_APP_SDK_LICENSE_KEY;
const profileId  = process.env.REACT_APP_SDK_PROFILE_ID;

Configuration object

PropertyTypeRequiredDescription
baseUrlstringYesHTTPS base URL of the Credence Cloud backend
licenseKeystringYesLicense key associated with the verification account
profileIdstringYesProfile ID defining the verification policy

07SDK Initialization

CredenceVerifier — Constructor

Purpose: Instantiates the SDK client. Create one instance per set of credentials.

new CredenceVerifier(options: { baseUrl: string }): CredenceVerifier
ParameterTypeRequiredDescription
options.baseUrlstringYesHTTPS base URL of the Credence Cloud backend

Why aren't credentials in the constructor? The constructor accepts only baseUrl because endpoint configuration is separate from authentication. Credentials (licenseKey, profileId) are passed to activate() instead. This allows you to instantiate the client at module load time and activate it separately — which enables the startup-latency optimization described below.

const verifier = new CredenceVerifier({ baseUrl: config.baseUrl });

activate()

Purpose: Authenticates the SDK instance against the backend. Must resolve before calling createVerificationSession().

verifier.activate(options: {
  licenseKey: string;
  profileId: string;
  webhookUrl?: string;
}): Promise<void>
ParameterTypeRequiredDescription
options.licenseKeystringYesLicense key
options.profileIdstringYesProfile ID
options.webhookUrlstringNoYour server endpoint for webhook delivery of session results. See Webhooks.

Returns: Promise<void> — resolves when the backend confirms authentication.

Throws:

  • AuthenticationError — credentials are invalid or expired
  • NetworkError — backend is unreachable

Two valid activation patterns

Pattern 1 — Startup activation (recommended when credentials come from environment variables). Call activate() at app startup without awaiting it. Store the returned Promise and await it just before calling createVerificationSession(). This allows authentication to run in parallel with the user navigating to the verification screen, eliminating the wait when verification actually starts.

// At app startup — fire and store, do not await:
const activationPromise = verifier.activate({
  licenseKey: config.licenseKey,
  profileId:  config.profileId,
});

// Later, just before creating a session — await here:
await activationPromise; // fast no-op if already resolved
const session = await verifier.createVerificationSession({ purpose: 'identity_check' });

Pattern 2 — On-demand activation (when credentials come from user input at runtime). If credentials are entered by the user at runtime (e.g. a configuration form), you cannot fire activation at startup. Simply await activate() directly when the user submits.

// After the user submits their credentials:
await verifier.activate({ licenseKey, profileId });
const session = await verifier.createVerificationSession({ purpose: 'identity_check' });

Both patterns are correct. Pattern 1 only provides a benefit when credentials are available before the user reaches the verification screen.

On activation failure: Catch the error, surface a message to the user, and recreate the CredenceVerifier instance before retrying. A failed activation leaves the instance in an indeterminate state.

Webhooks

Pass webhookUrl to activate() to have the Orchestrator POST session results to your server. Use this for server-side integrations instead of holding an SSE subscription or polling loop open.

Every webhook body is signed with HMAC-SHA256, and the signature is sent in the X-Credence-Signature header as sha256=<hex-digest>. Verify it with verifyWebhookSignature() before trusting the payload:

verifyWebhookSignature(payload: string, signature: string, secret: string): Promise<boolean>
ParameterTypeDescription
payloadstringThe raw request body. Do not parse the JSON first — the signature is computed over the exact bytes received.
signaturestringThe value of the X-Credence-Signature header.
secretstringYour shared webhook signing secret, issued by Credence ID.

Returns: Promise<boolean> — true if the signature is valid.

import { verifyWebhookSignature } from '@credenceid/verifier-sdk';

// Express example — use a raw body parser so the body is not re-serialised.
app.post('/credence/webhook', express.text({ type: '*/*' }), async (req, res) => {
  const isValid = await verifyWebhookSignature(
    req.body,                                  // raw request body string
    req.header('x-credence-signature') ?? '',  // "sha256=..."
    process.env.CREDENCE_WEBHOOK_SECRET!,
  );
  if (!isValid) return res.status(401).send('Invalid signature');

  // Signature is valid — process the session result.
  res.sendStatus(200);
});

08Verification Flow

The complete orchestrator verification lifecycle:

  1. Activate — authenticate the SDK against the backend (at startup or on demand).
  2. Create Session — call createVerificationSession() to receive a session ID, QR code image, and expiry timestamp.
  3. Subscribe — call subscribeToVerificationResult() and await it. This opens the SSE stream. Do this before showing the QR code to the user.
  4. Display QR — show the QR code. The end user scans it with their phone to open the orchestrator landing page.
  5. Receive Result — the callback fires when a terminal status arrives. Call unsubscribe() immediately.
  6. Process Claims — if status === 'verified', parse credentialData and extract identity claims.

Why subscribe before showing the QR? subscribeToVerificationResult() resolves once the SSE connection is established. If you show the QR first and the user scans and verifies before the SSE connection opens, you will miss the result event.

createVerificationSession()

Purpose: Creates a new verification session on the Credence Cloud backend. Returns a QR code image for the end user to initiate credential presentation from their digital wallet.

verifier.createVerificationSession(
  options: { purpose: string; referenceId?: string; returnUrl?: string }
): Promise<VerificationSession>
ParameterTypeRequiredDescription
options.purposestringYesDescribes the intent of the verification request (e.g., identity_check). Used for logging and auditing. This field is not validated by the backend — use a consistent, human-readable string across your application.
options.referenceIdstringNoAn optional application-supplied correlation ID (e.g. an order ID or internal transaction ID) attached to the session. Useful for cross-referencing sessions against your own systems and against per-transaction evidence exported from the Verify with Credence portal. Not validated by the backend.
options.returnUrlstringNoWhere the landing page sends the browser back to in the same-device flow. Must be HTTPS.

Returns: Promise<VerificationSession>

FieldTypeDescription
sessionIdstringUnique identifier for the verification session
qrImageBase64stringBase64-encoded QR code image. May include a data:image/png;base64, prefix or be a bare base64 string — handle both.
qrUrlstringThe orchestrator landing page URL encoded by the QR code. On mobile, navigate to it directly instead of showing a QR — see Same-device flow.
expiresAtDateSession expiry as a Date object. Use it to display a countdown timer or to check whether a session is still valid (session.expiresAt.getTime() > Date.now()).

Throws:

  • SessionCreationError — backend rejected the session request
  • NetworkError — backend is unreachable
await activationPromise; // ensure activation has resolved

const session = await verifier.createVerificationSession({
  purpose: 'identity_check',
});

// Trim whitespace before inspecting — some backends include a leading space.
// Guard against empty string before constructing the data: URI.
const qrRaw = session.qrImageBase64.trim();
if (!qrRaw) throw new Error('createVerificationSession returned an empty qrImageBase64');
const qrSrc = qrRaw.startsWith('data:')
  ? qrRaw
  : `data:image/png;base64,${qrRaw}`;

renderQRCode()

Purpose: Convenience helper that adds the QR code as an <img> to a container element.

verifier.renderQRCode(
  qrImageBase64: string,
  container: string | HTMLElement
): { remove: () => void }
ParameterTypeRequiredDescription
qrImageBase64stringYesThe image source. It is used as the <img> src unchanged, so pass the data: URI (qrSrc above), not a bare base64 string.
containerstring | HTMLElementYesA CSS selector or element to append the image to. Throws if a selector matches nothing.

Returns: { remove } — call remove() to take the image out of the page, e.g. when the session ends.

// Subscribe first, then show the QR:
const qr = verifier.renderQRCode(qrSrc, '#qr-container');

// Later, on a terminal status or when the user dismisses the UI:
qr.remove();

openVerificationTab()

Purpose: Opens the session's qrUrl in a new browser tab — useful for a "verify on this device" button on desktop.

verifier.openVerificationTab(session: VerificationSession): Window | null

Returns: the opened Window, or null if the browser blocked the pop-up.

Call openVerificationTab() directly inside a click handler. Browsers block window.open() that is not triggered by a user gesture — for example, after an await.

// session was created (and subscribed) before the button was shown.
verifyHereButton.addEventListener('click', () => {
  const tab = verifier.openVerificationTab(session);
  if (!tab) showError('Please allow pop-ups to continue.');
});

Same-device flow

When the user is already on their phone, they cannot scan a QR shown on the same screen. Instead, send the browser to the landing page and let it return to your app when the session ends:

  1. Create the session with a returnUrl (HTTPS) that points back to your app.
  2. Set window.location.href = session.qrUrl instead of showing a QR.
  3. The user presents their credential. On any terminal state, the landing page redirects to returnUrl with cid_session and cid_status query parameters added.
  4. On your return page, read both parameters, remove them from the address bar with history.replaceState, then call getVerificationStatus(cid_session) and use snapshot.result.
// 1–2. Start the flow on mobile:
const session = await verifier.createVerificationSession({
  purpose: 'identity_check',
  returnUrl: 'https://app.example.com/verify/return',
});
window.location.href = session.qrUrl;
// 4. On the return page:
const params = new URLSearchParams(window.location.search);
const sessionId = params.get('cid_session');
const status = params.get('cid_status'); // informational — confirm with getVerificationStatus()

if (sessionId) {
  // Remove the parameters so a refresh or shared link does not replay them.
  params.delete('cid_session');
  params.delete('cid_status');
  const query = params.toString();
  history.replaceState(null, '', window.location.pathname + (query ? `?${query}` : ''));

  await activationPromise;
  const snapshot = await verifier.getVerificationStatus(sessionId);
  if (snapshot.result) handleResult(snapshot.result);
}

Treat cid_status as a hint only. Anyone can edit a URL, so always confirm the outcome with getVerificationStatus() before trusting it.

subscribeToVerificationResult()

Purpose: Opens a Server-Sent Events (SSE) stream for a verification session. The provided callback is invoked for each status update. Returns a Promise that resolves to an unsubscribe function once the SSE connection is established.

verifier.subscribeToVerificationResult(
  sessionId: string,
  callback: (result: VerificationResult) => void
): Promise<() => void>
ParameterTypeRequiredDescription
sessionIdstringYesThe sessionId returned by createVerificationSession()
callbackfunctionYesInvoked when the session reaches a terminal status. Check result.status and call unsubscribe().

Returns: Promise<() => void> — must be awaited. The Promise resolves once the SSE connection to the backend is established and yields the unsubscribe function. If you do not await this call, the returned value is a Promise, not a function — your callback will not fire and calling it will throw a TypeError.

// ✗ Wrong — missing await, callback never fires:
const unsubscribe = verifier.subscribeToVerificationResult(id, cb);

// ✓ Correct:
const unsubscribe = await verifier.subscribeToVerificationResult(id, cb);

Throws:

  • SubscriptionError — failed to open the SSE stream

A connection that drops after the stream opens does not throw or call the callback — see Dropped SSE Connection.

Terminal statuses

StatusDescription
verifiedThe user presented a valid credential. credentialData is populated.
deniedThe credential was rejected — policy requirements not met, credential is invalid, or credential has been revoked.
failedA technical failure occurred during the verification process.
expiredThe session timed out before the user completed verification.
cancelledThe session was explicitly cancelled by the application.

Call unsubscribe() immediately on any terminal status. An unclosed SSE subscription maintains an open HTTP connection to the backend until the session expires server-side.

import { TERMINAL_STATUSES } from '@credenceid/verifier-sdk';
import type { TerminalStatus, VerificationResult } from '@credenceid/verifier-sdk';

const unsubscribe = await verifier.subscribeToVerificationResult(
  session.sessionId,
  (result: VerificationResult) => {
    if (TERMINAL_STATUSES.includes(result.status as TerminalStatus)) {
      unsubscribe();
      handleResult(result);
    }
  }
);

09VerificationResult Schema

FieldTypeAlways presentDescription
statusSessionStatusYesSession status. The full union is created | qr_displayed | opened | in_progress | fallback_started | verified | denied | failed | expired | cancelled. The subscription callback only fires for the five terminal values (TERMINAL_STATUSES).
sessionIdstringYesThe session identifier this result is associated with
purposestringYesThe purpose passed to createVerificationSession()
decisionstringNoThe backend's decision for the session, when provided
verifiedAtnumberNoTime the verification completed, when provided
credentialDatastringOnly when status === 'verified'JSON-encoded identity claims for one or more documents. Pass to parseCredentialData() (primary document) or parseCredentialDocuments() (all documents) — do not call JSON.parse() directly. See Credential Data.

credentialData is a JSON-encoded string, not a parsed object. Accessing result.credentialData.given_name directly will return undefined. Always use parseCredentialData(result.credentialData) from the SDK — it handles JSON parsing, envelope detection, and type coercion correctly.

Example payload:

{
  "status": "verified",
  "sessionId": "sess_01J4KRTMZ9VXWP3Q8FMCN7B5D",
  "purpose": "identity_check",
  "credentialData": "{\"given_name\":\"Jane\",\"family_name\":\"Doe\",\"birth_date\":\"1990-01-15\",\"portrait\":\"base64encodedimage...\"}"
}

Example payload — multi-document profile (mDL + Photo ID):

{
  "status": "verified",
  "sessionId": "sess_01J4KRTMZ9VXWP3Q8FMCN7B5D",
  "purpose": "identity_check",
  "credentialData": "{\"identity\":{\"given_name\":\"Jane\",\"family_name\":\"Doe\"},\"documents\":[{\"docType\":\"org.iso.18013.5.1.mDL\",\"identity\":{\"given_name\":\"Jane\",\"family_name\":\"Doe\",\"birth_date\":\"1990-01-15\"},\"authentication\":{\"authenticationResult\":\"SUCCESS\",\"attributeValidationStatus\":\"OK\"}},{\"docType\":\"eu.europa.ec.eudi.pid.1\",\"identity\":{\"given_name\":\"Jane\",\"portrait\":\"base64...\"},\"authentication\":{\"authenticationResult\":\"SUCCESS\"}}]}"
}

10Credential Data

Parsing

Use parseCredentialData() exported from the SDK. Do not call JSON.parse() directly — the SDK helper handles all known payload variants correctly and throws a typed SessionError on malformed input.

import { parseCredentialData } from '@credenceid/verifier-sdk';
import type { CredentialClaims } from '@credenceid/verifier-sdk';

if (result.status === 'verified') {
  let claims: CredentialClaims;
  try {
    claims = parseCredentialData(result.credentialData);
  } catch {
    // SessionError thrown — malformed payload, do not proceed.
    handleError('Credential data could not be parsed.');
    return;
  }

  const givenName  = claims.given_name;
  const familyName = claims.family_name;
}

parseCredentialData() handles the following automatically so you don't have to. The payload may arrive in one of three formats depending on the credential type and profile configuration — the helpers resolve all three transparently:

Format A — Flat object (most credential types)

{ "given_name": "Jane", "family_name": "Doe", "birth_date": "1990-01-15" }

Format B — Claims nested under an identity key (some credential types)

{ "identity": { "given_name": "Jane", "family_name": "Doe" } }

Format C — Multi-document envelope (profiles that request multiple document types)

{
  "identity": { "given_name": "Jane", "family_name": "Doe" },
  "documents": [
    { "docType": "org.iso.18013.5.1.mDL",   "identity": { "given_name": "Jane", "family_name": "Doe" }, "authentication": { "authenticationResult": "SUCCESS" } },
    { "docType": "eu.europa.ec.eudi.pid.1", "identity": { "given_name": "Jane" },                        "authentication": { "authenticationResult": "SUCCESS" } }
  ]
}

In Format C the top-level identity mirrors documents[0] for backward compatibility. parseCredentialData() returns the first document's claims only — existing single-document integrations keep working with no changes. To access every returned document, use parseCredentialDocuments().

Envelope detection is defensive in both directions: identity is only treated as an envelope when it is a plain object, and documents is only treated as a multi-document envelope when it is a non-empty array of plain objects. A flat credential with a string or number field named identity or documents is handled correctly.

Which format will I receive? Format depends on the credential type the user presents and the profile configuration for your account. The helpers handle all three — do not rely on a single format in production.


11Multi-document verification

parseCredentialDocuments()

Purpose: Parses the credentialData string and returns all returned credentials — one CredentialDocument per presented document. Use this instead of parseCredentialData() whenever your profile requests more than one document type. Single-document (legacy) payloads are normalised to a one-element array, so it is safe to use unconditionally.

parseCredentialDocuments(credentialData: string | null | undefined): CredentialDocument[]

Throws: SessionError with code CREDENTIAL_PARSE_ERROR if credentialData is absent, empty, or not valid JSON — same contract as parseCredentialData().

CredentialDocument

FieldTypeDescription
docTypestring | nullISO document type of the presented credential (e.g. org.iso.18013.5.1.mDL). null for legacy single-document payloads or flows that do not carry a doctype.
claimsCredentialClaimsIdentity claims for this document. Same shape and coercion rules as parseCredentialData() — sex normalised to number, both document_number and doc_number preserved.
authenticationDocumentAuthentication | undefinedPer-document verification status, when provided by the backend.

DocumentAuthentication — every field is optional (?), so check for undefined before use. All values are passed through from the backend unmodified. Status values are UPPERCASE — compare case-insensitively (?.toUpperCase() === 'FAILURE').

FieldTypeDescription
authenticationResult?string'SUCCESS' | 'WARNING' | 'FAILURE' — cryptographic verification outcome for this document.
attributeValidationStatus?string'OK' | 'WARNING' | 'FAILURE' — whether the requested attributes were returned.
missingMandatoryAttributes?string[]Requested mandatory attributes absent from the presentation.
missingOptionalAttributes?string[]Requested optional attributes absent from the presentation.
issuerRecognized?booleanIssuer certificate found on the configured trust list.
issuerSignedAuthenticated?booleanIssuer (MSO) signature verified.
deviceSignedAuthenticated?booleanDevice binding signature verified.
dataIntegrity?booleanMSO digest integrity check passed.
msoValidity?stringMSO validity window state, e.g. 'Valid'.
issuerSubjectInfo?stringSubject DN of the issuer signing certificate, e.g. 'C=US,CN=...'.
certValidationError?stringCertificate validation errors as a JSON-encoded array string, e.g. '[]'.
import { parseCredentialDocuments } from '@credenceid/verifier-sdk';
import type { CredentialDocument } from '@credenceid/verifier-sdk';

if (result.status === 'verified') {
  let documents: CredentialDocument[];
  try {
    documents = parseCredentialDocuments(result.credentialData);
  } catch {
    handleError('Credential data could not be parsed.');
    return;
  }

  // Validate that every document type you require is present.
  const mdl = documents.find((d) => d.docType === 'org.iso.18013.5.1.mDL');
  if (!mdl) {
    handleError('Required document (mDL) was not presented.');
    return;
  }

  // Check per-document verification status (values are uppercase —
  // compare case-insensitively).
  for (const doc of documents) {
    if (doc.authentication?.authenticationResult?.toUpperCase() === 'FAILURE') {
      handleError(`Document ${doc.docType} failed verification.`);
      return;
    }
  }

  const givenName = mdl.claims.given_name;
}

The wallet may return a subset of requested documents. Multi-document requests are optional-presentation at the wallet level: the holder presents whichever of the requested document types they hold. Never assume documents.length equals the number of document types configured in your profile — always validate the presence of each docType your application requires before proceeding.

Per-document duplicate keys. The document_number ?? doc_number resolution, sex/gender fallback, and portrait base64-prefix handling described in Claim Reference apply per document — resolve them on each CredentialDocument.claims individually, not once per session.

Choosing a helper:

Your profile requestsUse
One document typeparseCredentialData() — unchanged, no migration needed
Multiple document typesparseCredentialDocuments() — the only way to access documents beyond the first

12Claim Reference

Claim availability depends on the credential type and the profile configuration for your account. In multi-document results these claims apply per document (CredentialDocument.claims) — each document carries its own independent claim set. Always validate field presence before use.

ClaimTypeDescription
given_namestringFirst or given name(s)
family_namestringLast or family name
birth_datestringDate of birth — ISO 8601 date: YYYY-MM-DD
expiry_datestringDocument expiry date — ISO 8601 date: YYYY-MM-DD
document_numberstringPrimary document number. If absent, check doc_number.
doc_numberstringAlternate document number key. Present on some credential types in place of document_number.
admin_numberstringAdministrative or inventory control number
nationalitystringNationality
issuing_countrystringCountry that issued the document
issuing_authoritystringAuthority that issued the document
sexnumberGender per ISO/IEC 5218: 1 = male, 2 = female. Backends variously return an integer, a numeric string ("1"/"2"), or a word ("FEMALE", "male", "M", "F") — parseCredentialData() / parseCredentialDocuments() normalise all known variants to the numeric code. If absent, check gender.
genderstringAlternate gender key. String values: Male, Female, M, F.
portraitstringFacial photograph. Base64-encoded JPEG. May include a data:image/jpeg;base64, prefix or be a bare base64 string — handle both.
heightnumberSubject height in centimetres
weightnumberSubject weight in kilograms
resident_addressstringStreet address
resident_citystringCity or municipality
resident_statestringState or province
resident_postal_codestringZIP or postal code
resident_countrystringCountry of residence
signaturestringSignature image. Base64-encoded string.
issue_datestringDocument issue date — ISO 8601. mDL key; EU PID credentials use issuance_date.
issuance_datestringAlternate issue-date key — present on EU PID credentials.
administrative_numberstringAlternate administrative-number key (ISO 18013-5 element name). If absent, check admin_number.
eye_colourstringAlternate eye-color key (British spelling, ISO 18013-5 element name). If absent, check eye_color.
hair_colourstringAlternate hair-color key (British spelling). If absent, check hair_color.
age_in_yearsnumberHolder age in completed years, when the profile requests it.
age_birth_yearnumberHolder birth year, when the profile requests it.

Credentials may carry additional type-specific claims not listed here (e.g. driving_privileges, portrait_capture_date, signature_usual_mark, birth_place, family_name_birth, email_address, mobile_phone_number, personal_administrative_number, resident_street, resident_house_number, issuing_jurisdiction). All are preserved on the returned claims object and accessible via index access — only the claims your profile enables are returned.

Handling duplicate keys

Some claim concepts have two possible keys depending on the credential type. Both are preserved on the CredentialClaims object returned by parseCredentialData():

// Always use ?? (nullish coalescing), never || (logical OR).
// Document numbers like "0" are falsy — || would silently discard a valid value.
const documentNumber = claims.document_number ?? claims.doc_number;
const adminNumber    = claims.admin_number ?? claims.administrative_number;
const eyeColor       = claims.eye_color ?? claims.eye_colour;
const issueDate      = claims.issue_date ?? claims.issuance_date;

// sex is normalised to a number by the SDK — integers, numeric strings
// ("1"/"2"), and words ("FEMALE", "male", "M", "F") all become 1 or 2.
// 1 = male, 2 = female per ISO/IEC 5218.
const sex    = claims.sex;    // number | undefined
const gender = claims.gender; // "Male" | "Female" | "M" | "F" | undefined

Age verification — derived boolean attributes

For age-gating use cases (e.g. alcohol or tobacco sales), you do not need to request birth_date or portrait. The Credence Profile can be configured to return a derived boolean instead — the age math runs server-side and your application receives a simple yes/no:

ClaimTypeDescription
age_over_18booleantrue if the credential holder is 18 or older at the time of verification
age_over_21booleantrue if the credential holder is 21 or older at the time of verification

An age-gate profile requests only these attributes. birth_date, portrait, signature, address, and document_number are never requested and never returned, so they never reach your application. This avoids biometric data controller obligations under BIPA, GDPR Article 9, and similar regulations.

Configure the profile in the Verify with Credence portal before integration. Contact Credence ID to enable a minimal age-gate profile for your account.

// Age-gate result — no birth_date or portrait ever present
if (result.status === 'verified' && result.credentialData) {
  const claims = parseCredentialData(result.credentialData);
  const isOver21 = claims.age_over_21;

  if (isOver21 === true) {
    proceedWithSale();
  } else {
    denyAgeRestrictedSale(); // false or undefined both mean deny
  }
}

Do not derive age from birth_date yourself. Timezone edge cases on a customer's birthday, DST transitions, and calendar arithmetic are error-prone. The age_over_NN boolean is calculated server-side with the correct reference time and is the safe, compliant path.

String attestations. Some wallets return the attestation as the string "TRUE" / "FALSE" rather than a boolean. From SDK v0.3.1, parseCredentialData() and parseCredentialDocuments() coerce these to real booleans (any casing), so the claims.age_over_21 === true pattern shown here is always safe. On v0.3.0 and earlier this comparison silently fails against such payloads — upgrade rather than working around it.

Also note: age_over_NN values apply per document in multi-document results. The EU PID document typically carries age_over_18; check the claims of the specific document you are gating on.

Handling the portrait image

const portraitRaw = claims.portrait as string | undefined;
if (portraitRaw) {
  const portraitSrc = portraitRaw.startsWith('data:')
    ? portraitRaw
    : `data:image/jpeg;base64,${portraitRaw}`;
  // Use portraitSrc as an <img> src
}

13Error Handling

ScenarioCauseRecommended Action
Activation failureInvalid or expired credentialsVerify all three credential values. Recreate the CredenceVerifier instance and call activate() before retrying.
Activation failureBackend unreachableCheck network connectivity. Retry with exponential backoff.
Session creation failureactivate() not yet resolvedEnsure activationPromise has resolved before calling createVerificationSession().
Session creation failureBackend rejected the requestCheck that credentials are valid and profile ID is correct. Retry once.
Subscription failureNetwork error before SSE stream openedRetry subscribeToVerificationResult() once. If it fails again, create a new session.
SSE connection dropped mid-sessionNetwork interruption during verificationSee Dropped SSE Connection.
Session expiredUser did not complete verification within the session windowThe session is already terminated server-side — do not call cancelVerificationSession(). Create a new session if the user wants to retry.
Verification deniedCredential fails policy validation, is invalid, or has been revokedSee denied sub-statuses below.
Verification failedTechnical failure during verification processInform the user. Create a new session and offer retry.
credentialData absent on verifiedUnexpected backend responseDo not proceed with partial identity data. Treat as a failed verification and surface an error.
credentialData malformedJSON parse errorSame as above — do not proceed. Log the raw value for debugging.
Expected document type absent from documents[]Holder presented a subset of the requested document typesValidate each required docType after parsing. Treat a missing required document as a failed verification and offer retry.
Per-document authenticationResult is 'Failure' or 'Warning'One document in a multi-document presentation failed or partially failed verificationCheck authentication on every CredentialDocument — do not rely on the session-level verified status alone.

denied — understanding why

A denied result currently covers three distinct causes that the SDK does not sub-classify:

CauseWhat it meansSuggested UX
Policy not metThe presented credential does not satisfy the requirements of your Profile (e.g. wrong credential type, missing required attribute)"This credential type is not accepted. Please try a different ID."
Credential invalidThe issuer signature or cryptographic chain failed verification"Your credential could not be verified. Please contact your issuer."
Credential revokedThe issuer has revoked this credential"Your credential has been revoked. Please contact your issuer."

Differentiating error types

The SDK exports its error classes — ActivationError, SessionError, and UnauthorizedError — so instanceof checks work directly. SessionError carries a code field (e.g. CREDENTIAL_PARSE_ERROR).

import { ActivationError, SessionError } from '@credenceid/verifier-sdk';

try {
  await verifier.activate({ licenseKey, profileId });
} catch (err) {
  if (err instanceof ActivationError) {
    // Show "Check your license key and profile ID"
  } else {
    // Show "Connection error — check your network and try again"
  }
}

14Dropped SSE Connection — Recovery

SSE connections can be interrupted by network conditions, particularly on mobile. The SDK retries the stream up to three times. If it still cannot reconnect, the stream ends silently — the callback is never called with an error, and it only ever receives results. The session itself may still be valid, and the user may already have completed verification.

Recovery strategy. Decide in your app when a session looks stalled — for example on the browser's online event, when the tab becomes visible again, or when expiresAt is close — and query the session with getVerificationStatus():

import { TERMINAL_STATUSES } from '@credenceid/verifier-sdk';
import type { TerminalStatus } from '@credenceid/verifier-sdk';

async function recoverSession(sessionId: string) {
  try {
    const snapshot = await verifier.getVerificationStatus(sessionId);

    if (TERMINAL_STATUSES.includes(snapshot.state.toLowerCase() as TerminalStatus)) {
      // Session already ended — the result is on snapshot.result.
      unsubscribe();
      if (snapshot.result) handleResult(snapshot.result);
    } else {
      // Session still open — re-subscribe or create a new session.
      await resubscribeOrNewSession();
    }
  } catch {
    // Cannot reach backend — show a "connection lost" message.
    showConnectionError();
  }
}

window.addEventListener('online', () => recoverSession(session.sessionId));

If re-subscribing to the same session, call subscribeToVerificationResult() again with the same sessionId. The session remains valid until expiresAt.

If the session has expired or cannot be recovered, create a new session with createVerificationSession().


15cancelVerificationSession()

Purpose: Instructs the Credence Cloud backend to invalidate an active session. Call this when the user dismisses the verification UI before a terminal status has been received. Orphaned sessions remain open on the backend until they expire server-side.

verifier.cancelVerificationSession(sessionId: string): Promise<void>
ParameterTypeRequiredDescription
sessionIdstringYesThe sessionId of the session to cancel

Returns: Promise<void> — non-fatal if it rejects. The backend expires the session automatically if the cancellation cannot be delivered. Always add .catch(() => {}) to prevent unhandled Promise rejections.

When to call:

  • The user closes or dismisses the verification UI while waiting for a result
  • The application resets or navigates away while a session is active
  • An application error prevents normal flow completion

When NOT to call:

  • After receiving any terminal status (verified, denied, failed, expired, cancelled) — the session is already closed server-side

Always close the SSE subscription before calling cancelVerificationSession(). Due to network timing, a cancelled SSE event may still arrive in the callback after cancelVerificationSession() is called. Guard against this in the callback:

// Correct order — unsubscribe first, then cancel:
unsubscribe?.();
await verifier.cancelVerificationSession(session.sessionId).catch(() => {});

// Defensive callback — ignore events that arrive after unsubscribe:
let active = true;
const unsubscribe = await verifier.subscribeToVerificationResult(
  session.sessionId,
  (result) => {
    if (!active) return; // discard late-arriving events
    if (TERMINAL_STATUSES.includes(result.status as TerminalStatus)) {
      active = false;
      unsubscribe();
      handleResult(result);
    }
  }
);

// When dismissing the UI:
active = false;
unsubscribe?.();
await verifier.cancelVerificationSession(session.sessionId).catch(() => {});

Token expiry during long-lived sessions

The SDK manages token refresh automatically. Before each API call it checks whether the current token is within 30 seconds of expiry and re-activates transparently. If a 401 is returned unexpectedly (e.g. after a server restart), the SDK re-activates once and retries. If re-activation itself fails (e.g. the license key is revoked), an AuthenticationError is thrown to the caller.

For sessions that remain open for an extended period (e.g. the user leaves the QR on screen for several minutes), no extra handling is needed — token refresh is handled internally.


16getVerificationStatus()

Purpose: Retrieves a point-in-time snapshot of session status via a REST call. Use this as a fallback when the SSE stream is unavailable — for example, to check whether the user completed verification before a dropped connection occurred.

verifier.getVerificationStatus(sessionId: string): Promise<SessionStatusResponse>
ParameterTypeRequiredDescription
sessionIdstringYesThe session ID to query

Returns: Promise<SessionStatusResponse>

FieldTypeDescription
sessionIdstringThe session identifier
stateSessionStatusCurrent session state. Same values as VerificationResult.status. Compare case-insensitively (state.toLowerCase()).
purposestringThe purpose passed to createVerificationSession()
referenceIdstring | undefinedThe referenceId passed to createVerificationSession(), if any
qrUrlstringThe orchestrator landing page URL
qrImageBase64stringThe QR code image
expiresAtDateSession expiry
resultVerificationResult | undefinedThe session result once it has reached a terminal state. Read credentials from snapshot.result?.credentialData.

There is no status, terminal, or top-level credentialData field — use state and result.

Primary use case — SSE failure recovery:

import { TERMINAL_STATUSES } from '@credenceid/verifier-sdk';
import type { TerminalStatus } from '@credenceid/verifier-sdk';

try {
  const snapshot = await verifier.getVerificationStatus(session.sessionId);

  if (TERMINAL_STATUSES.includes(snapshot.state.toLowerCase() as TerminalStatus)) {
    // Session already ended — process the result
    if (snapshot.result) handleResult(snapshot.result);
  } else {
    // Session still open — user hasn't finished yet
    // Re-subscribe to the existing session:
    const newUnsubscribe = await verifier.subscribeToVerificationResult(
      session.sessionId,
      (result) => { /* ... */ }
    );
  }
} catch {
  // Cannot reach backend — create a new session
  startVerification();
}

17API Reference

MethodDescriptionReturns
new CredenceVerifier(options)Instantiate the SDK clientCredenceVerifier
.activate(options)Authenticate the SDK instance against the backendPromise<void>
.createVerificationSession(options)Create a new verification session; returns QR code and session IDPromise<VerificationSession>
.renderQRCode(qrImageBase64, container)Add the QR code as an <img> to a container{ remove: () => void }
.openVerificationTab(session)Open qrUrl in a new tab; call inside a click handlerWindow | null
.subscribeToVerificationResult(sessionId, callback)Open an SSE stream for a session (polling outside the browser); resolves to an unsubscribe function once connectedPromise<() => void>
.cancelVerificationSession(sessionId)Invalidate an active session on the backendPromise<void>
.getVerificationStatus(sessionId)Retrieve a session snapshot via REST (SSE recovery, same-device return)Promise<SessionStatusResponse>
verifyWebhookSignature(payload, signature, secret)Verify the X-Credence-Signature header on a webhook POSTPromise<boolean>
parseCredentialData(credentialData)Parse claims from the primary (first) document — handles Formats A, B, and CCredentialClaims
parseCredentialDocuments(credentialData)Parse all returned documents; legacy payloads normalise to a one-element arrayCredentialDocument[]

18Integration Checklist

Use this as a pre-launch review against your integration. Every item should be verifiable in your code.

Setup

  • SDK package installed; TypeScript types imported with import type
  • All three credentials (Base URL, License Key, Profile ID) sourced from environment variables — not hardcoded in source
  • .env (or equivalent credential file) added to .gitignore
  • Framework-correct env var prefix used (VITE_, NEXT_PUBLIC_, REACT_APP_) — see Configuration

Activation

  • CredenceVerifier instance created with baseUrl only
  • activate() called with licenseKey and profileId
  • Activation pattern matches your use case (startup Promise storage vs. direct await — see Two valid activation patterns)
  • activate() errors are caught and surfaced to the user with an actionable message

Session creation

  • activationPromise awaited (or activate() awaited directly) before calling createVerificationSession()
  • qrImageBase64 rendered with data: URI prefix detection (both bare and prefixed formats handled)

Subscription

  • subscribeToVerificationResult() is awaited before showing the QR code to the user
  • Callback calls unsubscribe() on all five terminal statuses: verified, denied, failed, expired, cancelled
  • Silent SSE drop handled — app checks getVerificationStatus() (e.g. on online / tab focus) or starts a new session

Cancellation

  • unsubscribe() called before cancelVerificationSession() — never after
  • cancelVerificationSession() called when user dismisses mid-flow (before terminal status)
  • cancelVerificationSession() NOT called after expired — session is already closed server-side

Credential data

  • parseCredentialData() / parseCredentialDocuments() used — never JSON.parse() directly
  • Parse call wrapped in try/catch — SessionError on malformed input handled, never proceeds with partial data
  • Multi-document profiles use parseCredentialDocuments() — parseCredentialData() only returns the first document
  • Every required docType validated as present in documents[] — wallet may return a subset
  • Per-document authentication.authenticationResult checked — not just the session-level verified status
  • Document number resolved with ?? per document: claims.document_number ?? claims.doc_number
  • Age-gate flows use claims.age_over_21 / claims.age_over_18 boolean — never derive age from birth_date
  • portrait and signature base64 prefix handled (.startsWith('data:') pattern) per document
  • Required claim fields validated for presence before application logic proceeds

Error states

  • All non-verified terminal statuses surface a user-facing error state
  • denied UX accounts for the three possible causes: policy, invalid credential, revoked
  • Session creation errors handled (user can retry)
  • Activation errors handled with clear credential-check messaging
  • Late cancelled SSE events after UI dismissal guarded against with an active flag

Version note. Multi-document support requires @credenceid/verifier-sdk v0.3.1 or later (npm install @credenceid/verifier-sdk@^0.3.1). Earlier versions silently return only the first document's claims from multi-document payloads; v0.3.0 additionally drops word-based sex values and leaves age_over_NN attestations as strings.