> ## 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 TypeScript Example

> Get your first AI avatar running using a TypeScript Express server.

This guide will walk you through setting up a minimal example of an interactive AI avatar using a backend built with TypeScript and Express.

## 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">
    Initialize a new project and install the required runtime and development dependencies:

    ```bash theme={null}
    npm init -y
    npm install express dotenv @trugen/js-sdk
    npm install -D typescript ts-node @types/express @types/node
    ```
  </Step>

  <Step title="Configure TypeScript">
    Create a `tsconfig.json` file in the root of your project:

    ```json theme={null}
    {
      "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "lib": ["ES2020"],
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "outDir": "dist",
        "rootDir": "."
      },
      "include": ["server.ts"],
      "exclude": ["node_modules", "dist"]
    }
    ```
  </Step>

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

    ```text theme={null}
    project/
    ├── .env
    ├── server.ts
    ├── public/
    │   └── index.html
    ├── tsconfig.json
    └── 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_trugen_api_key
    AGENT_ID=your_agent_id
    ```

    <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.ts` — this fetches the session token on the backend to keep your credentials secure:

    ```typescript theme={null}
    import express, { Request, Response } from "express";
    import path from "path";
    import dotenv from "dotenv";

    dotenv.config();

    const app = express();

    app.use(express.static("public"));

    app.get("/token", async (_req: Request, res: Response): Promise<void> => {
      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 as string,
          },
          body: JSON.stringify({
            agentId: process.env.AGENT_ID,
          }),
        });

        const data = await response.json() as { token: string };

        res.json({ token: data.token });
      } catch (error) {
        console.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 Frontend">
    Create `public/index.html`. The frontend runs plain browser JS and imports the SDK from esm.sh directly, so no TypeScript compilation is required for the client side:

    ```html theme={null}
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>TruGen SDK Test (TS)</title>
    </head>
    <body>

      <h2>TruGen SDK Test (TypeScript Server)</h2>

      <button id="connectBtn">Connect</button>
      <button id="disconnectBtn">Disconnect</button>

      <br /><br />

      <video
        id="avatarVideo"
        autoplay
        playsinline
        style="width:600px;border:1px solid #ccc;"
      ></video>

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

        let session;

        document.getElementById("connectBtn").addEventListener("click", async () => {
          try {
            const response = await fetch("/token");
            const { token } = await response.json();

            session = await createClient({ token });

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

            await session.connect();
            console.log("Connected");
          } catch (err) {
            console.error(err);
          }
        });

        document.getElementById("disconnectBtn").addEventListener("click", async () => {
          if (session) {
            await session.disconnect();
            console.log("Disconnected");
          }
        });
      </script>

    </body>
    </html>
    ```
  </Step>

  <Step title="Run the Application">
    Start the server with `ts-node` for quick testing without a separate build step:

    ```bash theme={null}
    npx ts-node server.ts
    ```

    Open `http://localhost:3000` in your web browser, allow microphone access, and click **Connect**.
  </Step>
</Steps>
