Developer documentation · Optional

Optional identity, credentials, and privacy proofs.

Use the Advanced Identity SDK only when your application needs portable identity, credentials, authentication, or privacy-preserving proofs. It is not required for the standard Trust ID website deployment.

01 · Advanced Identity SDK · Getting started

A three-tier architecture by default.

Applies to the Advanced Identity SDK only. The standard JavaScript tag needs no account, credentials, app IDs or backend.Trust ID uses a three-tier architecture. Your frontend application communicates with your backend server, which in turn communicates with the Trust ID platform. This architecture ensures sensitive API keys remain server-side and never reach the client. Once initialized, the frontend SDK also emits the live event stream — connections, clicks, scrolls, form submits, performance, and identity events — automatically, with no additional calls.

01

Your frontend app.

Web, React Native, or browser extension. Uses @dcid/sdk.

02

Your backend server.

Express, FastAPI, or Gin. Uses @dcid/server-sdk.

03

Trust ID platform.

iden3, HSM, IPFS, blockchain.

Prerequisites

  • A Trust ID account with API credentials.
  • Signing App ID and Encryption App ID. Request from info@tracerlabs.com.
  • Node.js 16+, Python 3.8+, or Go 1.21+.
  • A backend server. Required — API keys must not be exposed client-side.

02 · Advanced Identity SDK · Installation

Pick your package manager.

Frontend

npm install @dcid/sdk

Backend (Node)

npm install @dcid/server-sdk

Backend (Python)

pip install dcid-server-sdk

Backend (Go)

go get github.com/gettrustid/dcid-backend-sdk/golang

Frontend SDK

Frontend SDK
npm install @dcid/sdk

Backend SDK

Backend SDK
npm install @dcid/server-sdk

Environment variables

VariableRequiredDescription
TRUSTID_APP_IDYesSigning application ID (Identity SDK only).
TRUSTID_APP_ID_ENCRYPTIONYesEncryption application ID.
TRUSTID_API_KEYYes (backend)Server-side API key.
TRUSTID_ENVYesdev or prod.
TRUSTID_API_URLYesAPI endpoint URL.

03 · Advanced Identity SDK · Authentication

Optional OTP sign-in and session management.

Applies to the Advanced Identity SDK only. The standard JavaScript tag does not authenticate users and does not require a Trust ID account. The SDK offers OTP sign-in as one option for issuing sessions. It is not required. If you already authenticate your users, keep your existing flow.

Frontend auth flow

TypeScript — frontend
const client = new DCIDClient({
  appId: process.env.TRUSTID_APP_ID,
  appIdEncryption: process.env.TRUSTID_APP_ID_ENCRYPTION,
  env: 'prod',
  apiUrl: 'https://api.trustid.life'
});

await client.initialize();

// Step 1: Send OTP to user
await client.auth.initiateSignIn('user@example.com');

// Step 2: Confirm OTP code
const tokens = await client.auth.confirmCode('user@example.com', '123456');

// Step 3: Complete authentication
await client.auth.login(tokens.accessToken, tokens.refreshToken);

Backend auth

Backend auth
const sdk = new DCIDServerSDK({
  apiKey: process.env.TRUSTID_API_KEY,
  environment: 'prod'
});

// Send OTP
const result = await sdk.auth.registerOTP({ email: 'user@example.com' });

// Confirm OTP
const tokens = await sdk.auth.confirmOTP({
  email: 'user@example.com',
  otp: '123456'
});

Auth methods

initiateSignIn(login)

Send an OTP code to the user's email or phone number.

Promise<void>

confirmCode(login, code)

Validate the OTP code and receive access and refresh tokens.

TokenResponse

login(accessToken, refreshToken)

Complete authentication and establish the user session.

Promise<void>

logout()

Sign out the current user and clear all stored tokens.

Promise<void>

getAccessToken()

Get the current access token. Automatically refreshes if expired.

Promise<string>

isAuthenticated()

Check whether the user is currently authenticated.

boolean

onAuthStateChanged(callback)

Subscribe to auth state changes. Fires whenever the user logs in or out.

Unsubscribe

04 · Advanced Identity SDK · Identity

Decentralized identifiers, self-custodial keys.

Trust ID creates decentralized identities (DIDs) using the iden3 protocol. Each identity is self-custodial and cryptographically secured. The first call to createIdentity generates the user's Baby JubJub key pair and registers the DID on-chain. Subsequent calls retrieve the existing identity.

TypeScript — create identity
const identity = await client.identity.createIdentity(
  'user@example.com',
  accessToken
);

// identity.did       → "did:iden3:trustid:main:{identifier}"
// identity.wallet    → Wallet object
// identity.publicKey → BJJ hex public key

