WebSocket Connection Failed
The WebSocket connection could not be established or was closed unexpectedly.
Explanation
WebSocket Connection Failed occurs when the client cannot establish or maintain a WebSocket connection to the server. This can happen during the initial handshake (HTTP upgrade fails), during the connection (server closes it), or during data transfer. Common causes include server not supporting WebSocket upgrade, proxy/load balancer issues, CORS restrictions, invalid WebSocket URL, authentication failures, and server-side connection limits being reached.
Common Causes
- Server doesn't support WebSocket upgrade
- Invalid WebSocket URL protocol
- Proxy/load balancer blocking upgrade
- CORS restrictions
- Authentication failure
Solution
Verify the WebSocket URL is correct (ws:// or wss:// protocol). Check that the server supports WebSocket connections and is running. Ensure proxies and load balancers are configured to forward WebSocket upgrade requests. Add event handlers for error and close events to handle failures gracefully. Implement reconnection logic with exponential backoff. Check server logs for connection rejection reasons. Verify authentication if the WebSocket endpoint requires it.
Code Example
// WebSocket connection with error handling
const ws = new WebSocket('ws://localhost:3000');
ws.on('open', () => {
console.log('Connected!');
ws.send('Hello');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error.message);
});
ws.on('close', (code, reason) => {
console.log(`Closed: ${code} ${reason}`);
});
// Reconnection with backoff
function connectWithRetry(url, retries = 5, delay = 1000) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url);
ws.on('open', () => resolve(ws));
ws.on('error', (err) => {
if (retries > 0) {
setTimeout(() => {
connectWithRetry(url, retries - 1, delay * 2)
.then(resolve).catch(reject);
}, delay);
} else {
reject(err);
}
});
});
}
connectWithRetry('ws://localhost:3000')
.then(ws => console.log('Connected'))
.catch(err => console.error('Failed:', err));
Error Information
Language
javascript
Difficulty
Intermediate
Views
15
Related Errors
Frontend
CORS Error
The browser blocks cross-origin requests due to same-origin policy restrictions.
Frontend
Content Security Policy Violation
The browser blocked a resource because it violated the Content Security Policy.
General
Circular Dependency Detected
Module A depends on B which depends on A, creating an unresolvable import cycle.
Frontend
Invalid DOM Property
The code uses an incorrect HTML attribute or React-specific prop on a DOM element.