SDKsWeb SDK

Examples

Web SDK integration examples for React, Vue 3, Angular, and vanilla JS

Copy-paste examples for the most common frameworks. The React, Vue, and Angular examples render the agent inside a component, start the SDK when the component mounts, and call destroy() when it unmounts, so the connection and media tracks are cleaned up.

The SDK runs one widget at a time, so make sure only one component calls init at once. A second call before destroy() rejects with "SDK is already initialized".

Every example passes a getToken function that calls your own backend endpoint, here /api/avatar-session. That endpoint calls POST /public/agents/{agentId}/connections with your API key and returns the token.

import { useEffect, useRef } from "react";

import { NapsterCompanionApiSdk } from "@touchcastllc/napster-companion-api";
import type { NapsterCompanionApiInstance } from "@touchcastllc/napster-companion-api";
import "@touchcastllc/napster-companion-api/styles";

async function getToken() {
  const response = await fetch("/api/avatar-session", { method: "POST" });
  const { token } = await response.json();
  return token;
}

export function AgentWidget() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    let instance: NapsterCompanionApiInstance | null = null;
    let cancelled = false;

    // Wait one microtask, so React StrictMode's development-only
    // mount → unmount → mount cancels the first run before it starts the SDK.
    queueMicrotask(() => {
      if (cancelled) return;
      NapsterCompanionApiSdk.init(getToken, {
        layout: { type: "inline", mountContainer: container },
      }).then(
        (created) => {
          if (cancelled) created.destroy();
          else instance = created;
        },
        (error) => console.error(error),
      );
    });

    return () => {
      cancelled = true;
      instance?.destroy();
    };
  }, []);

  return <div ref={containerRef} style={{ width: 320, height: 480 }} />;
}
<template>
  <div ref="containerRef" style="width: 320px; height: 480px"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
import { NapsterCompanionApiSdk } from "@touchcastllc/napster-companion-api";
import type { NapsterCompanionApiInstance } from "@touchcastllc/napster-companion-api";
import "@touchcastllc/napster-companion-api/styles";

async function getToken() {
  const response = await fetch("/api/avatar-session", { method: "POST" });
  const { token } = await response.json();
  return token;
}

const containerRef = ref<HTMLElement>();
let instance: NapsterCompanionApiInstance | null = null;

onMounted(async () => {
  if (!containerRef.value) return;

  instance = await NapsterCompanionApiSdk.init(getToken, {
    layout: { type: "inline", mountContainer: containerRef.value },
  });
});

onUnmounted(() => {
  instance?.destroy();
});
</script>
import {
  AfterViewInit,
  Component,
  ElementRef,
  OnDestroy,
  ViewChild,
} from "@angular/core";
import { NapsterCompanionApiSdk } from "@touchcastllc/napster-companion-api";
import type { NapsterCompanionApiInstance } from "@touchcastllc/napster-companion-api";

@Component({
  selector: "app-agent",
  template: '<div #containerRef style="width: 320px; height: 480px"></div>',
})
export class AgentComponent implements AfterViewInit, OnDestroy {
  @ViewChild("containerRef") containerRef!: ElementRef<HTMLDivElement>;
  private instance: NapsterCompanionApiInstance | null = null;

  async ngAfterViewInit() {
    this.instance = await NapsterCompanionApiSdk.init(() => this.getToken(), {
      layout: { type: "inline", mountContainer: this.containerRef.nativeElement },
    });
  }

  ngOnDestroy() {
    this.instance?.destroy();
  }

  private async getToken() {
    const response = await fetch("/api/avatar-session", { method: "POST" });
    const { token } = await response.json();
    return token;
  }
}

Add the stylesheet to the styles array in angular.json: "node_modules/@touchcastllc/napster-companion-api/lib/index.css". If your app uses server-side rendering, start the SDK in afterNextRender instead of ngAfterViewInit, so it only runs in the browser.

If Angular's build stops with "Could not resolve" for two optional packages the SDK can load, mark them as external in the build options in angular.json (see Installation):

"architect": {
  "build": {
    "options": {
      "externalDependencies": [
        "@tensorflow/tfjs",
        "@tensorflow-models/face-landmarks-detection"
      ]
    }
  }
}
<div id="avatar-container" style="width: 320px; height: 480px"></div>

<script src="https://cdn.jsdelivr.net/npm/@touchcastllc/napster-companion-api@2/lib/index.standalone.js"></script>
<script>
  async function getToken() {
    const response = await fetch("/api/avatar-session", { method: "POST" });
    const { token } = await response.json();
    return token;
  }

  window.napsterCompanionApiSDK.init(getToken, {
    layout: { type: "inline", mountContainer: "#avatar-container" },
  });
</script>

For the floating corner widget instead, leave out layout and the container. The widget mounts on document.body, so you only need the init and destroy calls.

Start the SDK after the container exists in the DOM. In React, Vue, and Angular, the lifecycle hooks above guarantee this. In plain HTML, put the script after the container element, or wrap the init call in a DOMContentLoaded listener. If the selector matches nothing, the SDK mounts on document.body instead; set debug: true to see a warning in the console.

On TypeScript 6 or later, import "@touchcastllc/napster-companion-api/styles" can fail with "Cannot find module or type declarations for side-effect import". Add declare module "@touchcastllc/napster-companion-api/styles"; to a .d.ts file in your project.

Next steps

On this page