JavaScript / Node.js WebSocket Client: // Browser / Node.js WebSocket Subscription Client (graphql-ws)
const ws = new WebSocket('wss://api.example.com/graphql', 'graphql-transport-ws');
ws.onopen = () => {
console.log('Connected to GraphQL WebSocket endpoint');
// 1. Send connection_init
ws.send(JSON.stringify({"type":"connection_init","payload":{"Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log('Received frame:', msg);
if (msg.type === 'connection_ack') {
// 2. Start subscription on ACK
ws.send(JSON.stringify({"id":"sub_orders_01","type":"subscribe","payload":{"query":"subscription OnNewOrder($storeId: ID!) {\n newOrder(storeId: $storeId) {\n id\n amount\n status\n createdAt\n }\n}","variables":{"storeId":"store_99"}}}));
}
if (msg.type === 'next') {
console.log('Subscription Event Data:', msg.payload.data);
}
};