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

# Web Component API

> Integrate Corti Assistant using the modern Web Component approach

The Web Component API is the **recommended approach** for embedding Corti Assistant into your application. It provides a modern, framework-agnostic integration method using standard Web Components that work with any framework.

This approach works for **both native applications with WebView controls** (C#, .NET, Electron) and **web applications** built with any modern framework. We provide dedicated React wrappers for enhanced developer experience, while other frameworks (Vue, Angular, Svelte, etc.) can use the raw HTML element directly or with small framework-specific wrappers.

<Tip>
  **Want to skip to code?** Full working examples are available in the [Corti Examples Repository](https://github.com/corticph/corti-examples/tree/main/embedded-assistant) for both [vanilla TypeScript](https://github.com/corticph/corti-examples/tree/main/embedded-assistant/vanilla-ts/basic-example) and [React](https://github.com/corticph/corti-examples/tree/main/embedded-assistant/react/basic-example).
</Tip>

***

## Installation

Install the Corti Embedded Web package:

<CodeGroup>
  ```bash npm theme={null}
  npm install @corti/embedded-web
  ```

  ```bash yarn theme={null}
  yarn add @corti/embedded-web
  ```

  ```bash pnpm theme={null}
  pnpm add @corti/embedded-web
  ```
</CodeGroup>

## Authentication

Before using the Web Component API, authenticate your users using OAuth2. See the [Authentication Guide](/assistant/authentication) for complete setup instructions including Authorization Code Flow with PKCE (recommended), obtaining tokens, and handling token refresh.

<Info>
  All Embedded Assistant integrations require user-based OAuth2 authentication. Client credentials and machine-to-machine flows are not supported.
</Info>

***

## Usage

The Web Component works with any modern framework (React, Vue, Angular, Svelte, etc.) since it's based on standard Web Components. We provide dedicated React wrappers for enhanced developer experience, while other frameworks can use the raw HTML element with small framework-specific wrappers if needed.

### Vanilla TypeScript/JavaScript

This approach works universally - use it directly or wrap it in framework-specific components for Vue, Angular, or other frameworks.

<Info>
  **Full working example**: See the complete [vanilla TypeScript example](https://github.com/corticph/corti-examples/tree/main/embedded-assistant/vanilla-ts/basic-example) with authentication, interaction creation, and event handling.
</Info>

Import the web component and use it as a custom HTML element:

```typescript theme={null}
import "@corti/embedded-web";
```

Add the custom element to your HTML:

```html theme={null}
<corti-embedded
  id="assistant"
  baseurl="https://assistant.eu.corti.app"
  visibility="visible"
></corti-embedded>
```

Access the API via the element reference (which should be automatically typed if retrieved via `querySelector`):

```typescript theme={null}
async function initializeAssistant() {
  const corti = document.querySelector("corti-embedded");

  // Wait for the custom element to be defined
  await customElements.whenDefined("corti-embedded");

  // Wait for the embedded assistant to be ready
  await new Promise<void>((resolve) => {
    corti.addEventListener("embedded.ready", () => resolve(), { once: true });
  });

  // Authenticate
  await corti.auth({
    access_token: "your-access-token",
    refresh_token: "your-refresh-token",
    id_token: "your-id-token",
    token_type: "Bearer",
  });

  // Create interaction
  const interaction = await corti.createInteraction({
    assignedUserId: null,
    encounter: {
      identifier: `encounter-${Date.now()}`,
      status: "planned",
      type: "first_consultation",
      period: { startedAt: new Date().toISOString() },
    },
  });

  // Navigate to session
  await corti.navigate(`/session/${interaction.id}`);

  // Handle errors
  corti.addEventListener("error", (event: CustomEvent) => {
    console.error("Error:", event.detail?.message);
  });

  // Optional: Listen to all events for debugging and monitoring
  corti.addEventListener(
    "event",
    (event: CustomEvent<{ name: string; payload: unknown }>) => {
      console.log("Event:", event.detail.name, event.detail.payload);
    },
  );
}

// Initialize when the DOM is ready
initializeAssistant().catch(console.error);
```

### React (built-in support)

For React, we provide dedicated components and hooks for the best developer experience. For other frameworks like Vue or Angular, use the vanilla approach above and create small framework-specific wrappers as needed.

<Info>
  **Full working example**: See the complete [React example](https://github.com/corticph/corti-examples/tree/main/embedded-assistant/react/basic-example) with authentication, interaction creation, and event handling.
</Info>

<Note>
  In React, use the `baseURL` prop. In plain HTML, use the `baseurl` attribute. Both map to the same underlying component property.
</Note>

Import the React component and hook:

```typescript theme={null}
import {
  CortiEmbeddedReact,
  type CortiEmbeddedReactRef,
  useCortiEmbeddedApi,
} from "@corti/embedded-web/react";
```

Use the component in your React application:

```tsx theme={null}
import { useRef } from "react";
import {
  CortiEmbeddedReact,
  type CortiEmbeddedReactRef,
  useCortiEmbeddedApi,
} from "@corti/embedded-web/react";

function EmbeddedAssistant({ baseURL, authData }) {
  const cortiRef = useRef<CortiEmbeddedReactRef>(null);
  const api = useCortiEmbeddedApi(cortiRef);
  const hasInitialized = useRef(false);

  const handleReady = async () => {
    // Guard against React StrictMode double-invocation
    if (hasInitialized.current) return;
    hasInitialized.current = true;

    try {
      // Authenticate
      await api.auth(authData);

      // Create interaction
      const interaction = await api.createInteraction({
        assignedUserId: null,
        encounter: {
          identifier: `encounter-${Date.now()}`,
          status: "planned",
          type: "first_consultation",
          period: { startedAt: new Date().toISOString() },
        },
      });

      // Navigate to session
      await api.navigate(`/session/${interaction.id}`);
    } catch (error) {
      console.error("Error:", error);
    }
  };

  const handleError = (event: CustomEvent) => {
    console.error("Error:", event.detail?.message);
  };

  const handleEvent = (event: CustomEvent) => {
    console.log("Event:", event.detail.name, event.detail.payload);
  };

  return (
    <CortiEmbeddedReact
      ref={cortiRef}
      baseURL={baseURL}
      visibility="visible"
      onReady={handleReady}
      onError={handleError}
      onEvent={handleEvent}
      style={{ width: "100%", height: "100%" }}
    />
  );
}
```

***

## Component properties

### `baseURL` (required)

The base URL of the Corti Assistant instance. Choose the appropriate region:

* **EU**: `https://assistant.eu.corti.app`
* **EU MD**: `https://assistantmd.eu.corti.app` (medical device compliant)
* **US**: `https://assistant.us.corti.app`

### `visibility` (optional)

Controls the initial visibility of the embedded assistant:

* `"visible"` (default): Assistant is visible on mount
* `"hidden"`: Assistant is hidden on mount

***

## API methods

All API methods are available through the element reference (vanilla) or via the `useCortiEmbeddedApi` hook (React).

<Info>
  **Shared API surface**

  The Web Component provides the same operations documented in the [API Reference](/assistant/api-reference). Web Component, Window API, and PostMessage expose the same capabilities, but their invocation shapes differ.

  This page focuses on the package API exposed by the Web Component and React wrapper. For Window API and PostMessage-specific call shapes, see the [API Reference](/assistant/api-reference).
</Info>

### Core methods

* **`auth(credentials)`** - Authenticate the user session
* **`configure(config)`** - Configure interface features and appearance
* **`createInteraction(interaction)`** - Create a new clinical interaction
* **`navigate(path)`** - Navigate to a specific route
* **`startRecording()`** - Start audio recording
* **`stopRecording()`** - Stop audio recording
* **`getStatus()`** - Get current session status
* **`configureSession(config)`** - Configure session-specific settings
* **`getTemplates()`** - Retrieve available document templates
* **`addFacts(factsArray)`** - Add clinical facts to the current interaction
* **`setCredentials(credentials)`** - Update authentication credentials

See the [API Reference](/assistant/api-reference) for detailed documentation of each method.

***

## Events

The Web Component emits events for all Assistant activities. Listen for events using standard event listeners.

### Ready event

Emitted when the Assistant is fully loaded and ready to receive API calls:

```typescript theme={null}
corti.addEventListener(
  "embedded.ready",
  event => {
    console.log("Assistant is ready", event.detail);
  },
);
```

### Other named events

You can listen for all other named events directly by listening for them as above.

For example, the `recording.started` event (as detailed [here](/assistant/events/generated/recording/started)):

```typescript theme={null}
corti.addEventListener(
  "recording.started",
  event => {
    console.log("Recording has started", event.detail);
  },
);
```

For a complete list of events and their payloads, see the [Events Reference](/assistant/events/index).

### Error event

Emitted when an API call fails or an error occurs:

```typescript theme={null}
corti.addEventListener("error", (event: CustomEvent) => {
  console.error("Error:", event.detail);
  // event.detail contains: { message: string, code?: string, details?: unknown }
});
```

### Generic event

You can also listen for all events, regardless of type, by simply listening for `"event"` as per below:

```typescript theme={null}
corti.addEventListener(
  "event",
  (event: CustomEvent<{ name: string; payload: unknown }>) => {
    console.log("Event name:", event.detail.name);
    console.log("Event payload:", event.detail.payload);
  },
);
```

This is useful for debugging and logging purposes, but be aware that there are *many* events with lots of data, so be mindful about putting this into production.

***

## End-user authentication

Before using most API methods, you must authenticate with valid OAuth2 tokens. The Web Component expects tokens from an OAuth2 authentication flow.

See the [Authentication Guide](/assistant/authentication) for detailed information on obtaining tokens.

```typescript theme={null}
await api.auth({
  access_token: "your-access-token",
  refresh_token: "your-refresh-token",
  id_token: "your-id-token",
  token_type: "Bearer",
});
```

***

## Configuration

Configure the Assistant interface after authentication:

```typescript theme={null}
await api.configure({
  features: {
    interactionTitle: true,
    aiChat: true,
    documentFeedback: false,
    navigation: true,
    virtualMode: true,
    syncDocumentAction: false,
    templateEditor: true,
  },
  appearance: {
    primaryColor: "#00a6ff",
  },
  locale: {
    interfaceLanguage: "en",
    dictationLanguage: "en",
  },
});
```

See the [Configuration Guide](/assistant/configuration) for all available options.

***

## Full working examples

Complete, runnable examples are available in the [Corti Examples Repository](https://github.com/corticph/corti-examples):

<CardGroup cols={2}>
  <Card title="Vanilla TypeScript Example" icon="js" href="https://github.com/corticph/corti-examples/tree/main/embedded-assistant/vanilla-ts/basic-example">
    Demonstrates `<corti-embedded>` web component usage with vanilla TypeScript, including authentication, interaction creation, navigation, and event handling.
  </Card>

  <Card title="React Example" icon="react" href="https://github.com/corticph/corti-examples/tree/main/embedded-assistant/react/basic-example">
    Demonstrates `CortiEmbeddedReact` component and `useCortiEmbeddedApi` hook usage with React, including authentication, interaction creation, navigation, and event handling.
  </Card>
</CardGroup>

***

## TypeScript support

The package includes full TypeScript definitions:

```typescript theme={null}
import type {
  CortiEmbeddedAPI,
  CreateInteractionPayload,
  ConfigureAppPayload,
  KeycloakTokenResponse,
} from "@corti/embedded-web";

import type {
  CortiEmbeddedReactRef,
} from "@corti/embedded-web/react";
```

***

## Next steps

<CardGroup cols={2}>
  <Card title="Integration Comparison" icon="scale-balanced" href="/assistant/integrations-overview">
    Compare all three integration methods and choose the right one for your architecture
  </Card>

  <Card title="Authentication Setup" icon="key" href="/assistant/authentication">
    Set up OAuth2 authentication for your users
  </Card>

  <Card title="API Reference" icon="book" href="/assistant/api-reference">
    Complete API documentation for all methods
  </Card>

  <Card title="Configuration Guide" icon="sliders" href="/assistant/configuration">
    Customize the Assistant interface and behavior
  </Card>
</CardGroup>
