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):Configuration
Basic WebSocket Setup
Configure WebSocket by specifying a port:websocket.conf
ws://localhost:8080
WebSocket with TLS
Secure WebSocket (WSS) requires TLS configuration:websocket-tls.conf
wss://yourserver.com
Shared Port with HTTP Monitoring
WebSocket can share a port with HTTP monitoring:shared-port.conf
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
Cookie-Based Authentication
NATS supports passing authentication via cookies (websocket.go:119-123):Cookie Auth
Compression
Enable compression for bandwidth-constrained clients:Compression
MQTT over WebSocket
MQTT clients can connect via WebSocket using the/mqtt path:
MQTT WebSocket
Implementation Details
WebSocket Handshake
The server performs standard WebSocket upgrade (websocket.go:102-103):- Client sends HTTP Upgrade request with
Sec-WebSocket-Key - Server validates and computes accept hash using GUID
- Server responds with 101 Switching Protocols
- 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 thews 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 respectsX-Forwarded-For headers for client IP tracking (websocket.go:87):
Monitoring
Monitor WebSocket connections via/connz:
WebSocket Monitoring
/varz:
Server Info
Use Cases
Real-Time Dashboard
Dashboard Example
Chat Application
Chat Example
Live Notifications
Notifications
Troubleshooting
Connection Refused
Connection Refused
Check that WebSocket port is configured and server is listening:
Origin Blocked
Origin Blocked
Ensure client origin is in
allowed_origins or disable origin checking in development.TLS Handshake Failed
TLS Handshake Failed
Verify certificate paths and ensure certificates are valid. Check server logs for TLS errors.
Compression Not Working
Compression Not Working
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