How to use websockets on workers?

I'm trying to connect openAI realtime to workers, I use nuxt/nitro. I get this error in the logs: [ws] Error in open handler: SyntaxError: WebSocket Constructor: The protocol header token is invalid.
1 Reply
cosbgn
cosbgnOP2w ago
This is an example which works locally but fails on production/workers: https://pastecode.io/s/j4oo4jvn For whomever finds this via search the solution is to use subprotocols:
// --- OpenAI Realtime connection (Cloudflare Workers compatible) ---
// Use WebSocket subprotocols for auth & beta flags instead of custom headers.
// Ref: OpenAI Realtime API docs.
const MODEL = process.env.OPENAI_REALTIME_MODEL || 'gpt-4o-realtime-preview-2024-12-17'
const subprotocols: string[] = [
'realtime',
`openai-insecure-api-key.${process.env.OPENAI_API_KEY}`,
process.env.OPENAI_ORG_ID ? `openai-organization.${process.env.OPENAI_ORG_ID}` : undefined,
process.env.OPENAI_PROJECT_ID ? `openai-project.${process.env.OPENAI_PROJECT_ID}` : undefined,
'openai-beta.realtime-v1'
].filter(Boolean) as string[]

const openAiWs = new WebSocket(`wss://api.openai.com/v1/realtime?model=${encodeURIComponent(MODEL)}`, subprotocols)
// --- OpenAI Realtime connection (Cloudflare Workers compatible) ---
// Use WebSocket subprotocols for auth & beta flags instead of custom headers.
// Ref: OpenAI Realtime API docs.
const MODEL = process.env.OPENAI_REALTIME_MODEL || 'gpt-4o-realtime-preview-2024-12-17'
const subprotocols: string[] = [
'realtime',
`openai-insecure-api-key.${process.env.OPENAI_API_KEY}`,
process.env.OPENAI_ORG_ID ? `openai-organization.${process.env.OPENAI_ORG_ID}` : undefined,
process.env.OPENAI_PROJECT_ID ? `openai-project.${process.env.OPENAI_PROJECT_ID}` : undefined,
'openai-beta.realtime-v1'
].filter(Boolean) as string[]

const openAiWs = new WebSocket(`wss://api.openai.com/v1/realtime?model=${encodeURIComponent(MODEL)}`, subprotocols)

Did you find this page helpful?