Documentation Index
Fetch the complete documentation index at: https://docs.byul.ai/llms.txt
Use this file to discover all available pages before exploring further.
WebSocket Authentication
WebSocket connections require API key authentication for secure access to real-time news streams.
Authentication Method
WebSocket authentication uses your API key provided during the connection handshake.
API Key Setup
-
Get Your API Key
- Login to Byul API Dashboard
- Your API key is displayed on the dashboard
- API keys start with
byul_v2_
-
Connection Authentication
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
Authentication Flow
- Connection Request: Client connects with API key in auth options
- Server Validation: Server validates API key and plan permissions
- Authentication Success: Server emits
auth:success event with user details
- Ready for Subscriptions: Client can now subscribe to news streams
Authentication Success Event
socket.on('auth:success', (data) => {
console.log('Authentication successful');
console.log('Plan:', data.user.plan);
console.log('Email:', data.user.email);
// Now safe to subscribe to news
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
});
Success Response Structure:
{
"message": "WebSocket authentication successful",
"user": {
"email": "user@example.com",
"plan": "pro"
}
}
Error Handling
Authentication Errors
socket.on('news:error', (error) => {
console.error('Authentication failed:', error.message);
switch (error.code) {
case 'INVALID_API_KEY':
console.log('Please check your API key');
break;
case 'PLAN_REQUIRED':
console.log('WebSocket requires Pro or Enterprise plan');
break;
case 'RATE_LIMITED':
console.log('Too many connection attempts. Please wait.');
break;
}
});
Common Error Codes:
INVALID_API_KEY - API key is invalid or malformed
PLAN_REQUIRED - WebSocket access requires Pro/Enterprise plan
RATE_LIMITED - Too many authentication attempts
CONNECTION_LIMIT - Maximum connections exceeded for plan
Security Best Practices
Environment Variables
Never hardcode API keys in your source code. Use environment variables:
// ✅ Good - Use environment variables
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
// ❌ Bad - Hardcoded API key
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
Production Configuration
// config/websocket.js
export const websocketConfig = {
url: process.env.WEBSOCKET_URL || 'wss://api.byul.ai/news-v2',
auth: {
apiKey: process.env.BYUL_API_KEY
},
// Additional security options
transports: ['websocket'], // Disable polling
upgrade: false,
rememberUpgrade: false
};
// .env
REACT_APP_BYUL_API_KEY=byul_api_key
// src/config/websocket.js
export const websocketConfig = {
url: 'wss://api.byul.ai/news-v2',
auth: {
apiKey: process.env.REACT_APP_BYUL_API_KEY
}
};
import os
from dotenv import load_dotenv
load_dotenv()
# config/settings.py
WEBSOCKET_CONFIG = {
'url': 'wss://api.byul.ai/news-v2',
'auth': {
'apiKey': os.getenv('BYUL_API_KEY')
}
}
API Key Protection
Backend Only: Keep API keys on your backend servers. Never expose them to client-side JavaScript in production.
Key Rotation: Regularly rotate your API keys for enhanced security.
Access Control: Restrict API key access to authorized team members only.
Connection Examples
Basic Authentication
import { io } from 'socket.io-client';
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
socket.on('connect', () => {
console.log('Connected to WebSocket');
});
socket.on('auth:success', (data) => {
console.log('Authenticated successfully:', data.user.plan);
});
socket.on('news:error', (error) => {
console.error('Authentication error:', error.message);
});
With Reconnection
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY },
// Reconnection settings
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
});
socket.on('reconnect', (attemptNumber) => {
console.log(`Reconnected after ${attemptNumber} attempts`);
});
socket.on('reconnect_error', (error) => {
console.error('Reconnection failed:', error.message);
});
Python Authentication
import asyncio
import socketio
import os
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('Connected to WebSocket')
@sio.on('auth:success')
async def auth_success(data):
print(f"Authenticated successfully: {data['user']['plan']}")
# Subscribe to news after authentication
await sio.emit('news:subscribe', {
'minImportance': 7,
'startDate': '2024-01-01T00:00:00.000Z'
})
@sio.on('news:error')
async def auth_error(error):
print(f"Authentication error: {error['message']}")
async def main():
await sio.connect(
'wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')}
)
await sio.wait()
asyncio.run(main())
Troubleshooting
Authentication Issues
Invalid API Key Format
Error: API key must start with 'byul_v2_'
- Verify API key format from dashboard
- Check for extra whitespace or characters
Plan Requirements
Error: WebSocket streaming requires Pro or Enterprise plan
Connection Timeout
Error: Authentication timeout
- Check network connectivity
- Verify firewall settings allow WebSocket connections
- Try connecting from a different network
Testing Authentication
Test your authentication setup with a simple connection:
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' },
timeout: 10000
});
socket.on('connect', () => {
console.log('✅ Connection successful');
});
socket.on('auth:success', (data) => {
console.log('✅ Authentication successful');
console.log('Plan:', data.user.plan);
socket.disconnect();
});
socket.on('news:error', (error) => {
console.log('❌ Authentication failed:', error.message);
socket.disconnect();
});
socket.on('connect_error', (error) => {
console.log('❌ Connection failed:', error.message);
});
Next Steps
News Subscription
Subscribe to filtered news streams
Error Handling
Handle connection errors and implement retry logic
Connection Management
Advanced connection configuration and monitoring
Examples
Production-ready implementation examples