Modern Data and event sharing

TechnologyDescriptionUse Cases
WebSocketA protocol providing full-duplex communication channels over a single TCP connection, enabling bidirectional real-time data transfer between client and server.Real-time applications like chat apps, online gaming, collaborative editing, live sports updates, or stock trading platforms where low-latency two-way interaction is needed.
Server-Sent Events (SSE)A standard allowing servers to push updates to the client over a single, long-lived HTTP connection, supporting unidirectional streaming from server to client.Scenarios requiring server-initiated updates like live news feeds, social media notifications, real-time monitoring dashboards, or progress indicators for long-running tasks.
Web WorkersJavaScript scripts that run in background threads separate from the main browser thread, allowing concurrent execution without blocking the UI.Heavy computations such as data processing, image manipulation, complex calculations, or parsing large files in web apps to keep the interface responsive.
Service WorkersScripts that run in the background, acting as a proxy between the web app, browser, and network, enabling features like offline access and caching.Progressive Web Apps (PWAs) for offline functionality, push notifications, background syncing, or intercepting network requests to improve performance and reliability.
Shared WorkersSimilar to Web Workers but can be shared across multiple browser contexts (e.g., tabs or windows) of the same origin, allowing inter-tab communication.Applications needing shared state or communication between multiple instances, like coordinating data across open tabs in a web app or multiplayer games.
Broadcast Channel APIAn API for broadcasting messages between different browsing contexts (tabs, iframes, workers) on the same origin without needing a central hub.Syncing state across multiple tabs, such as updating user preferences or session data in real-time across open windows of the same site.
Long PollingA technique where the client sends a request to the server and keeps it open until new data is available, then responds and repeats, simulating real-time updates.Legacy real-time communication in environments where WebSockets or SSE aren’t supported, like older browsers or simple notification systems.
WebRTCA framework for real-time communication directly between browsers, supporting video, audio, and data channels without intermediaries.Video conferencing, peer-to-peer file sharing, live streaming, or collaborative tools requiring direct browser-to-browser connections.
Web Push APIAn API used with Service Workers to receive and display push notifications from a server, even when the web app is not open.Sending timely updates like news alerts, email notifications, or reminders in web apps to re-engage users.
WebTransportA modern API providing low-level access to bidirectional, multiplexed transport over HTTP/3 or other protocols, for efficient data streaming.High-performance applications needing reliable, ordered delivery or raw datagrams, such as gaming, media streaming, or large file transfers.
Background Sync APIAn extension for Service Workers allowing deferred actions to run in the background when network connectivity is restored.Ensuring data submission or updates in PWAs during intermittent connectivity, like syncing form data or emails offline.

WebSocket

WebSockets provide a persistent, full-duplex communication channel over a single TCP connection, allowing real-time bidirectional data exchange between a client (typically a browser) and a server.

Unlike traditional HTTP requests, which are stateless and require a new connection for each interaction, WebSockets maintain an open connection, enabling low-latency updates without the overhead of repeated handshakes.

How It Works

The process starts with an HTTP upgrade request from the client, including headers like Upgrade: websocket, Sec-WebSocket-Key, and Sec-WebSocket-Version. The server responds with a 101 Switching Protocols status and a Sec-WebSocket-Accept header if it accepts the upgrade.

Once established, data is sent in frames, supporting text (UTF-8) or binary formats. The connection stays open until explicitly closed by either party or due to an error. Events like open, message, close, and error handle the lifecycle. For advanced use, the non-standard WebSocketStream API offers promise-based handling with backpressure to manage data flow and prevent buffering issues.

developer.mozilla.org

Key Features

  • Full-duplex communication for simultaneous sending and receiving.
  • Low latency due to persistent connections.
  • Support for subprotocols (e.g., for custom message formats).
  • Automatic reconnection handling in some libraries.
  • Backpressure management in experimental APIs like WebSocketStream.
  • Broad browser support, but closing connections is recommended to allow browser caching (bfcache).

Use Cases

