Worldcoin IDKit JS

repository·main·Indexed 19 days ago

https://github.com/worldcoin/idkit-js

A toolkit for integrating the World ID Protocol into web and mobile applications to verify proof of personhood. It provides multiple integration patterns, including the IDKit Widget for modal-based flows and the Session API for custom UI/UX control. The library supports vanilla HTML/JavaScript via @worldcoin/idkit-standalone, React via @worldcoin/idkit, and React Native/Expo via @worldcoin/idkit-react-native.

Tokens
15.5K
Snippets
58
Records
74
Agent score
63%

What's inside idkit-js

  1. IDKit Integration Patterns for HTML/JavaScript

    main

    The with-html examples demonstrate two primary ways to integrate IDKit into vanilla HTML/JavaScript applications:

    1. IDKit Widget (index.html): Uses the standard IDKit Widget modal to handle the World ID verification flow. This is the simplest integration pattern for most use cases.
    2. Session API (session-example.html): Uses the Session API, which provides more granular control over state and UI management, allowing you to manage the modal and verification lifecycle manually.

    ⚠️ Security Note: These examples demonstrate how to retrieve a user's ZK-proof. In a production environment, you must verify the proof in your backend system to ensure security.

  2. Choose an integration pattern: IDKit Widget vs Session API

    main

    IDKit Standalone provides two distinct integration patterns depending on your UI requirements:

    IDKit Widget (Modal-based)

    A pre-built modal component for quick integration. It includes a ready-to-use interface, built-in QR code generation, and automatic state management. Best for: Quick integration, standard verification flows, and minimal code maintenance where custom UI design is not a priority.

    Session API (Custom flow)

    A low-level API providing full control over the verification flow. It allows for manual state management and custom QR code URI generation. Best for: Custom UI/UX design, mobile-first responsive experiences, embedding verification into complex layouts, and complete control over the user journey.

  3. How the IDKit Session flow works

    main

    The IDKit Session API manages the lifecycle of a World ID verification flow through the following steps:

    1. Session Creation: A new World ID session is initialized using your application configuration (App ID, Action, etc.).
    2. QR Code Display: The session URI is rendered as a QR code, allowing users to scan it with the World App.
    3. Status Polling: The client application continuously polls the session status (e.g., every 2 seconds) to track progress.
    4. State Management: The UI transitions through different states based on the polling results:
      • PreparingClient: Initial loading state.
      • WaitingForConnection: QR code is visible; waiting for the user to scan.
      • WaitingForApp: The user has scanned the code and is completing verification within the World App.
      • Confirmed: Verification is successful; the proof is available.
      • Failed: Verification failed; error details are provided.
    5. Automatic Cleanup: Polling automatically terminates once a terminal state (Confirmed or Failed) is reached.
  4. Use the Session class for World ID verification

    main

    The Session class is the primary interface for managing World ID verification. Each instance of Session is independent and manages its own lifecycle and state. You use it to create a session, obtain a connection URI, poll for verification status, and clean up resources.

    import { Session } from '@worldcoin/idkit-react-native'
    
    // Create a new verification session
    const session = await new Session().create('app_id', 'your-action', {
    	signal: 'signal', // Optional
    	bridge_url: undefined, // Optional: URL to a custom bridge
    	verification_level: VerificationLevel.Orb, // Optional: Minimum verification level
    	action_description: 'Verify with World ID', // Optional
    	partner: false, // Optional
    })
    
    // Get the connector URI
    const connectorUrl = new URL(session.sessionURI)
    
    // Poll for updates
    const status = await session.status()
    
    // Clean up
    session.destroy()
  5. Verify the IDKit response

    main

    When using IDKit, you must verify the returned proof to ensure it is valid.

    • handleVerify: This option allows your app to perform additional verification on the returned response. This is typically an API call to your backend to ensure the proof is valid.
    • onSuccess: An optional callback that executes after verification succeeds.

    Warning: Never perform proof verification on the client-side. Always verify the proof on your server.

  6. Develop and test the IDKit package locally

    main

    If you are contributing to the @worldcoin/idkit package, follow these steps. Note that most commands must be run from the /idkit directory, except for the initial installation.

    1. Install dependencies (Run in the repository root):

      yarn install
    2. Run tests (Run in the /idkit folder):

      cd idkit/
      yarn test
    3. Run local development server (Run in the /idkit folder):

      cd idkit/
      yarn dev

      Then open http://localhost:3000 in your browser.

    4. Build production bundle (Run in the /idkit folder):

      cd idkit/
      yarn build
  7. Implement Deep Linking for mobile verification

    main

    To allow users to return to your app after verifying in the World App, you must use deep linking. You should append a return_to query parameter to the sessionURI provided by the session and then open that URL using Linking.openURL.

    import { createURL } from 'expo-linking' // For Expo projects
    import { Linking } from 'react-native'
    import { Session } from '@worldcoin/idkit-react-native'
    
    const handleVerify = async () => {
    	const session = await new Session().create(appId, action)
    
    	// Set up return URL
    	const returnTo = createURL('') // Replace with your deep link path
    
    	if (session.sessionURI) {
    		const connectorUrl = new URL(session.sessionURI)
    		connectorUrl.searchParams.set('return_to', returnTo)
    
    		// Open the URL to redirect user to World App
    		Linking.openURL(connectorUrl.toString())
    	}
    }
  8. Use the IDKitWidget React component

    main

    The IDKitWidget component is the React wrapper for the IDKit JS Widget. It provides a declarative way to integrate World ID verification into your React application. You wrap your trigger element (like a button) in the component and use the open function provided by the render prop to launch the verification flow.

    <IDKitWidget
      app_id="your_app_id"
      action="your_action"
      onSuccess={handleSuccess}
    >
      {({ open }) => <button onClick={open}>Verify with World ID</button>}
    </IDKitWidget>
  9. Run the IDKit Next.js example project

    main

    To run the local development server for the IDKit Next.js example, use one of the following package manager commands from the project root. Once started, the application will be available at http://localhost:3000.

    npm run dev
    # or
    yarn dev
    # or
    pnpm dev
    # or
    bun dev
  10. Install and use IDKit in React Native

    main

    To integrate IDKit into a React Native application, install @worldcoin/idkit-react-native.

    Important: React Native requires crypto polyfills. You must install and call install() from react-native-quick-crypto at the start of your application.

    To perform verification, create a new Session, obtain the sessionURI to redirect the user to the World App, and poll the session status using session.status() to check if the state is VerificationState.Confirmed or VerificationState.Failed.

    // 1. Install polyfills
    import { install } from 'react-native-quick-crypto'
    install()
    
    // 2. Basic usage
    import { Session, VerificationState } from '@worldcoin/idkit-react-native'
    
    // Create a new verification session
    const session = await new Session().create('app_id', 'your-action')
    
    // Get the connector URI that redirects user to the World App
    const connectorUrl = new URL(session.sessionURI)
    connectorUrl.searchParams.set('return_to', returnTo)
    const connectUrlWithReturnAddress = connectorUrl.toString()
    
    // Poll for updates to check verification status
    const checkStatus = async () => {
    	const status = await session.status()
    
    	if (status.state === VerificationState.Confirmed) {
    		console.log('Verification successful:', status.result)
    	} else if (status.state === VerificationState.Failed) {
    		console.log('Verification failed:', status.errorCode)
    	}
    }
    
    // Clean up when done
    const cleanup = () => {
    	session.destroy()
    }