Skip to content

Client Examples

This page provides implementation examples of StreamElements’ websocket client in various programming languages. These examples demonstrate how to connect to the Astro Websocket Gateway, subscribe to topics, and handle incoming messages.

This example uses the browser’s native WebSocket API to implement a websocket client.

No additional dependencies are required.

// StreamElements Websocket Client - Browser Example
const websocket = new WebSocket('wss://astro.streamelements.com');
// Connection opened
websocket.addEventListener('open', (event) => {
console.log('Connected to StreamElements Astro');
});
// Listen for messages
websocket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
switch (message.type) {
case 'welcome':
console.log('Welcome received, client ID:', message.data.client_id);
// Subscribe to a topic after receiving welcome
websocket.send(JSON.stringify({
type: 'subscribe',
nonce: crypto.randomUUID(),
data: {
topic: 'channel.activities',
room: 'YOUR_CHANNEL_ID',
token: 'YOUR_JWT_TOKEN',
token_type: 'jwt'
}
}));
break;
case 'response':
if (message.error) {
console.error('Error:', message.error, message.data.message);
} else {
console.log('Success:', message.data.message);
}
break;
case 'message':
console.log(`[${message.topic}] in room ${message.room}:`, message.data);
if (message.topic === 'channel.activities') {
console.log('New activity:', message.data.type, message.data);
} else if (message.topic === 'channel.session.update') {
console.log('Session update - Key:', message.data.key);
console.log('Session update - Data:', message.data.data);
} else if (message.topic === 'channel.session.reset') {
console.log('Session reset - Full session data:', message.data);
}
break;
case 'reconnect':
console.log('Server is shutting down, reconnecting...');
const token = message.data.reconnect_token;
// Open a new connection with the reconnect token
const newWs = new WebSocket(
`wss://astro.streamelements.com/?reconnect_token=${token}`
);
// Transfer your event listeners to newWs...
break;
}
});
// Connection error
websocket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
// Connection closed
websocket.addEventListener('close', (event) => {
console.log('Connection closed:', event.code, event.reason);
// Implement reconnection logic here if needed
});
// Unsubscribe from a specific room
function unsubscribe(topic, room) {
websocket.send(JSON.stringify({
type: 'unsubscribe',
nonce: crypto.randomUUID(),
data: {
topic: topic,
room: room
}
}));
}
// Unsubscribe from all rooms for a topic
function unsubscribeAll(topic) {
websocket.send(JSON.stringify({
type: 'unsubscribe',
nonce: crypto.randomUUID(),
data: {
topic: topic
}
}));
}

Astro sends a reconnect message with a token before graceful shutdown. Use this token to reconnect without re-subscribing:

websocket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.type === 'reconnect') {
const token = message.data.reconnect_token;
const newWs = new WebSocket(
`wss://astro.streamelements.com/?reconnect_token=${token}`
);
// The new connection will restore all subscriptions automatically
}
});

For unexpected disconnects (network errors, etc.), implement exponential backoff and re-subscribe:

function connectWithRetry() {
const ws = new WebSocket('wss://astro.streamelements.com');
ws.addEventListener('open', () => {
console.log('Connected to StreamElements Astro');
reconnectionAttempts = 0;
});
ws.addEventListener('close', (event) => {
const reconnectDelay = Math.min(1000 * Math.pow(2, reconnectionAttempts), 30000);
reconnectionAttempts++;
console.log(`Reconnecting in ${reconnectDelay}ms...`);
setTimeout(connectWithRetry, reconnectDelay);
});
return ws;
}
let reconnectionAttempts = 0;
let websocket = connectWithRetry();

To authenticate using OAuth2 instead of JWT:

const subscribeMessage = {
type: 'subscribe',
nonce: crypto.randomUUID(),
data: {
topic: 'channel.activities',
room: 'YOUR_CHANNEL_ID',
token: 'YOUR_OAUTH2_TOKEN',
token_type: 'oauth2'
}
};

If you receive a rate_limit_exceeded error, back off before retrying. See Rate Limits for the current limits:

websocket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.error === 'rate_limit_exceeded') {
console.log('Rate limit exceeded, backing off...');
// Wait before retrying - note that rate limit responses do not include a nonce
setTimeout(() => {
// Retry your command
}, 5000);
}
});