Environment Configuration
First, create an.env file in your project root to store your AssemblyAI API key securely:
.env
Token Generation Function
The token generator creates temporary tokens that expire after a specified duration. This prevents exposing your permanent API key to the browser.Create the token generator module
Create a Key points: Uses your permanent API key from environment variables, requests tokens with configurable expiration (max 600 seconds), and returns the temporary token string.
tokenGenerator.js file that requests temporary tokens from AssemblyAI:tokenGenerator.js
Set up the Express server
Create a Server responsibilities: Serves static frontend files from the
server.js file that serves your frontend and provides the token endpoint:server.js
public/ directory (line 8), provides a /token endpoint that generates temporary tokens (lines 10-17), and returns tokens with 60-second expiration (maximum is 600 seconds).How It Works
The token flow ensures your API key never reaches the browser:- Client requests token: Browser calls
GET /token - Server authenticates: Server uses permanent API key to request temporary token from AssemblyAI
- Token returned: Server sends temporary token to browser
- WebSocket connection: Browser uses temporary token to connect to AssemblyAI’s streaming endpoint
Temporary tokens are single-use and expire after the specified duration. This provides security while allowing client-side WebSocket connections.
Next Steps
With your server configured, you’re ready to:- Request microphone access from the user
- Connect to AssemblyAI’s streaming endpoint using the temporary token