> ## Documentation Index
> Fetch the complete documentation index at: https://developer.uphold.com/llms.txt
> Use this file to discover all available pages before exploring further.

# KYC Widget installation and setup

> Install the Uphold KYC Widget SDK — or integrate directly against the Widget's message protocol — in web and native applications through a WebView.

By the end of this guide the KYC Widget will be running in your app, mounted to a container, and emitting events you can react to.

## Before you start

<Warning>Before you can test the KYC Widget in Sandbox or Production, Uphold must complete a one-time internal setup to enable identity verification for your account. Contact your Account Manager to have this provisioned ahead of your integration.</Warning>

You'll need:

* Access to [Widgets API](/rest-apis/widgets-api/kyc/create-session) to create widget sessions. Manage your access in [Enterprise Portal](https://portal.enterprise.uphold.com/).
* A **backend** that can call the Widgets API to create sessions on behalf of your users.
* A **frontend** — a web app, or a native app with a WebView — to embed the Widget.

The Widget runs from one of two hosts depending on environment:

| Environment | Widget host |
| - | - |
| Sandbox | `https://kyc-widget.enterprise.sandbox.uphold.com` |
| Production | `https://kyc-widget.enterprise.uphold.com` |

## Choose an integration approach

We recommend integrating **without the SDK** for native apps — it's simpler to set up. For web-only integrations, the Web SDK is a solid default.

There are two ways to embed the Widget:

* **[Web SDK](#setup-with-web-sdk)** — Install `@uphold/enterprise-kyc-widget-web-sdk` for a better developer experience — typed events and a more streamlined integration on web. For native apps, the SDK must be bundled into the WebView's HTML page.
* **[Without the SDK](#setup-without-the-sdk)** — Listen for the Widget's messages over the iframe or WebView and respond to them directly. This is also the simpler option for native apps: there's no SDK to bundle into the WebView's HTML page.

Both approaches use the same backend step — creating a session via the Widgets API — and emit the same four lifecycle outcomes (`ready`, `complete`, `cancel`, `error`).

## Shared setup

These two steps are identical whichever approach you choose above — do them once, then jump to the matching section below.

### 1. Create a session on your backend

The KYC Widget runs against a session — a short-lived, server-side authorization scoped to one flow and one user. Create it server-side using your OAuth credentials.

<Note>To create a session, you must have the `KYC Widget` scope.</Note>

<Warning>Never create session directly from the client. Your client secret must not leave your backend.</Warning>

Call [`Create session`](/rest-apis/widgets-api/kyc/create-session) with the `verify` flow, the processes you want the user to complete, and, optionally, the Widget `options`:

```bash theme={null}
curl -X POST https://api.sandbox.uphold.com/widgets/kyc/sessions \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "X-On-Behalf-Of: user $USER_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "flow": "verify",
    "processes": ["customer-due-diligence", "identity", "profile", "proof-of-address"],
    "options": {
      "layout": "fluid",
      "theme": {
        "appearance": "dark",
        "primary": "#4F46E5",
        "primaryForeground": "#FFFFFF",
        "foreground": "#E5E7EB",
        "background": "#111827",
        "fontFamily": { "sans": "Inter, sans-serif" },
        "components": {
          "button": { "borderRadius": "9999px" },
          "input": { "borderRadius": "8px" },
          "card": { "borderRadius": "12px" }
        }
      }
    }
  }'
```

The `options` object accepts the same options as the SDK, except `debug` — see [Configuration reference](#configuration-reference).

<Note>If you set `theme` or `layout`, also see [Theme and layout setup](#theme-and-layout-setup).</Note>

The response wraps the session object:

```json theme={null}
{
  "session": {
    "url": "https://kyc-widget.enterprise.sandbox.uphold.com/?sessionToken=..."
  }
}
```

Send `response.session` to your frontend, for example in your page response or through your own API endpoint.

Keep `session.url` unmodified, including its query string. The only change allowed is adding `theme_appearance` when integrating without the SDK (see [Theme and layout setup](#without-the-sdk)). Then:

* With the Web SDK, pass `response.session` as the `session` argument to the `KycWidget` constructor — see [Setup with Web SDK](#setup-with-web-sdk).
* Without the SDK, load `session.url` directly into your iframe or WebView — see [Setup without the SDK](#setup-without-the-sdk).

### 2. Allow the Widget domain in your CSP

If your web app embeds the Widget in an iframe and enforces a Content Security Policy, allow the Widget host for your environment(s) under `frame-src`.

```html theme={null}
<meta
  http-equiv="Content-Security-Policy"
  content="frame-src 'self' https://kyc-widget.enterprise.sandbox.uphold.com https://kyc-widget.enterprise.uphold.com;"
>
```

<Note>If your app does not use CSP, skip this step.</Note>

## Setup with Web SDK

### Install the SDK

Install the SDK in the frontend that will host the Widget — your web app, or the JS bundle loaded by your native WebView.

```bash theme={null}
npm install @uphold/enterprise-kyc-widget-web-sdk
```

### Initialize and mount the Widget

On the frontend, instantiate `KycWidget` with the session from [Create a session on your backend](#1-create-a-session-on-your-backend), then mount it into a container element. If you set `theme` or `layout` in Create session, also pass the same values to the constructor, to avoid a brief change in appearance (see [Theme and layout setup](#theme-and-layout-setup)).

```javascript theme={null}
import { KycWidget } from '@uphold/enterprise-kyc-widget-web-sdk';

// session is `response.session` from your backend — see Shared setup
const widget = new KycWidget(session, {
  debug: true, // Verbose logging during development
  // If you set `theme` or `layout` in Create session, pass the same values here
  layout: 'fluid',
  theme: { appearance: 'dark' }
});

widget.mountIframe(document.getElementById('kyc-container'));
```

<Note>The container must have explicit CSS width and height — the iframe fills its bounds. Minimum recommended size is **400px × 600px**.</Note>

See the [SDK reference](./sdk-reference#constructor) for full constructor details.

### Handle Widget events

The Widget emits four events during its lifecycle. Wire up handlers **before** calling `mountIframe`.

| Event | Fires when | What to do |
| - | - | - |
| `ready` | The Widget has finished loading | Hide your loading state |
| `complete` | The user submitted all KYC processes | Call `widget.unmount()`, then monitor outcomes via [KYC webhooks](/rest-apis/core-api/kyc/introduction) |
| `cancel` | The user dismissed the Widget | Call `widget.unmount()`, return them to your flow |
| `error` | The Widget hit an unrecoverable error | Read `event.detail.error`, call `widget.unmount()`, retry |

<Warning>The Widget does not unmount itself. You must call `widget.unmount()` from `complete`, `cancel`, and `error` handlers.</Warning>

```javascript [expandable] theme={null}
widget.on('ready', () => {
  console.log('KYC Widget is ready');
});

widget.on('complete', () => {
  console.log('KYC processes submitted');
  widget.unmount();
});

widget.on('cancel', () => {
  console.log('KYC cancelled');
  widget.unmount();
});

widget.on('error', (event) => {
  console.error('KYC error:', event.detail.error);
  widget.unmount();
});
```

<Note>The `complete` event signals that the user has submitted all required processes — not that verification was approved. Final verification outcomes (e.g. identity approved or rejected) are delivered asynchronously via [KYC webhooks](/rest-apis/core-api/kyc/introduction). Monitor those server-side to update your user's status.</Note>

### Native apps with the Web SDK

<Accordion title="Bundle the SDK into a WebView (not recommended — see Setup without the SDK instead)">
  Native mobile apps can also use the SDK to embed the Widget through a WebView, building on the [Install the SDK](#install-the-sdk) and [Initialize and mount the Widget](#initialize-and-mount-the-widget) steps above. To do so, it requires you to bundle the SDK into the WebView's HTML page, and forward events to native code through a bridge. We recommend integrating [without the SDK](#setup-without-the-sdk) for native apps as it has a simpler setup, but if you choose to use the SDK, follow the steps below.

  Create a JS bundle that includes the SDK. This bundle will be loaded in the WebView. You can use a tool like [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/) to bundle the SDK and your custom code into a single JS file.

  <Note>Loading the Web SDK from a CDN is not supported.</Note>

  Then create an HTML page that includes the JS bundle and mounts the Widget. This page will be loaded in the WebView. Here is an example you can use — the `sendToNativeApp` helper at the bottom forwards events to whichever bridge is available (iOS, Android, or React Native).

  ```html [expandable] theme={null}
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>KYC Widget</title>
      <style>
        body { margin: 0; padding: 0; }
        #kyc-container { width: 100%; height: 100vh; }
      </style>
    </head>
    <body>
      <div id="kyc-container"></div>

      <!-- Include your JS bundle which contains the SDK -->
      <script src="your-bundle-with-sdk.js"></script>
      <script>
        window.addEventListener('load', () => {
          const session = createKycWidgetSession();
          const widget = new KycWidget(session);

          widget.on('complete', () => {
            sendToNativeApp('complete');
            widget.unmount();
          });

          widget.on('cancel', () => {
            sendToNativeApp('cancel');
            widget.unmount();
          });

          widget.on('error', (event) => {
            sendToNativeApp('error', event.detail.error);
            widget.unmount();
          });

          widget.mountIframe(document.getElementById('kyc-container'));
        });

        function sendToNativeApp(type, data = null) {
          const message = { type, data };

          if (window.webkit?.messageHandlers?.kycWidgetMessage) {
            window.webkit.messageHandlers.kycWidgetMessage.postMessage(message);
          } else if (window.KycBridge) {
            window.KycBridge.onMessage(JSON.stringify(message));
          } else if (window.ReactNativeWebView) {
            window.ReactNativeWebView.postMessage(JSON.stringify(message));
          }
        }
      </script>
    </body>
  </html>
  ```

  ### Platform setup

  Here is a sample of how to create a WebView in your native app and load the HTML page that contains the SDK and mounts the Widget. The WebView should be configured to allow JavaScript execution and to forward messages to your native code.

  <Tabs>
    <Tab title="iOS (Swift)">
      ```swift [expandable] theme={null}
      import WebKit

      class KycViewController: UIViewController, WKScriptMessageHandler {
        @IBOutlet weak var webView: WKWebView!

        override func viewDidLoad() {
          super.viewDidLoad()

          // Register a single message handler for all Widget events
          let contentController = webView.configuration.userContentController
          contentController.add(self, name: "kycWidgetMessage")

          if let url = Bundle.main.url(forResource: "kyc-widget", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
          }
        }

        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
          guard message.name == "kycWidgetMessage",
                let messageDict = message.body as? [String: Any],
                let type = messageDict["type"] as? String else {
            return
          }

          let data = messageDict["data"]

          switch type {
            case "complete": handleKycComplete()
            case "cancel":   handleKycCancel()
            case "error":    handleKycError(error: data)
            default: print("Unknown KYC Widget message type: \(type)")
          }
        }

        private func handleKycComplete() { /* navigate to success */ }
        private func handleKycCancel() { /* return user to previous screen */ }
        private func handleKycError(error: Any?) { /* show error UI */ }

        deinit {
          webView?.configuration.userContentController.removeScriptMessageHandler(forName: "kycWidgetMessage")
        }
      }
      ```
    </Tab>

    <Tab title="Android (Java/Kotlin)">
      ```java [expandable] theme={null}
      import android.webkit.WebView;
      import android.webkit.WebSettings;
      import android.webkit.JavascriptInterface;
      import android.util.Log;
      import org.json.JSONObject;

      WebView webView = findViewById(R.id.webview);
      WebSettings webSettings = webView.getSettings();
      webSettings.setJavaScriptEnabled(true);

      webView.addJavascriptInterface(new KycBridge(), "KycBridge");
      webView.loadUrl("file:///android_asset/kyc-widget.html");

      public class KycBridge {
        @JavascriptInterface
        public void onMessage(String messageJson) {
          try {
            JSONObject message = new JSONObject(messageJson);
            String type = message.getString("type");
            Object data = message.opt("data");

            runOnUiThread(() -> {
              switch (type) {
                case "complete": handleKycComplete(); break;
                case "cancel":   handleKycCancel(); break;
                case "error":    handleKycError(data != null ? data.toString() : null); break;
                default: Log.w("Kyc", "Unknown KYC Widget message type: " + type);
              }
            });
          } catch (Exception e) {
            Log.e("Kyc", "Error parsing KYC Widget message", e);
          }
        }

        private void handleKycComplete() { /* navigate to success */ }
        private void handleKycCancel() { /* return user to previous screen */ }
        private void handleKycError(String error) { /* show error UI */ }
      }
      ```

      <Note>If you load local assets, ensure the WebView allows file access according to your security requirements (e.g. `setAllowFileAccess(true)` when needed).</Note>
    </Tab>

    <Tab title="React Native">
      ```javascript [expandable] theme={null}
      import { WebView } from 'react-native-webview';
      import { Alert } from 'react-native';

      const KycScreen = () => {
        const handleMessage = (event) => {
          try {
            const message = JSON.parse(event.nativeEvent.data);

            switch (message.type) {
              case 'complete': handleKycComplete(); break;
              case 'cancel':   handleKycCancel(); break;
              case 'error':    handleKycError(message.data); break;
              default: console.log('Unknown message type:', message.type);
            }
          } catch (error) {
            console.error('Error parsing WebView message:', error);
          }
        };

        const handleKycComplete = () => { /* navigate to success */ };
        const handleKycCancel = () => { /* return user to previous screen */ };
        const handleKycError = (error) => { /* show error UI */ };

        return (
          <WebView
            source={{ uri: 'file:///path/to/kyc-widget.html' }}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            onMessage={handleMessage}
          />
        );
      };
      ```

      <Note>For iOS, `file://` URLs may be restricted. Consider `source={{ html: '<html>...</html>' }}` or a bundled asset, adjusted per platform.</Note>
    </Tab>
  </Tabs>
</Accordion>

## Setup without the SDK

Instead of installing the SDK, you can load the Widget's session `url` directly — as an iframe you create yourself on web, or as your WebView's top-level page on native — and speak its underlying message protocol directly. This is useful for hosts that can't ship a JS bundle to their WebView, or want a fully native shell around the Widget.

<Note>The [Shared setup](#shared-setup) steps still apply here — you just don't install anything. Only how you load the Widget and exchange messages changes.</Note>

### The message protocol

These are the message types the Widget speaks. The transport carrying them differs per platform — see the tabs below.

**From the Widget to your host:**

| Type | Payload | Fires when | What to do |
| - | - | - | - |
| `load` | — | The Widget's script has booted | Optionally, reply with an `init` message to pass options from your frontend (see below) |
| `ready` | — | The Widget is ready for interaction | Hide your loading state |
| `complete` | — | The user submitted all KYC processes | Tear down the iframe/WebView, then monitor outcomes via [KYC webhooks](/rest-apis/core-api/kyc/introduction) |
| `cancel` | — | The user dismissed the Widget | Tear down the iframe/WebView, return them to your flow |
| `error` | `error` (string) | The Widget hit an unrecoverable error | Read `error`, tear down the iframe/WebView, retry |
| `force_repaint` | — | Works around a WKWebView redraw issue. iOS WKWebView hosts only (including React Native on iOS) | Briefly toggle the WebView's opacity to force a repaint |

**From your host to the Widget:**

| Type | Payload | Send when |
| - | - | - |
| `init` | `{ options }` | Optional. Replying to the Widget's `load` message |

The Widget loads its session on its own, using the options set when creating the session, so the `init` reply is optional. The `init` payload carries an `options` object with the same shape as the SDK's [`KycWidgetOptions`](./sdk-reference#options), except `debug` — omit it or pass `{}` to use defaults. For now, include the same `theme` and `layout` you set in Create session, to avoid a brief change in appearance (see [Theme and layout setup](#theme-and-layout-setup)).

If you send `init`, its options are merged with the ones set when creating the session, and **Create session** values take precedence for any value set in both.

<Note>Sending the full session object in `init` (`{ ...session, options }`) still works but is deprecated. The Widget ignores it if it has already loaded its session, and logs a console warning when it's used. Send `{ options }` only.</Note>

### Platform implementation

<Tabs>
  <Tab title="Web">
    Mount the session `url` in an iframe you create yourself, and exchange messages over the standard `window.postMessage` API. Make sure the iframe's container has explicit CSS width and height (minimum recommended size is **400px × 600px**).

    ```html [expandable] theme={null}
    <div id="kyc-container"></div>

    <script>
      // session is `response.session` from your backend
      async function startKycWidget(session) {
        const container = document.getElementById('kyc-container');
        const sessionOrigin = new URL(session.url).origin;

        const iframe = document.createElement('iframe');
        iframe.src = session.url;
        iframe.setAttribute('allow', "clipboard-write 'src'; clipboard-read 'src';");
        iframe.style.width = '100%';
        iframe.style.height = '100%';
        iframe.style.border = 'none';

        function teardown() {
          window.removeEventListener('message', onMessage);
          iframe.remove();
        }

        function onMessage(event) {
          if (event.origin !== sessionOrigin) return;

          switch (event.data?.type) {
            case 'load':
              // Options are the KycWidgetOptions shape from the SDK reference. Omit or pass {} to use defaults.
              iframe.contentWindow.postMessage({ options: {}, type: 'init' }, sessionOrigin);
              break;
            case 'ready':
              console.log('KYC Widget is ready');
              break;
            case 'complete':
              console.log('KYC processes submitted');
              teardown();
              break;
            case 'cancel':
              console.log('KYC cancelled');
              teardown();
              break;
            case 'error':
              console.error('KYC error:', event.data.error);
              teardown();
              break;
          }
        }

        window.addEventListener('message', onMessage);
        container.appendChild(iframe);
      }
    </script>
    ```
  </Tab>

  <Tab title="iOS (Swift)">
    Instead of bundling an HTML page, point the WebView directly at the session `url`. The Widget sends messages to native code through the `uphdKycWidget` message handler; to reply, call `window.KycWidgetBridge.sendMessageToWidget(...)` via `evaluateJavaScript`, passing an `options` object (empty below — see [Configuration reference](#configuration-reference) to customize it). The `KycViewController` below ties this together into a complete example, forwarding the Widget's messages to native callbacks.

    ```swift [expandable] theme={null}
    import WebKit

    final class KycViewController: UIViewController, WKScriptMessageHandler {

      var onComplete: (() -> Void)?
      var onCancel: (() -> Void)?
      var onError: ((Any?) -> Void)?

      private let webView: WKWebView = {
        let webView = WKWebView(frame: .zero)
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
      }()

      override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(webView)
        NSLayoutConstraint.activate([
          webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
          webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
          webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
          webView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])

        // Registers the exact handler name the Widget looks for
        webView.configuration.userContentController.add(self, name: "uphdKycWidget")

        Task {
          do {
            let session = try await createKycWidgetSession() // calls your backend

            guard let urlString = session["url"] as? String, let url = URL(string: urlString) else {
              onError?(["message": "KYC Widget session response is missing a valid 'url'"])
              return
            }

            webView.load(URLRequest(url: url))
          } catch {
            onError?(["message": "\(error)"])
          }
        }
      }

      // Replies to the Widget's "load" message with an "init" command carrying an options
      // object — same shape as the SDK's KycWidgetOptions. Empty here; see Configuration
      // reference to customize it.
      private func sendInitMessageToWidget() {
        let initMessage: [String: Any] = ["type": "init", "options": [:]]

        guard let data = try? JSONSerialization.data(withJSONObject: initMessage),
              let json = String(data: data, encoding: .utf8) else {
          return
        }

        webView.evaluateJavaScript("window.KycWidgetBridge.sendMessageToWidget(\(json));")
      }

      // Nudges the page's opacity to force a repaint — needed to work around a WKWebView
      // redraw bug when the Widget uses the View Transitions API.
      private func forceRepaintWidget() {
        webView.evaluateJavaScript("""
        document.documentElement.style.opacity = '0.99';
        setTimeout(() => { document.documentElement.style.opacity = '1'; }, 0);
        """)
      }

      func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // The Widget JSON.stringifies its messages before posting them, so the body
        // arrives as a string rather than an already-decoded dictionary.
        guard message.name == "uphdKycWidget",
              let jsonString = message.body as? String,
              let data = jsonString.data(using: .utf8),
              let messageDict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let type = messageDict["type"] as? String else {
          return
        }

        switch type {
          case "load":          sendInitMessageToWidget()
          case "force_repaint": forceRepaintWidget()
          case "ready":          print("KYC Widget is ready")
          case "complete":       onComplete?()
          case "cancel":         onCancel?()
          case "error":          onError?(messageDict["error"])
          default: print("Unknown KYC Widget message type: \(type)")
        }
      }

      deinit {
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "uphdKycWidget")
      }
    }
    ```
  </Tab>

  <Tab title="Android (Kotlin)">
    Instead of bundling an HTML page, point the WebView directly at the session `url`. The Widget sends messages to native code through the `uphdKycWidget` object registered below; to reply, call `replyProxy.postMessage(...)`, passing an `options` object (empty below — see [Configuration reference](#configuration-reference) to customize it). The `KycActivity` below ties this together into a complete example, forwarding the Widget's messages to native callbacks.

    <Warning>There is no bundled test app reference for this path yet. Validate the message names and payload shapes below against the version of the Widget you're integrating.</Warning>

    ```kotlin [expandable] theme={null}
    import android.webkit.WebView
    import androidx.webkit.JavaScriptReplyProxy
    import androidx.webkit.WebViewCompat
    import androidx.webkit.WebViewFeature
    import org.json.JSONObject

    class KycActivity : AppCompatActivity() {

      private lateinit var webView: WebView

      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kyc)

        webView = findViewById(R.id.webview)
        webView.settings.javaScriptEnabled = true

        if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
          WebViewCompat.addWebMessageListener(
            webView,
            "uphdKycWidget",
            setOf(
              "https://kyc-widget.enterprise.sandbox.uphold.com",
              "https://kyc-widget.enterprise.uphold.com"
            )
          ) { _, message, _, _, replyProxy ->
            val body = JSONObject(message.data ?: return@addWebMessageListener)

            when (body.getString("type")) {
              "load" ->     sendInitMessageToWidget(replyProxy)
              "ready" ->    Log.d("Kyc", "KYC Widget is ready")
              "complete" -> handleKycComplete()
              "cancel" ->   handleKycCancel()
              "error" ->    handleKycError(body.opt("error"))
              else -> Log.w("Kyc", "Unknown KYC Widget message type: ${body.getString("type")}")
            }
          }
        } else {
          // Fall back to Setup Web SDK on WebViews that don't support WEB_MESSAGE_LISTENER.
        }

        lifecycleScope.launch {
          try {
            val session = createKycWidgetSession() // calls your backend
            webView.loadUrl(session.getString("url"))
          } catch (e: Exception) {
            handleKycError(e.message)
          }
        }
      }

      // Replies to the Widget's "load" message with an "init" command carrying an options
      // object — same shape as the SDK's KycWidgetOptions. Empty here; see Configuration
      // reference to customize it.
      private fun sendInitMessageToWidget(replyProxy: JavaScriptReplyProxy) {
        val initMessage = JSONObject()
          .put("type", "init")
          .put("options", JSONObject())

        replyProxy.postMessage(initMessage.toString())
      }

      private fun handleKycComplete() { /* navigate to success */ }
      private fun handleKycCancel() { /* return user to previous screen */ }
      private fun handleKycError(error: Any?) { /* show error UI */ }
    }
    ```

    <Note>`force_repaint` is a WKWebView-specific workaround and isn't expected on Android — the listener above doesn't need to handle it.</Note>
  </Tab>

  <Tab title="React Native">
    Instead of bundling an HTML page, point the WebView directly at the session `url`. The Widget sends messages to native code through the WebView's `onMessage` prop, once it detects `window.ReactNativeWebView` (injected automatically by `react-native-webview`); to reply, call `window.KycWidgetBridge.sendMessageToWidget(...)` via `injectJavaScript`, passing an `options` object (empty below — see [Configuration reference](#configuration-reference) to customize it). The `KycScreen` below ties this together into a complete example, forwarding the Widget's messages to native callbacks.

    ```jsx [expandable] theme={null}
    import React, { useRef } from 'react';
    import { WebView } from 'react-native-webview';

    const KycScreen = ({ session }) => {
      const webViewRef = useRef(null);

      // Replies to the Widget's "load" message with an "init" command carrying an options
      // object.
      const sendInitMessageToWidget = () => {
        const initMessage = JSON.stringify({ options: {}, type: 'init' });

        webViewRef.current?.injectJavaScript(`window.KycWidgetBridge.sendMessageToWidget(${initMessage}); true;`);
      };

      const handleMessage = (event) => {
        const message = JSON.parse(event.nativeEvent.data);

        switch (message.type) {
          case 'load':     sendInitMessageToWidget(); break;
          case 'ready':     console.log('KYC Widget is ready'); break;
          case 'complete':  handleKycComplete(); break;
          case 'cancel':    handleKycCancel(); break;
          case 'error':     handleKycError(message.error); break;
          default: console.log('Unknown KYC Widget message type:', message.type);
        }
      };

      const handleKycComplete = () => { /* navigate to success */ };
      const handleKycCancel = () => { /* return user to previous screen */ };
      const handleKycError = (error) => { /* show error UI */ };

      return (
        <WebView
          ref={webViewRef}
          source={{ uri: session.url }}
          javaScriptEnabled
          onMessage={handleMessage}
        />
      );
    };
    ```

    <Note>`force_repaint` is a WKWebView-specific workaround. If you see repaint glitches on iOS, forward it the same way as `load`, toggling the WebView's `opacity` briefly via `injectJavaScript`. Check the iOS example for details.</Note>
  </Tab>
</Tabs>

## Theme and layout setup

Set `theme` and `layout` in the [Create session](/rest-apis/widgets-api/kyc/create-session) `options` to customize the Widget's appearance. See [WidgetThemeOption](/widgets/kyc/sdk-reference#widgetthemeoption) and [WidgetLayout](/widgets/kyc/sdk-reference#widgetlayout) for all options.

The Widget applies the options set in Create session once it has loaded the session. Until then, it renders its defaults: the browser or OS color scheme and the boxed layout. If you set `theme` or `layout`, the Widget may briefly show those defaults before switching.

Until a future release removes the need for it, pass the same `theme` and `layout` from your frontend as well. Use the same values in both places, since Create session values replace the frontend ones once the session loads.

### With the Web SDK

Pass the same `theme` and `layout` in the constructor `options`:

```javascript theme={null}
const widget = new KycWidget(session, {
  layout: 'fluid',
  theme: { appearance: 'dark' }
});
```

### Without the SDK

1. Before loading `session.url`, append a `theme_appearance` query parameter with the value you want (`dark` or `light`). The Widget renders before it receives any options, so this makes its first render use the right light or dark mode instead of the browser or OS color scheme:

   ```javascript theme={null}
   const url = new URL(session.url);
   url.searchParams.set('theme_appearance', 'dark'); // or 'light'
   ```

   This works the same whether you load the result into a web iframe or as your native WebView's top-level page.

   <Note>Add `theme_appearance` through `URL`/`URLSearchParams`, as above, to preserve the `sessionToken` query parameter the Widget needs to load its session. Don't rebuild the query string by hand.</Note>

2. When the Widget sends its `load` message, reply with an `init` message carrying the same `theme` and `layout`:

   ```javascript theme={null}
   iframe.contentWindow.postMessage(
     { options: { layout: 'fluid', theme: { appearance: 'dark' } }, type: 'init' },
     sessionOrigin
   );
   ```

## Test in Sandbox

With your Sandbox credentials and the Sandbox Widget host configured, run through this checklist — it applies whichever approach you integrated with:

* The Widget mounts and `ready` fires.
* Completing the verification flow fires `complete`.
* Closing or dismissing the Widget fires `cancel`.
* If your app uses a CSP (see [Shared setup](#shared-setup)), the browser console shows no violations (look for "Refused to frame").

Once Sandbox is green, swap your OAuth credentials to Production. The Widget host is selected automatically by the session `url` returned from your backend — no client-side environment switching is needed.

## Configuration reference

The most common Widget options. See the [SDK reference](./sdk-reference#options) for the full schema and all event types.

If you're integrating without the SDK, these map directly to the `options` object you send in the [Create session](/rest-apis/widgets-api/kyc/create-session) request, or in your `init` reply, except `debug`, which only applies to the SDK.

| Option | Purpose |
| - | - |
| `theme` | Customize the Widget's appearance: force `light` or `dark` mode, set brand colors, typography, and per-component border radii. See [WidgetThemeOption](/widgets/kyc/sdk-reference#widgetthemeoption) for all options. |
| `layout` | Control how the Widget is laid out on larger viewports — a centered, framed `'boxed'` card (default) or a `'fluid'` fill of its container. |
| `debug` | **SDK only.** Verbose SDK console logging. Use during development. Has no effect in the Create session request or the `init` message. |

## Troubleshooting

**Widget not displaying**

Confirm the Widget host for your environment is in the `frame-src` directive of your CSP (see [Shared setup](#shared-setup)). Open DevTools → Console and look for `Refused to frame` violations.

**Container is empty after mount**

The iframe fills its container — the container must have explicit CSS width and height. Minimum recommended size is 400px × 600px.

**Widget briefly shows the wrong theme or layout**

The Widget renders its defaults (the browser or OS color scheme and the boxed layout) until it loads the session, then switches to the `theme` and `layout` set in Create session. Verify that:

* You pass the same `theme` and `layout` from your frontend, with the same values as in Create session.
* Without the SDK, you append `theme_appearance` to `session.url` before loading it, and reply to `load` with `init` as soon as you receive it.

See [Theme and layout setup](#theme-and-layout-setup).

**Events not firing in native apps (with the Web SDK)**

Verify that:

* JavaScript is enabled in the WebView.
* The message bridge is registered **before** the HTML page loads.
* Event handler names match the platform-specific bridge contract used in `sendToNativeApp`.

**Events not firing (without the SDK)**

Verify that:

* Your message-handler / listener name is exactly `uphdKycWidget` — the name the Widget checks for on both iOS and Android — and is registered **before** the WebView loads the session `url`.
* On web, you're filtering incoming `message` events by origin (`event.origin === sessionOrigin`) — messages from other origins should be ignored, not treated as Widget events.

**Widget stays in a loading state and sends `error`**

The Widget couldn't load its session. Usually, the `sessionToken` in `session.url` is expired, invalid, or already used, or `session.url` was modified or rebuilt without its query string. Create a new session and load its `session.url` unmodified.

**Widget never unmounts.** The Web SDK does not auto-unmount, and neither does the Widget itself when integrating without it. Call `widget.unmount()` (Web SDK) or tear down your iframe/WebView (without the SDK) from each terminal message (`complete`, `cancel`, `error`).

## Next steps

* Review the complete [SDK Reference](./sdk-reference) for all available methods and events.
* Follow the [user onboarding guide](/developer-guides/user-onboarding/individual/via-kyc-widget) for a step-by-step walkthrough of verifying users with the KYC Widget.
