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

Transferring MessagePorts Across Workers

Pass MessagePort objects between workers to enable direct peer-to-peer communication.

Transferring MessagePorts Across Workers

You'll learn how to pass MessagePort objects between workers to enable direct peer-to-peer communication without routing messages through the main thread.

The Core Idea

Once you've created a MessageChannel, you have two MessagePort objects that form a communication pipeline. While you might keep one port in the main thread and send the other to a worker, there's a powerful twist: you can transfer a MessagePort itself to another worker. This lets two workers talk directly to each other, bypassing the main thread entirely.

Think of it like introducing two colleagues via email. You connect them initially, but once they have each other's contact info (the ports), they can communicate directly without you in the middle.

How It Works

You transfer a MessagePort just like you would an ArrayBuffer—by including it in the transfer list when calling postMessage. The port is then moved (not copied) to the receiving worker, where it can be used to send and receive messages with whoever holds the other port.

Example flow:

  1. Main thread creates a MessageChannel.
  2. Main thread sends port1 to Worker A.
  3. Main thread sends port2 to Worker B, transferring it in the message.
  4. Worker A and Worker B now communicate directly via their respective ports.

This pattern is especially useful for complex multi-worker architectures where workers need to coordinate without bottlenecking the main thread.

Why This Matters

Transferring ports decentralizes communication. Instead of all messages funneling through one point, workers can establish dedicated channels for specific tasks—image processing workers coordinating tiles, data workers sharing results, etc.

Key Takeaway: You can transfer MessagePort objects between workers using the transfer list, enabling direct worker-to-worker communication and reducing main-thread congestion in complex concurrent applications.