How to Fix WebSocket Connection Closed Unexpectedly Error
In this tutorial, you'll learn about How to Fix WebSocket Connection Closed Unexpectedly Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your WebSocket client receives:
WebSocket connection to 'wss://example.com/socket' failed: Connection closed unexpectedly
Or:
WebSocket onclose event: code 1006, reason: Abnormal Closure
The WebSocket connection was terminated unexpectedly. This can happen due to proxy timeouts, network issues, or server-side disconnections.
Quick Fix
1. Implement automatic reconnection
Add reconnection logic to handle unexpected closures:
// WebSocket with auto-reconnect
class ReconnectingWebSocket {
constructor(url, options = {}) {
this.url = url
this.reconnectInterval = options.reconnectInterval || 3000
this.maxRetries = options.maxRetries || 10
this.retries = 0
this.connect()
}
connect() {
this.ws = new WebSocket(this.url)
this.ws.onopen = () => {
this.retries = 0
console.log('WebSocket connected')
}
this.ws.onclose = (event) => {
if (this.retries < this.maxRetries) {
setTimeout(() => {
this.retries++
this.connect()
}, this.reconnectInterval * Math.pow(1.5, this.retries))
}
}
this.ws.onerror = (error) => {
console.error('WebSocket error:', error)
}
}
send(data) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data)
}
}
}
2. Fix proxy timeouts
Proxies and load balancers close idle WebSocket connections:
# Nginx โ increase proxy timeout for WebSocket
location /socket/ {
proxy_pass http://backend:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_read_timeout 86400s; # 24 hours for <a href="/apis/websocket/">Websocket</a>
proxy_send_timeout 86400s;
}
3. Implement heartbeat/ping-pong
Keep the connection alive with periodic pings:
// Server-side heartbeat (Node.js with ws)
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })
wss.on('connection', (ws) => {
ws.isAlive = true
ws.on('pong', () => { ws.isAlive = true })
const interval = setInterval(() => {
if (!ws.isAlive) {
ws.terminate()
return
}
ws.isAlive = false
ws.ping()
}, 30000)
ws.on('close', () => clearInterval(interval))
})
4. Use WSS (secure WebSocket) in production
Always use wss:// instead of ws:// in production to prevent middleboxes from closing the connection:
// Wrong โ unencrypted WebSocket
const ws = new WebSocket('ws://api.example.com/socket')
// Right โ encrypted WebSocket
const ws = new <a href="/apis/websocket/">Websocket</a>('wss://api.example.com/socket')
5. Check the WebSocket close code
ws.onclose = (event) => {
console.log(`Close code: ${event.code}, reason: ${event.reason}`)
// Common codes:
// 1000: Normal closure
// 1001: Going away (server restart)
// 1006: Abnormal closure (no close frame)
// 1009: Message too big
// 1011: Unexpected server error
}
Prevention
- Always implement reconnection with exponential backoff.
- Use heartbeats (ping/pong) to keep idle connections alive.
- Configure proxy timeouts to allow long-lived WebSocket connections.
- Use WSS to prevent interference from network intermediaries.
- Monitor WebSocket disconnect rates for early problem detection.
Common Mistakes with WebSocket close
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro