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

# Build a Deepgram Voice Assistant with React and Node.js

> Run a local Node token endpoint and a React client with a live Deepgram transcript, a voice-state orb, and browser microphone and playback handling.

Keep the Deepgram project key in Node. When a user starts a call, the browser requests a temporary token, connects to your configured Voice Agent, and displays final conversation messages next to the orb. The transcript tells the reader what was said. The orb shows whose audio is active.

## Issue temporary tokens in Node

You need a Deepgram Voice Agent ID, a project API key that can grant temporary tokens, and Node 22 or newer. Save this as `token-server.mjs`. Run `node --env-file=.env.local token-server.mjs` with `DEEPGRAM_API_KEY` set in the server environment. A live call uses your Deepgram account.

```js theme={null}
import { createServer } from 'node:http'

const key = process.env.DEEPGRAM_API_KEY
if (!key) throw new Error('Set DEEPGRAM_API_KEY on the server')

createServer(async (req, res) => {
  res.setHeader('Cache-Control', 'no-store')
  res.setHeader('Content-Type', 'application/json')
  if (req.url !== '/api/deepgram-token' || req.method !== 'POST') {
    res.writeHead(404).end('{}')
    return
  }
  if (
    req.headers.host !== '127.0.0.1:8788' ||
    req.headers['x-orb-demo'] !== '1' ||
    req.headers.origin !== 'http://localhost:5173'
  ) {
    res.writeHead(403).end('{}')
    return
  }
  try {
    const response = await fetch('https://api.deepgram.com/v1/auth/grant', {
      method: 'POST',
      headers: { Authorization: 'Token ' + key, 'Content-Type': 'application/json' },
      body: '{}',
      signal: AbortSignal.timeout(8000),
    })
    if (!response.ok) throw new Error('Grant failed')
    const { access_token } = await response.json()
    if (typeof access_token !== 'string') throw new Error('Missing token')
    res.end(JSON.stringify({ access_token }))
  } catch {
    res.writeHead(502).end(JSON.stringify({ error: 'Could not start a voice session' }))
  }
}).listen(8788, '127.0.0.1')
```

This local server accepts requests from the demo origin through the proxy below. For a hosted app, use your existing authenticated backend to authorize each caller and enforce a usage limit before issuing a grant. [Deepgram token grant](https://developers.deepgram.com/reference/auth/tokens/grant)

## Connect Vite to the token server

Add this `server` option to your existing `vite.config.ts`. Open the app at `http://localhost:5173`. The proxy preserves the browser origin and sets the upstream Host header to the loopback server.

```ts theme={null}
server: {
  host: 'localhost',
  port: 5173,
  strictPort: true,
  proxy: {
    '/api/deepgram-token': { target: 'http://127.0.0.1:8788', changeOrigin: true },
  },
}
```

## Show the conversation alongside the orb

Run `npm install orb-ui @deepgram/agents@0.1.2`. Save this component as `DeepgramAssistant.tsx` and render it with your agent ID. The adapter creates a fresh session and player on each start. Each new call also begins a fresh transcript.

```tsx theme={null}
import { useEffect, useMemo, useState } from 'react'
import {
  AgentMicrophone,
  AgentPlayer,
  AgentSession,
  type ConversationTextMessage,
} from '@deepgram/agents'
import { Orb } from 'orb-ui'
import { createDeepgramAdapter } from 'orb-ui/adapters'

async function getToken() {
  const response = await fetch('/api/deepgram-token', {
    method: 'POST',
    headers: { 'X-Orb-Demo': '1' },
    cache: 'no-store',
  })
  if (!response.ok) throw new Error('Voice authorization failed')
  const { access_token } = await response.json()
  if (typeof access_token !== 'string') throw new Error('Missing access token')
  return access_token
}

export default function DeepgramAssistant({ agentId }: { agentId: string }) {
  const [turns, setTurns] = useState<ConversationTextMessage[]>([])
  const client = useMemo(() => {
    let detach = () => {}
    const adapter = createDeepgramAdapter({
      createResources() {
        detach()
        setTurns([])
        const session = new AgentSession({
          auth: { tokenFactory: getToken },
          agent: agentId,
          audio: {
            input: { encoding: 'linear16', sampleRate: 16000 },
            output: { encoding: 'linear16', sampleRate: 24000 },
          },
        })
        const append = (turn: ConversationTextMessage) =>
          setTurns((previous) => [...previous, turn])
        session.on('conversation-text', append)
        detach = () => session.off('conversation-text', append)
        const microphone = new AgentMicrophone((chunk) => session.sendAudio(chunk), {
          sampleRate: 16000,
        })
        const player = new AgentPlayer({ sampleRate: 24000 })
        return { session, microphone, player }
      },
    })
    return {
      adapter,
      dispose() {
        detach()
        adapter.stop()
      },
    }
  }, [agentId])
  useEffect(() => () => client.dispose(), [client])

  return (
    <section>
      <Orb adapter={client.adapter} theme="circle" aria-label="Start or stop the voice assistant" />
      <ol aria-label="Conversation transcript" aria-live="polite" aria-relevant="additions">
        {turns.map((turn, i) => (
          <li key={i}>
            <strong>{turn.role}</strong> {turn.content}
          </li>
        ))}
      </ol>
    </section>
  )
}
```

Start a call, ask one question, and interrupt the answer. You should see the user's words and the assistant's response in the list. The orb should follow audible playback and return to listening on interruption. A transcript arriving early is normal. If text appears while the speakers stay silent, check playback permission and the 24 kHz player configuration. [Deepgram adapter and audio lifecycle](https://orb-ui.com/docs/adapters/deepgram.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.