2.4 KiB
File: COMMIT_08_VOICE_TOKEN.md
Commit 8: Real-time Voice: Token API
Objective
Implement the serverless-friendly Deepgram token generation API. This is the expert-level correction to the user's "WebSocket proxy" plan. A standard Vercel deployment does not support persistent WebSocket backends.22
This architecture (based on the nextjs-live-transcription starter's implications 23) provides a secure, stateless way to use Deepgram's real-time streaming:
- The client requests a temporary token from our Next.js API.
- Our Next.js API (server-side) uses
our secret Deepgram API key to generate a temporary, short-lived token. - The client receives this temporary token and uses it to connect directly to Deepgram's WebSocket endpoint.
Implementation Specification
1. Create app/api/voice-token/route.ts
Create a file at /app/api/voice-token/route.ts:
TypeScript
import { NextRequest, NextResponse } from 'next/server';
import { DeepgramClient, createClient } from '@deepgram/sdk';
/**
* This API route generates a short-lived, temporary API key
* for a client to connect directly to Deepgram's WebSocket.
* This avoids exposing our main API key and bypasses
* serverless WebSocket limitations.
*/
export async function POST(request: NextRequest) {
const deepgramApiKey = process.env.DEEPGRAM_API_KEY;
if (!deepgramApiKey) {
return NextResponse.json(
{ error: 'Deepgram API key not configured' },
{ status: 500 }
);
}
const deepgram: DeepgramClient = createClient(deepgramApiKey);
try {
// Create a new, temporary key with 'member' permissions
// that expires in 1 minute (60 seconds).
const { key, error } = await deepgram.keys.create(
null, // Let Deepgram generate the key
'Temporary key for Ponderants user',
['member'], // Required scope for transcription
{ timeToLive: 60 }
);
if (error) {
throw error;
}
// Send the temporary key back to the client
return NextResponse.json({ key });
} catch (error) {
console.error('Error creating Deepgram key:', error);
return NextResponse.json(
{ error: 'Failed to generate voice token' },
{ status: 500 }
);
}
}
Test Specification
This is an API-only commit. It will be tested by the client implemented in Commit 09.