WebSockets are ideal for applications needing instant updates, such as live chat systems (e.g., Slack), online multiplayer games (e.g., real-time player movements in a browser-based game), collaborative editing tools (e.g., Google Docs), stock trading platforms (e.g., live price feeds), or IoT dashboards (e.g., real-time sensor data).

They shine in scenarios where polling would be inefficient, but for unidirectional server pushes, alternatives like SSE might suffice.

Code Examples

Client-side (JavaScript in Browser):

javascript

const socket = new WebSocket('wss://example.com/chat');

socket.onopen = () => {
  console.log('Connection opened');
  socket.send('Hello, server!');
};

socket.onmessage = (event) => {
  console.log('Received:', event.data);
};

socket.onclose = (event) => {
  console.log('Connection closed', event.reason);
};

socket.onerror = (error) => {
  console.error('Error:', error);
};

// To close: socket.close();

Server-side (Node.js with ‘ws’ library):

javascript

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.send('Welcome!');

  ws.on('message', (message) => {
    console.log('Received:', message);
    ws.send(`Echo: ${message}`);
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

This setup creates a simple echo server for chat-like interactions.

Server-Sent Events (SSE)

Server-Sent Events (SSE) allow a server to push updates to a client over a single, persistent HTTP connection, enabling unidirectional real-time streaming from server to browser.

developer.mozilla.org It’s simpler than WebSockets for one-way communication and uses standard HTTP.

How It Works

The client initiates the connection using the EventSource API, specifying a URL that returns text/event-stream content-type. The server keeps the connection open, sending events as plain text lines prefixed with fields like data:, event:, id:, or retry:. Events are delimited by double newlines.

The browser automatically reconnects on drops, with customizable retry intervals. Data is UTF-8 encoded, and comments (starting with : ) can act as keep-alives to prevent timeouts.

Key Features

  • Unidirectional (server to client only).
  • Automatic reconnection with last-event-ID tracking.
  • Support for custom event types.
  • CORS compatibility with proper headers.
  • No client-to-server data sending on the same channel.
  • Works over HTTP/2 for multiplexing.

Use Cases

SSE is used for server-initiated updates like live news tickers (e.g., CNN real-time headlines), social media notifications (e.g., Twitter updates), monitoring dashboards (e.g., server logs or metrics), progress bars for long tasks (e.g., file uploads), or stock price feeds.

It’s not for bidirectional needs, where WebSockets are better.

Code Examples

Client-side (JavaScript):

javascript

const eventSource = new EventSource('/events');

eventSource.onmessage = (event) => {
  console.log('Message:', event.data);
  // Update UI, e.g., append to a list
};

eventSource.addEventListener('ping', (event) => {
  const data = JSON.parse(event.data);
  console.log('Ping:', data.time);
});

eventSource.onerror = (error) => {
  console.error('Error:', error);
};

// Close: eventSource.close();

Server-side (PHP):

php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (true) {
  if (connection_aborted()) break;

  $data = json_encode(['time' => date('c')]);
  echo "event: ping\n";
  echo "data: $data\n\n";
  flush();

  sleep(1);
}

This sends periodic pings.

Web Workers

Web Workers run JavaScript in background threads, separate from the main UI thread, to perform heavy computations without freezing the interface.

They enable concurrency in single-threaded JavaScript environments.

How It Works

A worker is created from a separate JS file using new Worker(‘worker.js’). Communication uses postMessage() to send data (copied, not shared) and onmessage to receive it.

Workers can’t access the DOM or window object but can use APIs like fetch() or XMLHttpRequest. They run in a WorkerGlobalScope and can spawn sub-workers.

Key Features

  • Non-blocking UI during intensive tasks.
  • Message-based communication.
  • Restricted access (no DOM manipulation).
  • Network requests support.
  • Types: Dedicated (single script), Shared (multi-context), Service (proxying).

Use Cases

Used for data processing (e.g., sorting large arrays in a spreadsheet app), image manipulation (e.g., filters in a photo editor), complex calculations (e.g., simulations in educational tools), or parsing big files (e.g., JSON in analytics dashboards).

Code Examples

Main Thread:

javascript

const worker = new Worker('worker.js');
worker.postMessage('Process this');
worker.onmessage = (event) => console.log('Result:', event.data);
worker.terminate(); // When done

Worker Script (worker.js):

javascript

self.onmessage = (event) => {
  const result = event.data.toUpperCase(); // Heavy computation here
  self.postMessage(result);
};
``` [](grok_render_citation_card_json={"cardIds":["89a8f2"]})

### Service Workers

Service Workers act as network proxies in the browser, intercepting requests to enable offline access, caching, and background features. [](grok_render_citation_card_json={"cardIds":["13a21b"]}) They run in a separate thread and require HTTPS.

#### How It Works
Registered via `navigator.serviceWorker.register('/sw.js')`, they have a lifecycle: install (cache assets), activate (clean up), and handle events like `fetch` (intercept requests). [](grok_render_citation_card_json={"cardIds":["c5e3e7"]}) Use `caches` API for storage and promises for async ops.

#### Key Features
- Request interception and modification.
- Offline caching.
- Push notifications and background sync.
- Event-driven (install, activate, fetch).
- Secure context only.

#### Use Cases
Progressive Web Apps (PWAs) for offline modes (e.g., Google Maps caching tiles), push alerts (e.g., news apps), API mocking in dev, or prefetching (e.g., gallery images). [](grok_render_citation_card_json={"cardIds":["225d9a"]})

#### Code Examples
**Registration:**
```javascript
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(reg => console.log('Registered'));
}

Service Worker (sw.js):

javascript

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open('cache-v1').then(cache => cache.addAll(['/'])));
});

