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

# Basic JavaScript Example

> Get your first AI avatar running using a JavaScript Node server.

The TruGen API provides a simple interface for implementing digital AI avatars within your web applications. This guide will walk you through the process of setting up a minimal example of an interactive AI avatar using a JavaScript server.

## Prerequisites

* A TruGen API key (get one [here](https://app.trugen.ai/api-keys))
* A TruGen Agent ID (create and get one [here](https://app.trugen.ai/teammate-library))
* Node.js installed on your machine
* A modern web browser with microphone access

## Project Setup

<Steps>
  <Step title="Install Dependencies">
    ```bash theme={null}
    npm init -y
    npm install express dotenv @trugen/js-sdk
    ```
  </Step>

  <Step title="Set Up Project Structure">
    Create the following directory layout:

    ```text theme={null}
    project/
    ├── .env
    ├── server.js
    ├── public/
    │   └── index.html
    └── package.json
    ```
  </Step>

  <Step title="Add Your Credentials">
    Create a `.env` file and add your API key and Agent ID:

    ```env theme={null}
    TRUGEN_API_KEY=your-api-key-here
    AGENT_ID=your-agent-id-here
    ```

    <Warning>
      Never expose your API key in the browser. The server reads it from `.env` and returns only a short-lived session token to the client.
    </Warning>
  </Step>

  <Step title="Create the Server">
    Create `server.js` — this keeps your API key on the server and returns a session token to the browser:

    ```javascript theme={null}
    const express = require("express");
    require("dotenv").config();

    const app = express();
    app.use(express.json());
    app.use(express.static("public"));

    app.post("/api/session-token", async (req, res) => {
      try {
        const response = await fetch("https://api.trugen.ai/v1/auth/conversation", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-API-Key": process.env.TRUGEN_API_KEY,
          },
          body: JSON.stringify({
            agentId: process.env.AGENT_ID,
          }),
        });

        if (!response.ok) {
          const errorData = await response.json();
          console.error("Token creation failed:", errorData);
          return res.status(response.status).json({ error: "Token creation failed" });
        }

        const { token } = await response.json();
        res.json({ token });
      } catch (error) {
        console.error("Network error:", error);
        res.status(500).json({ error: "Failed to create session token" });
      }
    });

    app.listen(3000, () => console.log("Server running at http://localhost:3000"));
    ```
  </Step>

  <Step title="Create the HTML">
    Create `public/index.html`:

    ```html theme={null}
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Hello TruGen</title>
    </head>
    <body>
      <div style="text-align: center; padding: 20px;">
        <h1>Chat with your AI Avatar</h1>
        <p>Your avatar will appear below once connected</p>
        <video
          id="avatarVideo"
          autoplay
          playsinline
          style="max-width: 100%; border-radius: 8px;"
        ></video>
        <div id="status" style="margin-top: 15px; font-size: 14px; color: #666;">
          Ready
        </div>
        <br />
        <button id="connectBtn">Connect</button>
        <button id="disconnectBtn">Disconnect</button>
      </div>

      <script type="module">
        import { createClient, TruGenEvent } from "https://esm.sh/@trugen/js-sdk";

        const statusEl = document.getElementById("status");
        let session;

        document.getElementById("connectBtn").addEventListener("click", async () => {
          try {
            statusEl.textContent = "Creating session...";

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

            statusEl.textContent = "Connecting...";

            session = await createClient({ token });

            session.on(TruGenEvent.VIDEO_STREAM_STARTED, (track) => {
              track.attach(document.getElementById("avatarVideo"));
            });

            await session.connect();

            statusEl.textContent = "Connected! Start speaking to your avatar";
          } catch (err) {
            console.error(err);
            statusEl.textContent = "Failed to connect. Check your API key and Agent ID.";
          }
        });

        document.getElementById("disconnectBtn").addEventListener("click", async () => {
          if (session) {
            await session.disconnect();
            statusEl.textContent = "Disconnected";
          }
        });
      </script>
    </body>
    </html>
    ```
  </Step>

  <Step title="Run">
    ```bash theme={null}
    node server.js
    ```

    Navigate to `http://localhost:3000` in your browser, allow microphone access when prompted, then click **Connect**.
  </Step>
</Steps>
