All posts

How to Fix Websocket Connection Failed in Vue.js

Fix Websocket Connection Failed in your Vue.js app. Understand the root cause and apply the right solution.

WebSocket Connection Failed in Vue.js

Vue.js WebSocket failures occur when the client can't establish or maintain a connection — often due to URL misconfiguration, CORS issues, or server-side problems.

Why It Fails

  • Hardcoded ws://localhost URLs reaching production
  • Mixed content (HTTP page trying wss:// or vice versa)
  • Vue devtools WebSocket conflicting with app WebSocket
  • Server closing connections due to missing heartbeats

The Fix

Build a resilient WebSocket composable:

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const messages = ref([]);
const connected = ref(false);
let ws = null;
let reconnectTimer = null;

function connect() {
  const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  const url = `${protocol}://${location.host}/api/ws`;

  ws = new WebSocket(url);
  ws.onopen = () => { connected.value = true; };
  ws.onclose = (e) => {
    connected.value = false;
    if (e.code !== 1000) {
      reconnectTimer = setTimeout(connect, 3000);
    }
  };
  ws.onmessage = (e) => {
    messages.value.push(JSON.parse(e.data));
  };
}

onMounted(connect);
onUnmounted(() => {
  clearTimeout(reconnectTimer);
  ws?.close(1000, 'Component unmounted');
});
</script>

Always derive the WebSocket URL from location rather than hardcoding it, and implement reconnection logic for production resilience.

Bugsly for Vue

Bugsly logs WebSocket lifecycle events — connection, disconnection, and errors — with close codes and timing, helping you identify whether failures are transient network issues or persistent server 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