Course contentsShow
← JavaScript
Lesson 2168 of 2,72345. Workers and ConcurrencyFree lesson

PostMessage Overview: Sending Data Between Contexts

Learn the postMessage API for cross-context communication in browsers and Node.js worker threads.

PostMessage Overview: Sending Data Between Contexts

You'll learn how postMessage enables safe, structured communication between isolated JavaScript execution contexts.

What Is PostMessage?

postMessage is the universal API for sending data between execution contexts that don't share the same global scope—like a main thread and a Web Worker, a Node.js main thread and a Worker Thread, or even different browser windows. Think of it as a message-passing mailbox: you drop a message in on one side, and the recipient picks it up on the other side through an event listener.

How It Works

The sender calls postMessage(data) with the data to send. The receiver listens for 'message' events. The data is copied (or transferred) between contexts using the structured clone algorithm, which safely duplicates most JavaScript values without sharing memory references.

Why It Matters

Because workers and different contexts run in isolation (no shared variables), postMessage is the only way to communicate without advanced techniques like SharedArrayBuffer. It's asynchronous—messages arrive as events, not synchronous return values—so your code stays non-blocking.

The Pattern

Sender side:

worker.postMessage({ type: 'compute', value: 42 });

Receiver side:

self.addEventListener('message', (event) => {
  console.log(event.data); // { type: 'compute', value: 42 }
});

The event.data property contains the cloned data. Both Web Workers and Node.js Worker Threads use this same pattern, though Node.js uses parentPort.postMessage() inside the worker script.

Key Characteristics

  • Asynchronous: Messages arrive via events, not immediately
  • Safe copying: Data is cloned by default, preventing shared-state bugs
  • Bidirectional: Both sides can send and receive

Key Takeaway:
postMessage is the standard, safe API for sending data across isolated execution contexts—it clones your data and delivers it asynchronously via message events.