self.addEventListener('fetch', (event) => {
  event.respondWith(caches.match(event.request).then(res => res || fetch(event.request)));
});
``` [](grok_render_citation_card_json={"cardIds":["cd320e"]})

### Shared Workers

Shared Workers are web workers accessible by multiple browsing contexts (tabs, iframes) on the same origin, allowing shared state and communication. [](grok_render_citation_card_json={"cardIds":["5c9a28"]})

#### How It Works
Created with `new SharedWorker('worker.js')`, they use `MessagePort` for communication via `port.postMessage()` and `port.onmessage`. [](grok_render_citation_card_json={"cardIds":["5ae880"]}) The worker handles connections with `onconnect`.

#### Key Features
- Shared across contexts.
- Port-based messaging.
- Event-driven connections.
- Terminates when no references remain.

#### Use Cases
Coordinating data across tabs (e.g., shared calculator in multi-window app) or cross-iframe sync (e.g., game state). [](grok_render_citation_card_json={"cardIds":["05d676"]})

#### Code Examples
**Main Script:**
```javascript
const worker = new SharedWorker('worker.js');
worker.port.start();
worker.port.postMessage([2, 3]);
worker.port.onmessage = (e) => console.log('Result:', e.data);

Worker (worker.js):

javascript

onconnect = (e) => {
  const port = e.ports[0];
  port.onmessage = (e) => port.postMessage(e.data[0] * e.data[1]);
};
``` [](grok_render_citation_card_json={"cardIds":["311ec8"]})

### Broadcast Channel API

The Broadcast Channel API allows messaging between browsing contexts and workers on the same origin via a named channel. [](grok_render_citation_card_json={"cardIds":["fb66a0"]})

#### How It Works
Create with `new BroadcastChannel('channel')`, send via `postMessage()`, receive with `onmessage`. [](grok_render_citation_card_json={"cardIds":["9a5f6a"]}) Data is cloned; no direct references needed.

#### Key Features
- Cross-context broadcasting.
- No reference management.
- Structured cloning for complex data.
- Close with `close()`.

#### Use Cases
Syncing state across tabs (e.g., login status) or iframes (e.g., UI updates). [](grok_render_citation_card_json={"cardIds":["b6065d"]})

#### Code Examples
```javascript
const bc = new BroadcastChannel('test');
bc.postMessage('Hello');
bc.onmessage = (e) => console.log('Received:', e.data);
bc.close();
``` [](grok_render_citation_card_json={"cardIds":["b416c8"]})

### Long Polling

Long Polling simulates real-time updates by keeping HTTP requests open until new data arrives, then responding and repeating. [](grok_render_citation_card_json={"cardIds":["26926f"]})

#### How It Works
Client sends request; server holds until data, responds, closes. Client immediately re-requests. [](grok_render_citation_card_json={"cardIds":["116398"]}) Handles errors with retries.

#### Key Features
- No special protocols.
- Low delay for infrequent messages.
- Simple HTTP-based.
- Graceful reconnection.

#### Use Cases
Notifications in legacy systems (e.g., chat with low traffic) or where WebSockets aren't supported. [](grok_render_citation_card_json={"cardIds":["1ef1ee"]})

#### Code Examples
**Client:**
```javascript
async function subscribe() {
  try {
    const res = await fetch('/subscribe');
    if (res.ok) {
      console.log(await res.text());
      subscribe();
    }
  } catch {
    setTimeout(subscribe, 1000);
  }
}
subscribe();

