JavaScript SDK
A server helper that creates cases and sessions, a typed session client, and browser screens for questions, the liveness challenge, the location step, and email and phone codes.
npm ci and npm run build. The package name will be @credflare/sdk-javascript.On your server
Keep this code and your client credentials on the server. The constructor refuses to run in a browser.
import {CredflareServer} from '@credflare/sdk-javascript/server';
const credflare = new CredflareServer(process.env.CREDFLARE_API_URL, {
clientId: process.env.CREDFLARE_CLIENT_ID,
clientSecret: process.env.CREDFLARE_CLIENT_SECRET,
});
const verification = await credflare.createVerification({
email: '[email protected]',
profileId: 123,
});
const session = await credflare.createSession(verification.id, [
'https://app.example.test',
]);
// Store verification.id with your user. Return only session to the browser. The second argument lists the browser origins allowed to use the session. Use exact HTTPS origins without a path. Native apps can omit it. Authenticate your own user before returning a session, and keep each user bound to their own case.
| Method | Calls |
|---|---|
createVerification({email, profileId, callbackUrl}) | POST /client/verifications |
createSession(id, allowedOrigins) | POST /client/verifications/{id}/sessions |
revokeSession(sessionId) | DELETE /client/verification-sessions/{session} |
getVerification(id) | GET /client/verifications/{id} |
In the browser
Load the requirements the case's profile set, then build one step per side and source with captureSteps. It reads the capture method from the requirement, so a document set to snapshot_and_upload in the profile produces a camera step and an upload step for each side. Your code never chooses the method.
import {CredflareSession, captureSteps, methodSummary} from '@credflare/sdk-javascript';
const client = new CredflareSession(session);
const info = await client.get();
const requirement = info.profile.document_requirements[0];
methodSummary(requirement); // "Camera photos", "Saved files", ...
const steps = captureSteps(requirement);
// [{id: 'camera:front', side: 'front', source: 'camera', label: 'Front', sourceLabel: 'Camera photo'}, ...] Upload each file, then submit the document with every file in evidence.
const evidence = [];
for (const step of steps) {
const {file, source} = selected[step.id]; // source is 'camera' or 'upload'
const body = new FormData();
body.append('file', file);
body.append('side', step.side);
body.append('capture_source', source);
body.append('document_type_id', String(requirement.document_type.id));
const uploaded = await client.upload('documents', body, crypto.randomUUID());
evidence.push({file_id: uploaded.id, side: step.side, source});
}
await client.submit({
type: 'document_verification',
document_type_id: requirement.document_type.id,
evidence,
}, crypto.randomUUID()); Keep each request key with its payload until it succeeds, so a retry after a dropped connection does not create a duplicate. After a submission, call client.get() again: received documents drop out of document_requirements.
Use isCaptureSupported(requirement) before offering a document. An unsupported method should tell the applicant to contact you rather than open a capture screen.
Liveness and location
After the documents, mountRemainingSteps runs the case's outstanding facial and location requirements in profile order and ends with a receipt. It requests the liveness challenge, records the gesture frames, the video and the selfie, and submits them with the challenge ID.
import {mountRemainingSteps} from '@credflare/sdk-javascript/browser';
import {createMediaPipeProvider} from '@credflare/sdk-javascript/mediapipe';
const dispose = mountRemainingSteps(element, client, {
provider: createMediaPipeProvider({
wasmBaseUrl: '/mediapipe/wasm',
modelAssetPath: '/models/face_landmarker.task',
}),
onDone: () => showFinished(),
}); - Face signals come from MediaPipe Face Landmarker. Install
@mediapipe/tasks-vision0.10.32, an optional peer dependency, in apps that collect liveness. It loads only when the liveness step starts. - Without
wasmBaseUrlandmodelAssetPath, the runtime loads from jsDelivr and the model from Google's storage. Serve both yourself if your content security policy or privacy rules require it. - The page needs camera and location permission, and no microphone. Serve it over HTTPS.
- Browsers cannot tell whether a location is mocked, so the SDK sends
is_mock: nullandprovider: "browser". mountLiveness,mountLocationandmountReceiptmount one step each for a custom flow. Passproviderto use another face signal source with the same shape.
To build your own screens, the client has createLivenessChallenge(key), uploadBiometric({type, challengeId, gesture, file}, key), submitFacial(submission, key) and submitLocation(submission, key). facialSettings and locationSettings read info.profile.verification_requirements and fill in the spec defaults. The package also exports the shared gesture engine and the generated spec constants and copy.
Questions, codes and rejections
mountRemainingSteps also asks the profile's questions and confirms email addresses and phone numbers. The order is questions, documents, then the verification requirements in profile order.
const dispose = mountRemainingSteps(element, client, {
provider: createMediaPipeProvider(),
handoff: true,
onLeave: code => host.needsAction(code),
onDone: () => showFinished(),
}); - A question whose
show_ifdoes not match is not shown, not checked and not sent.visibleQuestions,isShown,answerProblemsandanswersPayloadapply the same rules to your own form. - The email and phone steps send a code with
client.requestCode(channel, destination), take the six digit code, confirm it withclient.confirmCode(channel, code), and enable a new code atresend_available_at. - After every submit and code confirmation, the SDK fetches the session again and continues while something is outstanding, as described in after a submit.
refreshOutcomeandrefreshFailureOutcomeimplement the rule. remainingStep(info, earlier)returns the next step with itsRemainingSteptype, includingquestions,email_verificationandphone_verification.nextStepandFlowStepare deprecated and still report those steps ashost.- A
422with a known code shows its rejection screen, built byrejectionScreen(error, {requester}), with the requester's help contact. - With
onLeave, aleaverejection such asphone.not_configuredoffers a close button and callsonLeavewith the code. It is never reported as a cancellation. mountQuestionsandmountContactCodemount one step each for a custom flow.client.submitAnswers(fields, key)sends aform_submission.
Continue on a phone
With handoff: true, mountRemainingSteps offers "Continue on your phone". It creates a link with client.createHandoff(), shows it as a QR code (qrSvg) with the minutes left, offers a new code when it expires, and polls the session until the phone has finished, then shows the receipt. mountHandoff shows the QR step on its own. The link carries a single use token in its fragment: never log or store it. See how the handoff works.
Errors
Failures throw CredflareError with status, type (network, session_unavailable, verification_closed, validation or api), validation errors and the rejection code for a capture rule. See how to handle each status.
The API requires HTTPS, except on localhost. Applicant requests omit cookies.