Skip to main content
WebSocket integration provides real-time, bidirectional communication between Evolution API and your applications. Perfect for dashboards, live chat interfaces, and real-time monitoring.

Configuration

Configure WebSocket through environment variables:
.env
# Enable WebSocket server
WEBSOCKET_ENABLED=true

# Enable global events (all instances)
WEBSOCKET_GLOBAL_EVENTS=false

# Allowed hosts for connections (comma-separated)
WEBSOCKET_ALLOWED_HOSTS=127.0.0.1,::1,::ffff:127.0.0.1

Host Restrictions

Control which hosts can connect to your WebSocket server:
Default configuration for local development:
.env
WEBSOCKET_ALLOWED_HOSTS=127.0.0.1,::1,::ffff:127.0.0.1

Connection Modes

WebSocket supports two connection modes:
Connect to a specific instance namespace:
const socket = io('http://localhost:8080/my_instance', {
  query: {
    apikey: 'YOUR_API_KEY'
  }
});
Receives events only from that instance.

Authentication

WebSocket connections require authentication via API key:
1

Query Parameter

Pass API key in connection URL:
const socket = io('http://localhost:8080', {
  query: {
    apikey: 'YOUR_API_KEY'
  }
});
2

Header (Alternative)

Or pass as custom header:
const socket = io('http://localhost:8080', {
  extraHeaders: {
    apikey: 'YOUR_API_KEY'
  }
});
3

Validation

Evolution API validates the API key:
  • For instance namespaces: Instance API key
  • For global connection: Global API key
Connections without valid API keys will be rejected with an authentication error.

Connection Examples

const io = require('socket.io-client');

// Connect to instance namespace
const socket = io('http://localhost:8080/my_instance', {
  query: {
    apikey: 'YOUR_API_KEY'
  },
  transports: ['websocket'],
  reconnection: true,
  reconnectionDelay: 1000,
  reconnectionAttempts: 10
});

// Connection events
socket.on('connect', () => {
  console.log('Connected to WebSocket');
  console.log('Socket ID:', socket.id);
});

socket.on('disconnect', (reason) => {
  console.log('Disconnected:', reason);
});

socket.on('connect_error', (error) => {
  console.error('Connection error:', error.message);
});

// Listen for WhatsApp events
socket.on('messages.upsert', (data) => {
  console.log('New message:', data);
});

socket.on('qrcode.updated', (data) => {
  console.log('QR Code updated:', data.data.qrcode);
});

socket.on('connection.update', (data) => {
  console.log('Connection status:', data.data.state);
});

Available Events

You can listen for any WhatsApp event through WebSocket:

Instance Events

  • qrcode.updated - QR code changes
  • connection.update - Connection status changes

Message Events

  • messages.set - Message history loaded
  • messages.upsert - New messages received/sent
  • messages.edited - Messages edited
  • messages.update - Message status updates (read, delivered)
  • messages.delete - Messages deleted
  • send.message - Message sent confirmation
  • send.message.update - Sent message status update

Contact Events

  • contacts.set - Contacts loaded
  • contacts.upsert - Contact added/updated
  • contacts.update - Contact information changed
  • presence.update - Contact online/offline status

Chat Events

  • chats.set - Chats loaded
  • chats.upsert - New chat created
  • chats.update - Chat updated
  • chats.delete - Chat deleted

Group Events

  • groups.upsert - Group created/joined
  • group.update - Group information changed
  • group.participants.update - Participants added/removed

Other Events

  • labels.edit - Label edited
  • labels.association - Label associated with chat
  • call - Incoming call

Per-Instance Configuration

Configure which events are emitted for a specific instance:
curl -X POST https://your-api.com/websocket/set/instance_name \
  -H "apikey: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "websocket": {
      "enabled": true,
      "events": [
        "MESSAGES_UPSERT",
        "MESSAGES_UPDATE",
        "QRCODE_UPDATED",
        "CONNECTION_UPDATE"
      ]
    }
  }'

Event Payload Structure

All WebSocket events have a consistent structure:
{
  "event": "messages.upsert",
  "instance": "my_instance",
  "data": {
    // Event-specific data
  },
  "server_url": "https://your-evolution-api.com",
  "date_time": "2024-03-04T10:30:00.000Z",
  "sender": "5511999999999",
  "apikey": "instance_api_key"
}

Sending Custom Commands

Send custom commands to WhatsApp through WebSocket:
// Send a custom Baileys node/stanza
socket.emit('sendNode', {
  instanceId: 'my_instance',
  stanza: {
    tag: 'iq',
    attrs: { type: 'get', xmlns: 'w:web', to: 'c.us' },
    content: [{ tag: 'status', attrs: {} }]
  }
});
Sending custom nodes requires deep knowledge of WhatsApp’s protocol. Incorrect usage may cause connection issues.

Best Practices

1

Handle Reconnections

Always enable automatic reconnection:
const socket = io(url, {
  reconnection: true,
  reconnectionDelay: 1000,
  reconnectionAttempts: 10
});
2

Use Event Filtering

Configure only needed events to reduce bandwidth:
websocket: {
  events: ['MESSAGES_UPSERT', 'CONNECTION_UPDATE']
}
3

Implement Error Handling

Handle all error events:
socket.on('connect_error', (error) => {
  console.error('Connection failed:', error);
});

socket.on('error', (error) => {
  console.error('Socket error:', error);
});
4

Secure Your Connection

  • Use HTTPS/WSS in production
  • Restrict WEBSOCKET_ALLOWED_HOSTS
  • Never expose API keys in client-side code
5

Monitor Connection State

Track connection status in your UI:
socket.on('connect', () => setStatus('Connected'));
socket.on('disconnect', () => setStatus('Disconnected'));

CORS Configuration

WebSocket respects your CORS settings:
.env
# Allow specific origins
CORS_ORIGIN=https://your-app.com,https://dashboard.your-app.com

# Or allow all origins
CORS_ORIGIN=*
WebSocket CORS is automatically configured based on your CORS_ORIGIN setting.

Troubleshooting

  1. Verify API key is correct
  2. Check that WebSocket is enabled: WEBSOCKET_ENABLED=true
  3. Ensure your IP is in WEBSOCKET_ALLOWED_HOSTS
  4. Check Evolution API logs for authentication errors
  1. Verify instance is connected to WhatsApp
  2. Check that specific events are enabled in instance configuration
  3. Ensure you’re connected to correct namespace
  4. Enable logging to see if events are being emitted
  1. Check network stability
  2. Increase reconnectionDelay in client configuration
  3. Monitor server resources (CPU, memory)
  4. Check for firewall issues blocking WebSocket connections
  1. Verify API key format (no extra spaces)
  2. For instance namespaces, use instance API key
  3. For global events, use global API key
  4. Check that instance exists and is active
  1. Add your domain to CORS_ORIGIN
  2. Restart Evolution API after changing CORS settings
  3. Check browser console for specific CORS error
  4. Ensure protocol matches (http/https)

Build docs developers (and LLMs) love