Server (Node.js):

javascript

const http = require('http');
const subscribers = {};
http.createServer((req, res) => {
  if (req.url === '/subscribe') {
    const id = Math.random();
    subscribers[id] = res;
    req.on('close', () => delete subscribers[id]);
  }
}).listen(8080);
``` [](grok_render_citation_card_json={"cardIds":["ba35a2"]})

### WebRTC

WebRTC enables peer-to-peer real-time communication for audio, video, and data without intermediaries. [](grok_render_citation_card_json={"cardIds":["dde31f"]})

#### How It Works
Uses `RTCPeerConnection` for connections, exchanging offers/answers and ICE candidates via signaling. Adds streams (`MediaStream`) or channels (`RTCDataChannel`). [](grok_render_citation_card_json={"cardIds":["817048"]})

#### Key Features
- P2P media and data.
- Encryption (DTLS/SRTP).
- ICE for NAT traversal.
- DTMF for telephony.

#### Use Cases
Video calls (e.g., Zoom-like apps), file sharing, screen sharing, or gaming. [](grok_render_citation_card_json={"cardIds":["cb657c"]})

#### Code Examples
```javascript
const pc = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
  stream.getTracks().forEach(track => pc.addTrack(track, stream));
});
pc.ontrack = (e) => document.getElementById('video').srcObject = e.streams[0];
``` [](grok_render_citation_card_json={"cardIds":["98ecb3"]})

### Web Push API

The Web Push API delivers server-pushed notifications via service workers, even when the app isn't open. [](grok_render_citation_card_json={"cardIds":["9dae9d"]})

#### How It Works
Subscribe with `PushManager.subscribe()`, get endpoint and keys. Server sends to endpoint; service worker handles `push` event. [](grok_render_citation_card_json={"cardIds":["499295"]})

#### Key Features
- Background delivery.
- Unique subscriptions.
- Encryption keys.
- `push` and `pushsubscriptionchange` events.

#### Use Cases
News alerts, chat notifications, or e-commerce updates. [](grok_render_citation_card_json={"cardIds":["ba5bc3"]})

#### Code Examples
(Refer to MDN's ServiceWorker Cookbook for full implementations, as direct snippets focus on events like `onpush` in service workers.) [](grok_render_citation_card_json={"cardIds":["9aa2ca"]})

### WebTransport

WebTransport provides low-level access to HTTP/3 for bidirectional streams and datagrams. [](grok_render_citation_card_json={"cardIds":["418178"]})

#### How It Works
Connect with `new WebTransport(url)`, await `ready`. Use streams for reliable data or datagrams for unreliable. [](grok_render_citation_card_json={"cardIds":["7e938a"]})

#### Key Features
- HTTP/3/QUIC-based.
- Bi/uni-directional streams.
- Datagram support.
- Congestion control options.

#### Use Cases
Gaming (low-latency), streaming, or large transfers. [](grok_render_citation_card_json={"cardIds":["2a3c45"]})

#### Code Examples
```javascript
const transport = new WebTransport('https://example.com:443');
await transport.ready;
const stream = await transport.createBidirectionalStream();
``` [](grok_render_citation_card_json={"cardIds":["842db4"]})

### Background Sync API

Background Sync defers tasks in service workers until network is available. [](grok_render_citation_card_json={"cardIds":["6116b3"]})

#### How It Works
Register via `sync.register(tag)`, handle `sync` event in worker when online. [](grok_render_citation_card_json={"cardIds":["a0fa8e"]})

#### Key Features
- Deferred network ops.
- Tag-based tasks.
- `sync` event.

#### Use Cases
Offline email sending or form submissions. [](grok_render_citation_card_json={"cardIds":["8c8823"]})

#### Code Examples
**Registration:**
```javascript
navigator.serviceWorker.ready.then(reg => reg.sync.register('sync-tag'));