DID format

Trust ID DIDs follow the pattern did:iden3:trustid:main:{identifier} where the identifier is derived from the user’s cryptographic key material. The DID is permanent and portable across all Trust ID-integrated applications.

Looking for visitor identity resolution on the live data feed? That is a separate surface — see Identity events.

05 · Advanced Identity SDK · Credentials

W3C verifiable credentials, wallet-held.

Trust ID supports W3C Verifiable Credentials for storing and sharing proof of verification events. Credentials are stored in the user's self-custodial wallet and can be backed up to IPFS with encryption.

Credential methods

handleCredentialOffer()

Process and store an incoming credential offer from an issuer.

Promise<void>

getCredentials()

Retrieve all credentials stored in the user's wallet.

Promise<Credential[]>

storeCredential(credential)

Store a W3C verifiable credential directly in the user's wallet.

Promise<void>

hasCredentialType(type)

Check if a credential of the specified type exists in the wallet.

Promise<boolean>

backupAllCredentials()

Create an encrypted backup of all credentials to IPFS.

Promise<string>

recoverCredentialsFromIPFS()

Restore credentials from an encrypted IPFS backup.

Promise<void>

Supported credential types

DocumentVerification.

Government-issued ID verification.

ProofOfAge.

Age verification for age-gated content and products.

Custom schemas.

Define your own credential types with custom JSON-LD schemas.

06 · Advanced Identity SDK · Zero-knowledge proofs

Prove without revealing.

Trust ID enables zero-knowledge proof generation and verification, allowing users to prove attributes about themselves without revealing the underlying data. Proofs are generated client-side using ZK circuits and verified against the blockchain.

TypeScript — generate & verify proof
const proof = await client.proofs.createAndVerifyProof({
  emailOrPhone: 'user@example.com',
  did: identity.did,
  proofRequestUrl: 'https://api.trustid.life/proof-request/...',
  accessToken: tokens.accessToken
});

// proof.verified  → boolean
// proof.submitted → boolean

Query types

TypeDescriptionExample
ComparisonNumeric comparisons (<, >, =, range).Age >= 21.
Set membershipValue in allowed set.Country in [US, UK, CA].
Selective disclosureReveal specific fields only.Share name without DOB.

Error codes

CodeDescription
CREDENTIAL_NOT_FOUNDNo matching credential in the user's wallet.
CIRCUIT_LOAD_FAILEDZK circuit files are unavailable or could not be loaded.
PROOF_GENERATION_FAILEDProof computation encountered an error.
VERIFICATION_FAILEDProof did not pass verification.

07 · Advanced Identity SDK · Platform guides

Web, mobile, and extensions.

React Native

The Trust ID SDK is production-ready for React Native with platform-specific security features.

Peer dependencies

  • @react-native-async-storage/async-storage
  • react-native-keychain

iOS setup

  • Run cd ios && pod install after installing dependencies.
  • Use .xcworkspace (not .xcodeproj) to open the project.
  • Requires iOS 15.1+.

Android setup

  • minSdkVersion 24 required.

Critical

You must call client.setMkHSM() before client.initialize() in React Native. This configures the HSM bridge for native key storage. Circuit caching via MMKV storage is recommended for performance.

Browser extension

  • Manifest V3 required.
  • Content security policy: wasm-unsafe-eval is needed for ZK proof circuits.
  • Storage: use chrome.storage.local for credential persistence.

Web application

Bundler config
import { trustidPlugin } from '@dcid/sdk/vite-plugin-web';

export default defineConfig({
  plugins: [trustidPlugin()]
});

08 · Advanced Identity SDK · Backend server setup

Minimal sample servers.

Your backend server acts as the secure intermediary between your frontend application and the Trust ID platform. Below are minimal server implementations in Express, FastAPI, and Gin.

Sample server
import express from 'express';
import cors from 'cors';
import { DCIDServerSDK } from '@dcid/server-sdk';

const app = express();
app.use(cors());
app.use(express.json());

const sdk = new DCIDServerSDK({
  apiKey: process.env.TRUSTID_API_KEY!,
  environment: process.env.TRUSTID_ENV as 'dev' | 'prod'
});

app.post('/auth/initiate', async (req, res) => {
  const result = await sdk.auth.registerOTP({ email: req.body.email });
  res.json(result);
});

app.post('/auth/confirm', async (req, res) => {
  const tokens = await sdk.auth.confirmOTP({
    email: req.body.email,
    otp: req.body.otp
  });
  res.json(tokens);
});

app.listen(3001, () => console.log('Server running on :3001'));

09 · Advanced Identity SDK · Frontend API reference

The complete @dcid/sdk surface.

