I'm encountering a persistent WebSocket connection error when trying to connect to the Kite WebSocket API. Despite verifying that the access token and API key are correct and active, I keep receiving the following error:
WebSocket error: Error: Unexpected server response: 403
Details: 1.Access Token is valid — I confirmed this by calling the user profile API and got the expected user data. 2.Using correct API Key and Access Token 3.WebSocket URL used: const url = `wss://ws.kite.trade/?api_key=${apiKey}&access_token=${accessToken}&uid=${new Date().getTime().toString()}`; 4.Also including X-Kite-Version:3 in headers 5. Checked using uid in url and without uid in url
Code Snippet:
const WebSocket = require('ws'); const url = `wss://ws.kite.trade/?api_key=${apiKey}&access_token=${accessToken}&uid=${new Date().getTime().toString()}`; console.log('Connecting to Kite WebSocket at:', url); const conn = new WebSocket(url, { headers: { 'X-Kite-Version': '3', // "User-Agent": "kiteconnectjs/5.1.0" // Uncommenting this didn't help either } }); conn.on('error', (err) => { console.error("WebSocket error:", err); });
Error Stack Trace: Error: Unexpected server response: 403 at ClientRequest. (/.../node_modules/ws/lib/websocket.js:913:7) at TLSWrap.onStreamRead (node:internal/stream_base_commons:191:23)
What I've Tried: 1.Regenerating access token and reconnecting — same issue. 2.Verifying token via profile API — works fine. 3.Tried adding/removing the User-Agent header.
Please help me understand why I'm getting a 403 on the WebSocket despite using a valid token and following the official documentation. using documentation : https://kite.trade/docs/connect/v3/websocket/
A 403 generally means, session expired or permission is not there for initiating the Websocket connection. Make sure you have created a Kite Connect app on developers console and not Kite personal app.
If you have a valid Kite Connect app. You may print the api_key and access_token before setting the url.
Make sure you are not calling generate_session method every run. You may also refer to this thread.
Make sure you have created a Kite Connect app on developers console and not Kite personal app.
If you have a valid Kite Connect app. You may print the
api_key
andaccess_token
before setting the url.Make sure you are not calling
generate_session
method every run. You may also refer to this thread.