How to Sync Two Front‑End Apps in Real Time with WebSocket and Socket.io

Learn how to achieve real‑time data synchronization between separate front‑end applications by leveraging WebSocket and Socket.io, covering the protocol basics, connection setup, event handling, server implementation, alternative communication methods, and practical code examples for both client and server sides.

WeDoctor Frontend Technology
WeDoctor Frontend Technology
WeDoctor Frontend Technology
How to Sync Two Front‑End Apps in Real Time with WebSocket and Socket.io

1. Introduction

In a visual drag‑and‑drop H5 page builder project, the system is split into a backend configuration app and a frontend rendering app. The requirement is that when a page property (e.g., background color) is changed in the backend, the frontend reflects the change instantly without a page refresh.

The core challenge is keeping the two front‑end applications synchronized in real time, i.e., establishing communication between them.

2. Why Not iframe + postMessage?

Embedding one app inside the other via iframe and using window.postMessage() works only when the apps share a nesting relationship and introduces compatibility issues. For independent apps, a more robust solution is needed.

3. What is WebSocket?

WebSocket is a network communication protocol that operates at the application layer alongside HTTP. It solves HTTP's limitation of server‑initiated push by allowing bidirectional, persistent connections after a single handshake.

This makes it ideal for scenarios requiring continuous data exchange, such as online games or real‑time feeds.

Compared with HTTP polling (including long polling), WebSocket avoids the heavy server load caused by repeatedly handling client requests.

4. Using WebSocket

To open a WebSocket connection, use the ws (or secure wss) protocol:

let socket = new WebSocket("ws://javascript.info");

The socket provides four main events:

open — connection established message — data received error — error occurred close — connection closed

Sending data is done with socket.send(data). A complete example:

let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");

socket.onopen = function(e) {
  alert("[open] Connection established");
  alert("Sending to server");
  socket.send("My name is John");
};

socket.onmessage = function(event) {
  alert(`[message] Data received from server: ${event.data}`);
};

socket.onclose = function(event) {
  if (event.wasClean) {
    alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    // e.g. server process killed or network interruption
    alert('[close] Connection died');
  }
};

socket.onerror = function(error) {
  alert(`[error] ${error.message}`);
};

5. Front‑end ↔ Back‑end Communication

5.1 Application Role Model

One independent process acts as the server, while the front‑end applications act as clients. All clients connect to this socket server to exchange data.

5.2 Starting a Socket Process

The client needs a URL that starts with ws:// or wss://. The server side can be built with socket.io, which abstracts WebSocket and fallback polling mechanisms.

5.3 Server Code (socket.io)

// ws/index.js
const server = require('http').createServer();
const io = require('socket.io')(server);

io.on('connect', socket => {
  console.log('Server connection established');
  socket.on('disconnect', () => {
    console.log('Server detected disconnection');
  });
  socket.on('transportData', data => {
    console.log('Server received data', data);
    io.sockets.emit('updateData', data);
    console.log('Server emitted updateData');
  });
});

server.listen(8020, () => {
  console.log('==== socket server is running at port 8020 ====');
});

5.4 Client Code (Vue + socket.io-client)

// client1.vue
<script>
import io from 'socket.io-client';
export default {
  mounted() {
    const socket = io('http://127.0.0.1:8020');
    socket.on('connect', () => {
      console.log('client1 connected');
      socket.emit('transportData', { name: 'xuhx' });
    });
    socket.on('updateData', data => {
      console.log('client1 received update', data);
    });
  }
};
</script>
// client2.vue
<script>
import io from 'socket.io-client';
export default {
  mounted() {
    const socket = io('http://127.0.0.1:8020');
    socket.on('connect', () => {
      console.log('client2 connected');
    });
    socket.on('updateData', data => {
      console.log('client2 received update', data);
    });
  }
};
</script>

When the server emits updateData, both clients receive the event and can update their UI accordingly.

6. Alternative Communication Methods

6.1 Cookie

If two applications share the same root domain, a cookie with a common Domain attribute can be used to share small pieces of state.

6.2 iframe + window.postMessage()

For different domains, an invisible iframe can act as a bridge, allowing the parent and child pages to exchange messages via window.postMessage().

6.3 Server‑Sent Events (EventSource)

EventSource provides a unidirectional, persistent connection for the server to push text data. It is simpler than WebSocket but lacks bidirectional communication and binary support.

WebSocket

EventSource

Bidirectional: both client and server can exchange messages

Unidirectional: only server can send messages

Binary and text data

Text data only

WebSocket protocol

Standard HTTP protocol

6.4 Micro‑frontend

Micro‑frontend architectures also address inter‑application communication, though they introduce their own complexities.

7. Conclusion

Real‑time data synchronization between two front‑end applications can be achieved efficiently with WebSocket (or socket.io). By running a dedicated socket server and having each client emit and listen to custom events, developers can keep multiple independent apps in sync. The article also outlines alternative techniques for various scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendWebSocketReal-time communicationSocket.IO
WeDoctor Frontend Technology
Written by

WeDoctor Frontend Technology

Official WeDoctor Group frontend public account, sharing original tech articles, events, job postings, and occasional daily updates from our tech team.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.