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:
- Your application calls
createVerificationSession()and receives a QR code image. - The end user scans the QR code with their phone, which opens an orchestrator landing page hosted by Credence ID.
- 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.
- 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:
- SDK Initialisation —
new CredenceVerifier()→activate()→ CloudSDK validateslicenseKey+profileIdagainst VwC (customer identity + domain check) → Bearer token returned. - Create Verification Session —
createVerificationSession()→ CloudSDK generates the session and QR internally →VerificationSessionreturned to your app. - Subscribe to Results (SSE) —
subscribeToVerificationResult()establishes the SSE connection before the QR is shown to the user. - User Scans QR — the orchestrator landing page handles wallet detection and credential request (OpenID4VP / DC API / Annex-B) → signed credential sent to CloudSDK.
- 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.
- Application Processes Result —
parseCredentialData()extracts typedCredentialClaimsfrom 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
| Requirement | Minimum | Notes |
|---|---|---|
| Node.js | 14.0+ | Build environment only |
| Browser | Chrome 67+, Firefox 60+, Safari 12+, Edge 79+ | Requires async/await, Promises, EventSource, fetch |
| EventSource API | Native | Required for SSE. Polyfillable — see note below. |
| Fetch API | Native | Required for session management |
EventSource and authentication headers. The native browser
EventSourceAPI 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 polyfillEventSourcefor legacy targets, use a polyfill that preserves the URL-based auth mechanism.event-source-polyfillis a compatible option.
Running outside the browser. When
windowis 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()andopenVerificationTab()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).
| Credential | Description | Reference |
|---|---|---|
| Base URL | HTTPS endpoint of the Credence Cloud backend | For a baseUrl, contact Credence ID |
| License Key | Authentication key bound to your verification account | Generate Cloud SDK Key → |
| Profile ID | UUID identifying the verification policy and accepted credential types | What a Profile is → |
Your
licenseKeyandprofileIdmust 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 option | Returned claim key | Value |
|---|---|---|
| 18+ | age_over_18 | true / false |
| 21+ | age_over_21 | true / false |
| Custom age | age_over_NN | true / 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
| Property | Type | Required | Description |
|---|---|---|---|
baseUrl | string | Yes | HTTPS base URL of the Credence Cloud backend |
licenseKey | string | Yes | License key associated with the verification account |
profileId | string | Yes | Profile 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
| Parameter | Type | Required | Description |
|---|---|---|---|
options.baseUrl | string | Yes | HTTPS base URL of the Credence Cloud backend |
Why aren't credentials in the constructor? The constructor accepts only
baseUrlbecause endpoint configuration is separate from authentication. Credentials (licenseKey,profileId) are passed toactivate()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>
| Parameter | Type | Required | Description |
|---|---|---|---|
options.licenseKey | string | Yes | License key |
options.profileId | string | Yes | Profile ID |
options.webhookUrl | string | No | Your 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 expiredNetworkError— 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
CredenceVerifierinstance 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>
| Parameter | Type | Description |
|---|---|---|
payload | string | The raw request body. Do not parse the JSON first — the signature is computed over the exact bytes received. |
signature | string | The value of the X-Credence-Signature header. |
secret | string | Your 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:
- Activate — authenticate the SDK against the backend (at startup or on demand).
- Create Session — call
createVerificationSession()to receive a session ID, QR code image, and expiry timestamp. - Subscribe — call
subscribeToVerificationResult()and await it. This opens the SSE stream. Do this before showing the QR code to the user. - Display QR — show the QR code. The end user scans it with their phone to open the orchestrator landing page.
- Receive Result — the callback fires when a terminal status arrives. Call
unsubscribe()immediately. - Process Claims — if
status === 'verified', parsecredentialDataand 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>
| Parameter | Type | Required | Description |
|---|---|---|---|
options.purpose | string | Yes | Describes 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.referenceId | string | No | An 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.returnUrl | string | No | Where the landing page sends the browser back to in the same-device flow. Must be HTTPS. |
Returns: Promise<VerificationSession>
| Field | Type | Description |
|---|---|---|
sessionId | string | Unique identifier for the verification session |
qrImageBase64 | string | Base64-encoded QR code image. May include a data:image/png;base64, prefix or be a bare base64 string — handle both. |
qrUrl | string | The orchestrator landing page URL encoded by the QR code. On mobile, navigate to it directly instead of showing a QR — see Same-device flow. |
expiresAt | Date | Session 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 requestNetworkError— 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 }
| Parameter | Type | Required | Description |
|---|---|---|---|
qrImageBase64 | string | Yes | The image source. It is used as the <img> src unchanged, so pass the data: URI (qrSrc above), not a bare base64 string. |
container | string | HTMLElement | Yes | A 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 blockwindow.open()that is not triggered by a user gesture — for example, after anawait.
// 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:
- Create the session with a
returnUrl(HTTPS) that points back to your app. - Set
window.location.href = session.qrUrlinstead of showing a QR. - The user presents their credential. On any terminal state, the landing page redirects to
returnUrlwithcid_sessionandcid_statusquery parameters added. - On your return page, read both parameters, remove them from the address bar with
history.replaceState, then callgetVerificationStatus(cid_session)and usesnapshot.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_statusas a hint only. Anyone can edit a URL, so always confirm the outcome withgetVerificationStatus()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>
| Parameter | Type | Required | Description |
|---|---|---|---|
sessionId | string | Yes | The sessionId returned by createVerificationSession() |
callback | function | Yes | Invoked 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
| Status | Description |
|---|---|
verified | The user presented a valid credential. credentialData is populated. |
denied | The credential was rejected — policy requirements not met, credential is invalid, or credential has been revoked. |
failed | A technical failure occurred during the verification process. |
expired | The session timed out before the user completed verification. |
cancelled | The 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
| Field | Type | Always present | Description |
|---|---|---|---|
status | SessionStatus | Yes | Session 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). |
sessionId | string | Yes | The session identifier this result is associated with |
purpose | string | Yes | The purpose passed to createVerificationSession() |
decision | string | No | The backend's decision for the session, when provided |
verifiedAt | number | No | Time the verification completed, when provided |
credentialData | string | Only 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. |
credentialDatais a JSON-encoded string, not a parsed object. Accessingresult.credentialData.given_namedirectly will returnundefined. Always useparseCredentialData(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:
identityis only treated as an envelope when it is a plain object, anddocumentsis 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 namedidentityordocumentsis 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
| Field | Type | Description |
|---|---|---|
docType | string | null | ISO 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. |
claims | CredentialClaims | Identity claims for this document. Same shape and coercion rules as parseCredentialData() — sex normalised to number, both document_number and doc_number preserved. |
authentication | DocumentAuthentication | undefined | Per-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').
| Field | Type | Description |
|---|---|---|
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? | boolean | Issuer certificate found on the configured trust list. |
issuerSignedAuthenticated? | boolean | Issuer (MSO) signature verified. |
deviceSignedAuthenticated? | boolean | Device binding signature verified. |
dataIntegrity? | boolean | MSO digest integrity check passed. |
msoValidity? | string | MSO validity window state, e.g. 'Valid'. |
issuerSubjectInfo? | string | Subject DN of the issuer signing certificate, e.g. 'C=US,CN=...'. |
certValidationError? | string | Certificate 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.lengthequals the number of document types configured in your profile — always validate the presence of eachdocTypeyour application requires before proceeding.
Per-document duplicate keys. The
document_number ?? doc_numberresolution,sex/genderfallback, and portrait base64-prefix handling described in Claim Reference apply per document — resolve them on eachCredentialDocument.claimsindividually, not once per session.
Choosing a helper:
| Your profile requests | Use |
|---|---|
| One document type | parseCredentialData() — unchanged, no migration needed |
| Multiple document types | parseCredentialDocuments() — 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.
| Claim | Type | Description |
|---|---|---|
given_name | string | First or given name(s) |
family_name | string | Last or family name |
birth_date | string | Date of birth — ISO 8601 date: YYYY-MM-DD |
expiry_date | string | Document expiry date — ISO 8601 date: YYYY-MM-DD |
document_number | string | Primary document number. If absent, check doc_number. |
doc_number | string | Alternate document number key. Present on some credential types in place of document_number. |
admin_number | string | Administrative or inventory control number |
nationality | string | Nationality |
issuing_country | string | Country that issued the document |
issuing_authority | string | Authority that issued the document |
sex | number | Gender 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. |
gender | string | Alternate gender key. String values: Male, Female, M, F. |
portrait | string | Facial photograph. Base64-encoded JPEG. May include a data:image/jpeg;base64, prefix or be a bare base64 string — handle both. |
height | number | Subject height in centimetres |
weight | number | Subject weight in kilograms |
resident_address | string | Street address |
resident_city | string | City or municipality |
resident_state | string | State or province |
resident_postal_code | string | ZIP or postal code |
resident_country | string | Country of residence |
signature | string | Signature image. Base64-encoded string. |
issue_date | string | Document issue date — ISO 8601. mDL key; EU PID credentials use issuance_date. |
issuance_date | string | Alternate issue-date key — present on EU PID credentials. |
administrative_number | string | Alternate administrative-number key (ISO 18013-5 element name). If absent, check admin_number. |
eye_colour | string | Alternate eye-color key (British spelling, ISO 18013-5 element name). If absent, check eye_color. |
hair_colour | string | Alternate hair-color key (British spelling). If absent, check hair_color. |
age_in_years | number | Holder age in completed years, when the profile requests it. |
age_birth_year | number | Holder 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:
| Claim | Type | Description |
|---|---|---|
age_over_18 | boolean | true if the credential holder is 18 or older at the time of verification |
age_over_21 | boolean | true 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_dateyourself. Timezone edge cases on a customer's birthday, DST transitions, and calendar arithmetic are error-prone. Theage_over_NNboolean 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()andparseCredentialDocuments()coerce these to real booleans (any casing), so theclaims.age_over_21 === truepattern 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_NNvalues apply per document in multi-document results. The EU PID document typically carriesage_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
| Scenario | Cause | Recommended Action |
|---|---|---|
| Activation failure | Invalid or expired credentials | Verify all three credential values. Recreate the CredenceVerifier instance and call activate() before retrying. |
| Activation failure | Backend unreachable | Check network connectivity. Retry with exponential backoff. |
| Session creation failure | activate() not yet resolved | Ensure activationPromise has resolved before calling createVerificationSession(). |
| Session creation failure | Backend rejected the request | Check that credentials are valid and profile ID is correct. Retry once. |
| Subscription failure | Network error before SSE stream opened | Retry subscribeToVerificationResult() once. If it fails again, create a new session. |
| SSE connection dropped mid-session | Network interruption during verification | See Dropped SSE Connection. |
| Session expired | User did not complete verification within the session window | The session is already terminated server-side — do not call cancelVerificationSession(). Create a new session if the user wants to retry. |
| Verification denied | Credential fails policy validation, is invalid, or has been revoked | See denied sub-statuses below. |
| Verification failed | Technical failure during verification process | Inform the user. Create a new session and offer retry. |
credentialData absent on verified | Unexpected backend response | Do not proceed with partial identity data. Treat as a failed verification and surface an error. |
credentialData malformed | JSON parse error | Same 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 types | Validate 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 verification | Check 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:
| Cause | What it means | Suggested UX |
|---|---|---|
| Policy not met | The 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 invalid | The issuer signature or cryptographic chain failed verification | "Your credential could not be verified. Please contact your issuer." |
| Credential revoked | The 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>
| Parameter | Type | Required | Description |
|---|---|---|---|
sessionId | string | Yes | The 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, acancelledSSE event may still arrive in the callback aftercancelVerificationSession()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>
| Parameter | Type | Required | Description |
|---|---|---|---|
sessionId | string | Yes | The session ID to query |
Returns: Promise<SessionStatusResponse>
| Field | Type | Description |
|---|---|---|
sessionId | string | The session identifier |
state | SessionStatus | Current session state. Same values as VerificationResult.status. Compare case-insensitively (state.toLowerCase()). |
purpose | string | The purpose passed to createVerificationSession() |
referenceId | string | undefined | The referenceId passed to createVerificationSession(), if any |
qrUrl | string | The orchestrator landing page URL |
qrImageBase64 | string | The QR code image |
expiresAt | Date | Session expiry |
result | VerificationResult | undefined | The 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
| Method | Description | Returns |
|---|---|---|
new CredenceVerifier(options) | Instantiate the SDK client | CredenceVerifier |
.activate(options) | Authenticate the SDK instance against the backend | Promise<void> |
.createVerificationSession(options) | Create a new verification session; returns QR code and session ID | Promise<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 handler | Window | null |
.subscribeToVerificationResult(sessionId, callback) | Open an SSE stream for a session (polling outside the browser); resolves to an unsubscribe function once connected | Promise<() => void> |
.cancelVerificationSession(sessionId) | Invalidate an active session on the backend | Promise<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 POST | Promise<boolean> |
parseCredentialData(credentialData) | Parse claims from the primary (first) document — handles Formats A, B, and C | CredentialClaims |
parseCredentialDocuments(credentialData) | Parse all returned documents; legacy payloads normalise to a one-element array | CredentialDocument[] |
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
-
CredenceVerifierinstance created withbaseUrlonly -
activate()called withlicenseKeyandprofileId - 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
-
activationPromiseawaited (oractivate()awaited directly) before callingcreateVerificationSession() -
qrImageBase64rendered withdata: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. ononline/ tab focus) or starts a new session
Cancellation
-
unsubscribe()called beforecancelVerificationSession()— never after -
cancelVerificationSession()called when user dismisses mid-flow (before terminal status) -
cancelVerificationSession()NOT called afterexpired— session is already closed server-side
Credential data
-
parseCredentialData()/parseCredentialDocuments()used — neverJSON.parse()directly - Parse call wrapped in try/catch —
SessionErroron malformed input handled, never proceeds with partial data - Multi-document profiles use
parseCredentialDocuments()—parseCredentialData()only returns the first document - Every required
docTypevalidated as present indocuments[]— wallet may return a subset - Per-document
authentication.authenticationResultchecked — not just the session-levelverifiedstatus - Document number resolved with
??per document:claims.document_number ?? claims.doc_number - Age-gate flows use
claims.age_over_21/claims.age_over_18boolean — never derive age frombirth_date -
portraitandsignaturebase64 prefix handled (.startsWith('data:')pattern) per document - Required claim fields validated for presence before application logic proceeds
Error states
- All non-
verifiedterminal statuses surface a user-facing error state -
deniedUX 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
cancelledSSE events after UI dismissal guarded against with anactiveflag
Version note. Multi-document support requires
@credenceid/verifier-sdkv0.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-basedsexvalues and leavesage_over_NNattestations as strings.