Worker:

javascript

self.addEventListener('sync', (event) => {
  if (event.tag === 'sync-tag') event.waitUntil(fetch('/api'));
});
``` [](grok_render_citation_card_json={"cardIds":["ec7a12"]})

What Are Progressive Web Apps (PWAs)?

Progressive Web Apps (PWAs) are web applications that use modern web technologies to deliver an experience similar to native mobile apps. They combine the reach and accessibility of websites with app-like features such as offline functionality, push notifications, and home screen installation.Coined in 2015 by Google engineers, PWAs have become a standard for building fast, reliable, and engaging experiences across devices. As of 2025, they are widely adopted, with the global PWA market projected to grow significantly due to their cost-effectiveness and performance advantages.PWAs load quickly, work offline or on slow networks, and feel immersive—all from a single codebase using HTML, CSS, and JavaScript.

Core Technologies Behind PWAs

PWAs rely on a few key web APIs:

  • Service Workers — Background scripts that act as a proxy between the app and the network. They enable caching for offline access, background syncing, and push notifications.
  • Web App Manifest — A JSON file that provides metadata (name, icons, theme colors, display mode) so the browser can treat the site like an installable app.
  • HTTPS — Required for security, as service workers have powerful capabilities.
  • Other supporting features: Cache API, Push API, Background Sync API.

These allow PWAs to be reliable (load fast/offline), installable (add to home screen), and engaging (push notifications).

Key Features and Benefits (as of 2025)

FeatureDescriptionBenefit
Offline FunctionalityService workers cache assets, allowing use without internet.Users in low-connectivity areas stay engaged; e.g., view cached content.
Fast LoadingInstant loads via caching and optimized delivery.Lower bounce rates, better SEO (Google favors fast sites).
Installable“Add to Home Screen” prompt; launches fullscreen without browser UI.Feels like a native app; no app store needed.
Push NotificationsRe-engage users even when the app isn’t open.Higher retention and conversions.
Cross-PlatformOne codebase works on Android, iOS, desktop.Cheaper development/maintenance than separate native apps.
Responsive DesignAdapts to any screen size.Seamless on phones, tablets, laptops.
Automatic UpdatesUpdates in the background; always current.No manual downloads required.

Pros:

  • Cost-effective (single codebase).
  • Discoverable via search engines.
  • Improved engagement (many brands report 50-100%+ increases).

Cons:

  • Limited access to some native features (e.g., advanced Bluetooth on iOS).
  • iOS support is improving but still lags behind Android.
  • User adoption: Some prefer traditional app stores.

Popular PWA Examples in 2025

Many major brands use PWAs with impressive results:

  • Starbucks → Doubled daily users; customers browse/menu offline and order seamlessly.
  • Twitter/X Lite → Reduced data usage, faster loads; 20% lower bounce rates.
  • Pinterest → 60% increase in core engagements; higher ad revenue.
  • Uber → Works in low-connectivity areas; quick ride requests.
  • AliExpress → 104% increase in conversions for new users.
  • Flipkart → 70% higher conversions; 3x more time spent on site.
  • Tinder → Faster swiping/loading; better engagement.
  • Others: Forbes, Washington Post, Spotify, BMW.

PWAs represent the future of web development in 2025—blurring the line between web and native apps while offering broader reach and lower costs. If you’re building a site or app, starting with PWA principles (like adding a manifest and service worker) is highly recommended. Tools like Google’s Lighthouse can audit your site for PWA readiness.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *