Node.jsSocket.IOError Fix2026 Updated

Node.js WebSocket Connection Error— Fixed [Complete Guide 2026]

January 20267 min readNode.js · Socket.IO · All OS

⚡ Most Common Fix — Socket.IO CORS

server.js
const { Server } = require('socket.io')

const io = new Server(httpServer, {
  cors: {
    origin: 'http://localhost:3000',
    credentials: true,
  }
})

Diagnose Your WebSocket Error

Browser / Terminal 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 / SymptomCauseFix
CORS policy blockedSocket.IO cors not configuredJump →
Unexpected response code: 400Server not passing httpServer to Socket.IOJump →
Connection refused / ERR_CONNECTIONWrong port or URL on clientJump →
Works locally, fails in productionnginx not forwarding WebSocket upgradeJump →
Disconnects every 60snginx proxy_read_timeout too shortJump →
1

Socket.IO CORS Configuration

CORS policy blocked — most common issue
2 min

Socket.IO requires its own CORS configuration — separate from Express cors middleware.

server.js
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.

2

Correct Socket.IO Server Setup

400 error — Socket.IO not attached to HTTP server
3 min

Socket.IO must be attached to the HTTP server, not the Express app directly. This is a very common mistake.

server.js
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'))
3

Client Connecting to Wrong URL

Connection refused — wrong port or protocol
1 min
Frontend client
import { 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))
4

Handle Disconnects and Auto-Reconnection

Connections dropping — robust client setup
3 min

Server — handle disconnection events

server.js
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

Frontend
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')
})
5

WebSocket Behind nginx (Production)

Works locally but fails in production
5 min

nginx does not forward WebSocket connections by default. Without the Upgrade headers, nginx closes the WebSocket connection as a regular HTTP request.

/etc/nginx/sites-available/myapp
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;
    }
}
terminal
sudo nginx -t          # test config
sudo systemctl reload nginx

proxy_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).

6

Raw ws Library Connection Errors

Using ws package instead of Socket.IO
3 min
terminal
npm install ws
server.js — ws server
const { 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)
Client — native WebSocket API
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)
})
7

Authenticate WebSocket Connections

JWT auth for Socket.IO
3 min
server.js
const 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)
})
Frontend — send token
const socket = io('http://localhost:5000', {
  auth: {
    token: localStorage.getItem('authToken')
  }
})

How to Prevent WebSocket Connection Errors

Frequently Asked Questions

Why is Socket.IO not connecting?+
Most common causes: CORS not configured (add cors option to Socket.IO server), client connecting to wrong URL or port, nginx not configured for WebSocket upgrade, or the HTTP server is not passed to Socket.IO correctly.
How do I fix WebSocket CORS error in Node.js?+
In Socket.IO: const io = new Server(httpServer, { cors: { origin: 'http://localhost:3000', credentials: true } }). This is separate from Express cors — Socket.IO has its own CORS config.
Socket.IO works locally but not in production?+
nginx is likely blocking the WebSocket upgrade. Add these lines to your nginx location block: proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'. Without these, nginx closes WebSocket connections.
What is the difference between Socket.IO and ws?+
ws is a lightweight WebSocket library — pure WebSocket protocol. Socket.IO uses WebSocket underneath but adds rooms, namespaces, auto-reconnection, fallback to long-polling, and a custom event system. Use ws for simple cases, Socket.IO for feature-rich real-time apps.
How do I handle WebSocket disconnects gracefully?+
On the server: io.on('connection', socket => { socket.on('disconnect', reason => { console.log('Disconnected:', reason) }) }). On the client: Socket.IO auto-reconnects by default. Configure: { reconnectionAttempts: 5, reconnectionDelay: 1000 }
WebSocket connection closes immediately — why?+
Common causes: server-side error during connection handler, authentication failure, CORS rejection, or an exception in the connection event listener crashing the socket. Add error event handler: socket.on('error', console.error) and check server logs.

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