Complete reference for all methods available in the @dcid/sdk frontend package. Event capture needs no method calls: once the SDK is initialized, it streams the events documented in the event stream reference on its own.

ModuleMethodParametersReturnsDescription
auth.initiateSignIninitiateSignInlogin: stringPromise<void>Send OTP to email/phone.
auth.confirmCodeconfirmCodelogin: string, code: stringTokenResponseValidate OTP code.
auth.loginloginaccessToken: string, refreshToken: stringPromise<void>Complete authentication.
auth.logoutlogoutPromise<void>Clear session.
auth.getAccessTokengetAccessTokenPromise<string>Get token (auto-refresh).
auth.getRefreshTokengetRefreshTokenPromise<string>Get refresh token.
auth.refreshTokensrefreshTokensPromise<TokenResponse>Manual token refresh.
auth.isAuthenticatedisAuthenticatedbooleanCheck auth status.
auth.onAuthStateChangedonAuthStateChangedcallback: FunctionUnsubscribeAuth state listener.
identity.createIdentitycreateIdentityemailOrPhone: string, accessToken?: stringIdentityResultCreate or retrieve identity.
credentials.handleCredentialOfferhandleCredentialOfferPromise<void>Process credential offer.
credentials.getCredentialsgetCredentialsPromise<Credential[]>Get all credentials.
credentials.storeCredentialstoreCredentialcredential: objectPromise<void>Store W3C credential.
credentials.hasCredentialTypehasCredentialTypetype: stringPromise<boolean>Check credential exists.
credentials.backupAllCredentialsbackupAllCredentialsPromise<string>IPFS backup.
credentials.recoverCredentialsFromIPFSrecoverCredentialsFromIPFSPromise<void>Restore from IPFS.
proofs.createAndVerifyProofcreateAndVerifyProofconfig: ProofConfigProofResultGenerate and verify ZK proof.
proofs.verifyProofverifyProofwallet, proof, pubSignals, circuitIdPromise<boolean>Local proof verification.

10 · Advanced Identity SDK · Backend API reference

The complete @dcid/server-sdk surface.

Complete reference for all methods available in the @dcid/server-sdk backend package.

ModuleMethodParametersReturnsDescription
auth.registerOTPregisterOTP{ email/phone }InitiateOTPResponseSend OTP.
auth.confirmOTPconfirmOTP{ email/phone, otp }TokenResponseValidate OTP.
auth.refreshTokenrefreshToken{ refreshToken }TokenResponseRefresh access token.
identity.encryption.generateKeygenerateKey{ did }KeyResponseGenerate HSM key.
identity.encryption.getKeygetKey{ did }KeyResponseRetrieve key.
identity.issuer.issueCredentialissueCredential{ recipientDid, name, values, ownerEmail }CredentialResponseIssue credential.
identity.issuer.getCredentialOffergetCredentialOffer{ claimId, transactionId }OfferResponseGet credential offer URL.
identity.ipfs.storeCredentialstoreCredential{ did, credential, encrypt? }StorageResponseStore to IPFS.
identity.ipfs.retrieveUserCredentialretrieveUserCredential{ did, type }CredentialResponseFetch by type.
identity.ipfs.getAllUserCredentialsgetAllUserCredentials{ did }CredentialResponse[]Fetch all.
identity.verification.verifySignInverifySignIn{ credentialName }VerifyResponseStart verification.
identity.verification.getLinkStoregetLinkStore{ sessionId }ProofRequestGet proof request.
identity.verification.verifyCallbackverifyCallback{ sessionId, jwzToken }VerifyResultVerify proof.

11 · Advanced Identity SDK · Configuration

Constructor options.

DCIDClient options

Constructor options for the frontend SDK.

OptionTypeRequiredDescription
appIdstringYesSigning application ID (Identity SDK only).
appIdEncryptionstringYesEncryption application ID.
env'dev' | 'prod'YesEnvironment.
apiUrlstringYesAPI endpoint URL.
wsUrlstringNoWebSocket URL.
platformstringNoOverride platform detection.
timeoutnumberNoRequest timeout (ms).
maxRetriesnumberNoMax retry attempts.
loggerobjectNoCustom logger.

DCIDServerSDK options

Constructor options for the backend SDK.

OptionTypeRequiredDescription
apiKeystringYesServer-side API key.
environment'dev' | 'prod'YesEnvironment.
timeoutnumberNoRequest timeout (ms).
defaultHeadersobjectNoCustom headers.
loggerobjectNoCustom logger.
enableRequestLoggingbooleanNoLog all requests.

We use cookies and similar technologies to measure site performance and support marketing. Optional tags load only after you choose. See our Privacy Policy.