Node.js WebSocket Connection Error— Fixed [Complete Guide 2026]
⚡ Most Common Fix — Socket.IO CORS
const { Server } = require('socket.io')
const io = new Server(httpServer, {
cors: {
origin: 'http://localhost:3000',
credentials: true,
}
})Diagnose Your WebSocket Error
WebSocket connection to 'ws://localhost:5000/socket.io/?...' failed:
Error during WebSocket handshake: Unexpected response code: 400
# or:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?...'
from origin 'http://localhost:3000' has been blocked by CORS policy| Error / Symptom | Cause | Fix |
|---|---|---|
| CORS policy blocked | Socket.IO cors not configured | Jump → |
| Unexpected response code: 400 | Server not passing httpServer to Socket.IO | Jump → |
| Connection refused / ERR_CONNECTION | Wrong port or URL on client | Jump → |
| Works locally, fails in production | nginx not forwarding WebSocket upgrade | Jump → |
| Disconnects every 60s | nginx proxy_read_timeout too short | Jump → |
Socket.IO CORS Configuration
CORS policy blocked — most common issueSocket.IO requires its own CORS configuration — separate from Express cors middleware.
const express = require('express')
const http = require('http')
const { Server } = require('socket.io')
const cors = require('cors')
const app = express()
const server = http.createServer(app)
// Express cors (for REST routes)
app.use(cors({ origin: 'http://localhost:3000' }))
// Socket.IO cors (separate config!)
const io = new Server(server, {
cors: {
origin: ['http://localhost:3000', 'https://yourapp.com'],
methods: ['GET', 'POST'],
credentials: true,
}
})
io.on('connection', (socket) => {
console.log('Client connected:', socket.id)
socket.on('disconnect', () => console.log('Client disconnected'))
})
server.listen(5000)Using origin: '*' with credentials: true is invalid. Specify exact origins when using credentials.
Correct Socket.IO Server Setup
400 error — Socket.IO not attached to HTTP serverSocket.IO must be attached to the HTTP server, not the Express app directly. This is a very common mistake.
const express = require('express')
const http = require('http')
const { Server } = require('socket.io')
const app = express()
// ❌ WRONG — passing Express app to Socket.IO
// const io = new Server(app, { ... }) // 400 errors!
// ✅ CORRECT — create HTTP server from Express, pass that
const server = http.createServer(app)
const io = new Server(server, {
cors: { origin: 'http://localhost:3000' }
})
io.on('connection', (socket) => {
console.log('Connected:', socket.id)
// Emit to this client
socket.emit('welcome', { message: 'Connected!' })
// Receive from client
socket.on('message', (data) => {
console.log('Received:', data)
// Broadcast to all clients
io.emit('message', data)
})
})
// Listen on the HTTP server — not app.listen()
server.listen(5000, () => console.log('Server on port 5000'))Client Connecting to Wrong URL
Connection refused — wrong port or protocolimport { io } from 'socket.io-client'
// ❌ WRONG — common URL mistakes
const socket = io('http://localhost:3000') // wrong port (backend is on 5000)
const socket = io('ws://localhost:5000') // Socket.IO uses http/https, not ws://
const socket = io() // no URL — may resolve wrong
// ✅ CORRECT — explicit URL matching backend port
const socket = io('http://localhost:5000')
// Production — use environment variable
const socket = io(process.env.NEXT_PUBLIC_SOCKET_URL || 'http://localhost:5000')
// Debug — log connection status
socket.on('connect', () => console.log('Connected:', socket.id))
socket.on('connect_error', (err) => console.error('Connection error:', err.message))Handle Disconnects and Auto-Reconnection
Connections dropping — robust client setupServer — handle disconnection events
io.on('connection', (socket) => {
const { userId } = socket.handshake.auth
// Track user sessions
userSockets.set(userId, socket.id)
socket.on('disconnect', (reason) => {
console.log(`User ${userId} disconnected: ${reason}`)
userSockets.delete(userId)
// Notify others
io.emit('user:offline', { userId })
})
socket.on('error', (err) => {
console.error('Socket error:', err)
})
})Client — robust reconnection config
const socket = io('http://localhost:5000', {
reconnection: true, // auto-reconnect (default: true)
reconnectionAttempts: 10, // try 10 times before giving up
reconnectionDelay: 1000, // start with 1s delay
reconnectionDelayMax: 5000, // max 5s between attempts
auth: { token: localStorage.getItem('token') }, // send auth token
})
socket.on('connect', () => {
console.log('Connected')
// Re-join rooms after reconnection
socket.emit('join:room', { roomId: currentRoom })
})
socket.on('disconnect', (reason) => {
console.log('Disconnected:', reason)
if (reason === 'io server disconnect') {
// Server intentionally disconnected — reconnect manually
socket.connect()
}
})
socket.on('reconnect', (attempt) => {
console.log('Reconnected after', attempt, 'attempts')
})WebSocket Behind nginx (Production)
Works locally but fails in productionnginx does not forward WebSocket connections by default. Without the Upgrade headers, nginx closes the WebSocket connection as a regular HTTP request.
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
# ← These two lines are REQUIRED for WebSockets
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Prevent nginx from closing idle WebSocket connections
proxy_read_timeout 86400;
proxy_send_timeout 86400;
}
}sudo nginx -t # test config
sudo systemctl reload nginxproxy_read_timeout 86400 sets the timeout to 24 hours. Without this, nginx closes WebSocket connections that are idle for more than 60 seconds (the default).
Raw ws Library Connection Errors
Using ws package instead of Socket.IOnpm install wsconst { WebSocketServer } = require('ws')
const http = require('http')
const server = http.createServer()
const wss = new WebSocketServer({ server })
wss.on('connection', (ws, req) => {
const origin = req.headers.origin
console.log('Connection from:', origin)
ws.on('message', (data) => {
console.log('Received:', data.toString())
// Echo back
ws.send(`Echo: ${data}`)
})
ws.on('error', (err) => console.error('WebSocket error:', err))
ws.on('close', (code, reason) => {
console.log('Closed:', code, reason.toString())
})
ws.send('Welcome!')
})
server.listen(5000)const ws = new WebSocket('ws://localhost:5000')
ws.addEventListener('open', () => {
console.log('Connected')
ws.send('Hello server!')
})
ws.addEventListener('message', (event) => {
console.log('Received:', event.data)
})
ws.addEventListener('error', (error) => {
console.error('WebSocket error:', error)
})
ws.addEventListener('close', (event) => {
console.log('Disconnected:', event.code, event.reason)
})Authenticate WebSocket Connections
JWT auth for Socket.IOconst jwt = require('jsonwebtoken')
// Middleware runs before connection event
io.use((socket, next) => {
const token = socket.handshake.auth.token
if (!token) {
return next(new Error('Authentication required'))
}
try {
const payload = jwt.verify(token, process.env.JWT_SECRET)
socket.userId = payload.userId // attach to socket
next()
} catch (err) {
next(new Error('Invalid token'))
}
})
io.on('connection', (socket) => {
console.log('Authenticated user:', socket.userId)
})const socket = io('http://localhost:5000', {
auth: {
token: localStorage.getItem('authToken')
}
})How to Prevent WebSocket Connection Errors
- Always pass the HTTP server to Socket.IO — not the Express app
- Configure Socket.IO cors separately from Express cors
- Add proxy_set_header Upgrade and Connection 'upgrade' to nginx config
- Set proxy_read_timeout 86400 in nginx to prevent idle disconnects
- Implement reconnection handling on the client
- Add authentication middleware to Socket.IO before the connection event
- Log socket.on('connect_error') on client for immediate feedback
Frequently Asked Questions
Why is Socket.IO not connecting?+−
How do I fix WebSocket CORS error in Node.js?+−
Socket.IO works locally but not in production?+−
What is the difference between Socket.IO and ws?+−
How do I handle WebSocket disconnects gracefully?+−
WebSocket connection closes immediately — why?+−
Need Expert Help?
We Build Real-Time Node.js Applications
Softplix builds real-time applications with Socket.IO and WebSockets. Need help with a chat app, live dashboard, or notification system? We can help.
Talk to an Engineer