All posts

How to Fix Websocket Connection Failed in Next.js

A practical guide to resolving Websocket Connection Failed in Next.js, with real code examples and debugging tips.

WebSocket Connection Failed in Next.js

WebSocket connection failures in Next.js usually stem from the development server's HMR (Hot Module Replacement) WebSocket, proxy configuration issues, or production deployment misconfiguration.

Common Causes

  • Reverse proxy not configured for WebSocket upgrade
  • CORS blocking WebSocket connections
  • SSL/TLS termination not forwarding wss:// connections
  • Next.js dev server HMR WebSocket blocked by firewall

The Fix

Configure your WebSocket connection and proxy:

// lib/websocket.js
export function createWebSocket(path) {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const url = `${protocol}//${window.location.host}${path}`;

  const ws = new WebSocket(url);

  ws.onopen = () => console.log('Connected');
  ws.onclose = (e) => {
    console.log(`Closed: ${e.code} ${e.reason}`);
    if (e.code !== 1000) {
      // Reconnect on abnormal closure
      setTimeout(() => createWebSocket(path), 3000);
    }
  };
  ws.onerror = (e) => console.error('WebSocket error:', e);

  return ws;
}

For production with nginx:

location /ws {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Production Hardening

Beyond the immediate fix, consider adding circuit breakers and graceful degradation for this failure mode. Log structured error data so your observability stack can correlate this error with upstream causes. Set up dashboards to track error rates over time and catch regressions early.

Bugsly for Next.js

Bugsly tracks WebSocket connection failures with the URL, close code, and network context, helping you distinguish between server-side issues and client network problems.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free