# Getting Started with Hiyve SDK

Build a video conferencing app with Hiyve SDK in under 15 minutes. This guide walks you through setting up a server, connecting a React client, and rendering a video room with controls.

---

## Prerequisites

- **Node.js 18+** and npm
- **React 18+** with TypeScript
- **API key** (`pk_*`) from [console.hiyve.dev](https://console.hiyve.dev) — required for all Hiyve apps
- **Client secret** (`sk_*`) from [console.hiyve.dev](https://console.hiyve.dev) — required for video conferencing (room token generation). Not needed for identity-only apps.

---

## Step 1: Authenticate

Log in to the Hiyve private registry so you can install SDK packages:

```bash
npx @hiyve/cli login
```

Enter your API key (`pk_live_*` or `pk_test_*` from [console.hiyve.dev](https://console.hiyve.dev)). This configures your `.npmrc` with registry access.

> **Token expired?** If you've logged in before and your token has expired, `npx @hiyve/cli login` may fail with a 401 error. Run `npm config delete @hiyve:registry` first, then re-run the login command.

---

## Step 2: Create a Project

Scaffold a new React + TypeScript project with Vite:

```bash
npm create vite@latest my-hiyve-app -- --template react-ts
cd my-hiyve-app
```

---

## Step 3: Install Dependencies

Install the Hiyve SDK packages:

```bash
npm install @hiyve/rtc-client @hiyve/react @hiyve/react-ui
```

Install the server package (for token generation):

```bash
npm install @hiyve/admin express cors dotenv
```

Install UI dependencies (Material UI):

```bash
npm install @mui/material @mui/icons-material @emotion/react @emotion/styled
```

Install the dev tool for running client and server together:

```bash
npm install -D concurrently
```

---

## Step 4: Server Setup

The server handles authentication and token generation. Your API key and client secret stay on the server -- they are never exposed to the browser.

Create a `.env` file in your project root:

```env
# API Key (required — identifies your app)
APIKEY=pk_live_xxx

# Client Secret (required for video conferencing — generates room tokens)
CLIENT_SECRET=sk_live_xxx

# Server Configuration (optional — defaults shown)
SERVER_REGION=us-west-2
SERVER_REGION_URL=.rtc.muziemedia.com
ENVIRONMENT=development
```

Replace `pk_live_xxx` and `sk_live_xxx` with the values from your [developer console](https://console.hiyve.dev).

> **Identity-only apps** (login/register without video): You only need the `APIKEY` (`pk_*`). See the [basic-identity-example](https://github.com/hiyve/hiyve-examples/tree/main/basic-identity-example) for a client-only setup with no backend.

Create `server.js` in your project root:

```javascript
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import { mountHiyveRoutes, loadHiyveConfig } from '@hiyve/admin';

const app = express();
app.use(cors({ origin: ['http://localhost:5173'] }));
app.use(express.json());

const apiRouter = express.Router();
mountHiyveRoutes(apiRouter, loadHiyveConfig());
app.use('/api', apiRouter);

app.listen(3001, () => console.log('Server running on http://localhost:3001'));
```

`mountHiyveRoutes` registers the following endpoints on your router:

| Method | Path | Description |
|--------|------|-------------|
| POST | `/generate-room-token` | Generate a token for joining a WebRTC room |
| POST | `/generate-cloud-token` | Generate a token for AI cloud services |
| POST | `/generate-note` | Generate AI-powered meeting notes |
| POST | `/create-join-token` | Create a shareable invite token |
| GET | `/health` | Health check (returns config status, region, uptime) |
| ALL | `/hiyve/identity/*` | Identity proxy (forwards to Hiyve Cloud) |

Since the router is mounted at `/api`, the full paths become `/api/generate-room-token`, `/api/generate-cloud-token`, and so on.

---

## Step 5: Client Setup

### Configure HiyveProvider

`HiyveProvider` wraps your app and manages connection state. By default, it requests tokens by POSTing to `/api/generate-room-token` -- no extra configuration needed if the server is at the same origin.

Update `src/main.tsx`:

```tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { HiyveProvider } from '@hiyve/react';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <HiyveProvider>
    <App />
  </HiyveProvider>
);
```

### Configure Vite proxy

Since the dev server runs on port 5173 and the backend runs on port 3001, add a proxy to forward `/api` requests. Update `vite.config.ts`:

```ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': 'http://localhost:3001',
    },
  },
});
```

---

## Step 6: Build the Room

### App.tsx -- Screen flow

Use `useRoomFlow()` to manage the lobby, connecting, and in-room screens:

```tsx
import { useRoomFlow } from '@hiyve/react';
import { JoinForm, ConnectingScreen } from '@hiyve/react-ui';
import VideoRoom from './VideoRoom';

function App() {
  const { screen } = useRoomFlow();

  switch (screen) {
    case 'connecting':
      return <ConnectingScreen />;
    case 'in-room':
      return <VideoRoom />;
    default:
      return <JoinForm autoConnect devicePreviewMode="inline" />;
  }
}

export default App;
```

- **Lobby** (default) -- `JoinForm` renders a form to enter a room name and display name, with an inline camera/microphone preview.
- **Connecting** -- `ConnectingScreen` shows a loading state while the connection is established.
- **In-room** -- Your custom `VideoRoom` component.

### VideoRoom.tsx -- Video grid and controls

```tsx
import { useState } from 'react';
import { useRoom, useConnection } from '@hiyve/react';
import { VideoGrid, ControlBar } from '@hiyve/react-ui';

function VideoRoom() {
  const { room } = useRoom();
  const { leaveRoom } = useConnection();
  const [layout, setLayout] = useState('grid');

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      {room?.name && <h2 style={{ margin: '8px 16px' }}>{room.name}</h2>}
      <VideoGrid layout={layout} showNames showLocalFlip />
      <ControlBar
        onLeave={leaveRoom}
        showScreenShare
        showLayoutSelector
        layout={layout}
        onLayoutChange={setLayout}
      />
    </div>
  );
}

export default VideoRoom;
```

`VideoGrid` renders all participants' video streams. `ControlBar` provides mute, camera toggle, screen share, layout switching, and leave controls.

---

## Step 7: Run It

Add a start script to `package.json`:

```json
{
  "scripts": {
    "dev": "concurrently \"node server.js\" \"vite\""
  }
}
```

Start the app:

```bash
npm run dev
```

Open [http://localhost:5173](http://localhost:5173) in your browser. Enter a room name and display name, then click join. Open a second browser tab with the same room name to see multi-participant video.

---

## Using the Development Environment

If you are working with the **development** version of the Hiyve SDK (pre-release packages, staging servers), pass the `--dev` flag to the CLI. This points both the CLI and your `.npmrc` at the development registry and servers.

### 1. Authenticate against the dev registry

```bash
npx @hiyve/cli --dev login
```

This configures your `.npmrc` to fetch `@hiyve/*` packages from the development registry instead of production. All other CLI commands also accept `--dev`:

```bash
npx @hiyve/cli --dev list      # list available dev packages
npx @hiyve/cli --dev whoami    # check dev auth status
```

### 2. Set your server to development mode

In your `.env` file, use your **test** keys and set `ENVIRONMENT=development`:

```env
# Test API key (required)
APIKEY=pk_test_xxx

# Test client secret (required for video conferencing)
CLIENT_SECRET=sk_test_xxx

SERVER_REGION=us-west-2
SERVER_REGION_URL=.rtc.muziemedia.com
ENVIRONMENT=development
```

`ENVIRONMENT=development` tells `@hiyve/admin` to route cloud API requests to the development servers.

### 3. Switch back to production

When you are ready to deploy, re-authenticate against the production registry (without `--dev`), switch to your live keys (`pk_live_*` / `sk_live_*`), and set `ENVIRONMENT=production`:

```bash
npx @hiyve/cli login
```

See the [Production Checklist](./production-checklist.md) for the full list of changes needed before going live.

---

## Troubleshooting

### `npm error 401 Unauthorized` when running `npx @hiyve/cli login`

If you see an error like:

```
npm error 401 Unauthorized - GET https://console.hiyve.dev/api/registry/@hiyve%2fcli
```

Your `~/.npmrc` has a stale registry entry from an older CLI version. Fix it by removing the old entry first:

```bash
npm config delete @hiyve:registry
npx @hiyve/cli login
```

---

## Next Steps

### Add recording and transcription

```bash
npm install @hiyve/react-capture
```

`@hiyve/react-capture` provides `RecordingControls`, `StreamingControls`, and `TranscriptionView` components for in-meeting recording and live captions.

### Add chat and collaboration

```bash
npm install @hiyve/react-collaboration
```

`@hiyve/react-collaboration` provides `ChatPanel`, `PollsWindow`, `QAPanel`, and `FileManager` components for in-meeting interaction.

### Add AI-powered intelligence

```bash
npm install @hiyve/react-intelligence @hiyve/cloud
```

`@hiyve/react-intelligence` provides `AIAssistant`, `MeetingSummary`, `SentimentDashboard`, and `AlertsPanel` components for AI-powered meeting features.

### Example apps

See working examples with full source code:

- [Basic Example](https://github.com/hiyve/hiyve-examples/tree/main/basic-example) -- minimal setup (this guide)
- [Full Example](https://github.com/hiyve/hiyve-examples/tree/main/full-example) -- all components integrated
- [AI Video Room](https://github.com/hiyve/hiyve-examples/tree/main/ai-video-room-example) -- recording, transcription, and AI sidebar
- [Token Room](https://github.com/hiyve/hiyve-examples/tree/main/token-room-example) -- shareable invite links with password protection
- [Next.js Example](https://github.com/hiyve/hiyve-examples/tree/main/nextjs-example) -- Next.js 14 App Router integration
- [Angular Example](https://github.com/hiyve/hiyve-examples/tree/main/angular-example) -- Angular 20 with `@hiyve/angular`
