Skip to main content

Overview

NATS Server provides native WebSocket connectivity, enabling web browsers and other WebSocket clients to communicate using the NATS protocol. This makes it possible to build real-time web applications with direct NATS messaging from the browser.
WebSocket support is built directly into NATS Server with no additional proxy or gateway required.

Why WebSocket?

WebSocket connectivity unlocks NATS for web applications:
  • Browser Support: Native NATS messaging directly from JavaScript
  • Real-Time Web Apps: Build interactive dashboards, chat, notifications
  • No HTTP Polling: Persistent bidirectional connection
  • Single Port: WebSocket and HTTP monitoring can share a port
  • TLS Support: Secure WebSocket (WSS) with TLS certificates
  • Per-Message Compression: Optional compression for bandwidth reduction

WebSocket Protocol

NATS implements the RFC 6455 WebSocket Protocol with extensions:
  • Binary and Text Frames: Support for both message types
  • Compression: Optional per-message deflate compression (RFC 7692)
  • Masking: Configurable frame masking for clients
  • Control Frames: PING/PONG for keepalive, CLOSE for clean shutdown

Frame Types

Implemented WebSocket opcodes (websocket.go:41-49):
Frame Types

WebSocket Extensions

Per-Message Compression (websocket.go:89-93):
Compression is negotiated during the WebSocket handshake and applied per-frame.

Configuration

Basic WebSocket Setup

Configure WebSocket by specifying a port:
websocket.conf
Clients connect to: ws://localhost:8080

WebSocket with TLS

Secure WebSocket (WSS) requires TLS configuration:
websocket-tls.conf
Clients connect to: wss://yourserver.com
Always use WSS (TLS) in production. Unencrypted WebSocket connections expose credentials and message content.

Shared Port with HTTP Monitoring

WebSocket can share a port with HTTP monitoring:
shared-port.conf
The server automatically detects WebSocket upgrade requests on the HTTP port.

Advanced Configuration

websocket-advanced.conf
int
required
WebSocket listener port
string
default:"0.0.0.0"
Listen address for WebSocket connections
bool
default:"false"
Enable per-message deflate compression
bool
default:"false"
Require connections from same origin as server
array
List of allowed origins for CORS
duration
default:"2s"
Maximum time to complete WebSocket handshake
bool
default:"false"
Disable masking for server-to-client frames (performance optimization)

Browser Clients

JavaScript/TypeScript

Connect from the browser using the NATS WebSocket client:
Browser Example

React Application

React Hook

Web Client Support

Authentication

WebSocket clients support all NATS authentication methods:
Authentication
NATS supports passing authentication via cookies (websocket.go:119-123):
Cookie Auth

Compression

Enable compression for bandwidth-constrained clients:
Compression
Compression is applied when message size exceeds threshold (websocket.go:62).

MQTT over WebSocket

MQTT clients can connect via WebSocket using the /mqtt path:
MQTT WebSocket
See MQTT for more details on MQTT support (mqtt.go:191).

Implementation Details

WebSocket Handshake

The server performs standard WebSocket upgrade (websocket.go:102-103):
  1. Client sends HTTP Upgrade request with Sec-WebSocket-Key
  2. Server validates and computes accept hash using GUID
  3. Server responds with 101 Switching Protocols
  4. Connection upgraded to WebSocket protocol

Frame Processing

WebSocket frames are processed efficiently (websocket.go:125-193):
  • Masking: Client-to-server frames must be masked per RFC 6455
  • Fragmentation: Large messages can be fragmented across frames
  • Control Frames: PING/PONG handled automatically
  • Browser Optimization: Frame size limited to 4KB for better browser performance (websocket.go:61)

Connection Detection

The server detects WebSocket clients via the ws field (websocket.go:197-199):
Client Detection

Performance Optimization

Disable Masking

Use no_masking: true to skip server-to-client masking for better performance (websocket.go:85-86).

Compression Threshold

Compression only applied for messages larger than 64 bytes (websocket.go:62).

Frame Size

Server uses 4KB frames for optimal browser performance (websocket.go:61).

Connection Pooling

Reuse WebSocket connections for multiple subscriptions to reduce overhead.

Security

TLS Best Practices

1

Always Use WSS in Production

Unencrypted WebSocket exposes all traffic including credentials.
2

Verify Certificates

Set verify: true in TLS configuration to validate client certificates.
3

Restrict Origins

Configure allowed_origins to prevent unauthorized domains from connecting.
4

Use Strong Authentication

Prefer JWT/NKey authentication over username/password for web clients.

Origin Restrictions

Origin Control

X-Forwarded-For

The server respects X-Forwarded-For headers for client IP tracking (websocket.go:87):
Useful when behind a reverse proxy or load balancer.

Monitoring

Monitor WebSocket connections via /connz:
WebSocket Monitoring
Check WebSocket configuration in /varz:
Server Info

Use Cases

Real-Time Dashboard

Dashboard Example

Chat Application

Chat Example

Live Notifications

Notifications

Troubleshooting

Check that WebSocket port is configured and server is listening:
Ensure client origin is in allowed_origins or disable origin checking in development.
Verify certificate paths and ensure certificates are valid. Check server logs for TLS errors.
Both client and server must support and negotiate permessage-deflate extension.

Next Steps

Client SDKs

Explore NATS WebSocket client libraries

Security

Configure authentication and TLS

MQTT

MQTT clients can also use WebSocket

Monitoring

Monitor WebSocket connections