Skip to main content
Version: 3.2.x

Authentication & Connection

Browser Authentication

For browser applications, use a token provider function:

import OptaveJavaScriptSDK from '@optave/client-sdk';

const client = new OptaveJavaScriptSDK({
websocketUrl: 'wss://ws-{{tenant}}.oco.optave.{{tld}}',
authTransport: 'subprotocol',
tokenProvider: async () => {
// Replace '/api/optave-token' with your actual backend endpoint
const response = await fetch('/api/optave-token');
const { token } = await response.json();
return token;
}
});

Note: Never expose client secrets in browser code. Use a backend endpoint to fetch tokens.

Server Authentication

For Node.js servers, use the authenticate method with client credentials:

import OptaveJavaScriptSDK from '@optave/client-sdk/server';

const client = new OptaveJavaScriptSDK({
websocketUrl: process.env.OPTAVE_WEBSOCKET_URL,
authenticationUrl: process.env.OPTAVE_AUTHENTICATION_URL,
clientId: process.env.OPTAVE_CLIENT_ID,
clientSecret: process.env.OPTAVE_CLIENT_SECRET
});

async function authenticateAndConnect() {
try {
const token = await client.authenticate();
console.log('Authentication successful');
await client.openConnection(token);
console.log('Connected');
} catch (error) {
console.error('Authentication or connection failed:', error);
}
}

Note: Ensure that authenticationUrl, clientId, and clientSecret are correctly set in the configuration.

Establishing a WebSocket Connection

After authentication (if required), establish a WebSocket connection:

// With explicit token
const token = await client.authenticate();
await client.openConnection(token);

// Or with token provider (browser)
await client.openConnection();
Important: JWT Token Usage

Each JWT token can only be used once to establish a WebSocket connection. If you need to reconnect or establish a new connection, you must obtain a fresh token by calling authenticate() again or invoking your tokenProvider function. Attempting to reuse the same token will result in an authentication error.

Reconnection Example:

// Reconnecting requires a new token
async function reconnect() {
try {
// Get a fresh token
const newToken = await client.authenticate();
// Establish new connection with fresh token
await client.openConnection(newToken);
console.log('Reconnected successfully');
} catch (error) {
console.error('Reconnection failed:', error);
}
}

// Handle disconnection
client.on('close', () => {
console.log('Connection closed, reconnecting...');
reconnect();
});

Configuration Options

const client = new OptaveJavaScriptSDK({
websocketUrl: 'wss://ws-{{tenant}}.oco.optave.{{tld}}',
tokenProvider: async () => { /* ... */ }, // For browsers
authenticationUrl: '...', // For servers
clientId: '...', // For servers
clientSecret: '...', // For servers
connectionTimeoutMs: 30000, // Optional (default: 30s)
requestTimeoutMs: 30000, // Optional (default: 30s)
authTransport: 'subprotocol' // Optional: 'subprotocol' or 'query'
});