Skip to main content

DDP Connections API

DDP (Distributed Data Protocol) is Meteor’s protocol for sending data over WebSockets. These APIs allow you to manage connections and create multi-server applications. Source: packages/ddp-client/common/livedata_connection.js

DDP.connect()

Connect to another Meteor server and return a connection object. Locus: Anywhere
string
required
URL of another Meteor application to connect to.
object
Optional connection options.
boolean
Whether to reload if there are outstanding methods. Default: false.
object
Extra headers to send on the WebSocket connection (server-to-server DDP only).
boolean
Whether to automatically retry on connection failures. Default: true.
function
Callback when version negotiation fails.

Connection Object

The connection object returned by DDP.connect() has the same API as Meteor on the client:

connection.subscribe()

Subscribe to a publication on the remote server.

connection.call() / connection.callAsync()

Call a method on the remote server.

connection.apply() / connection.applyAsync()

Call a method with an array of arguments.

connection.status()

Get the current connection status. A reactive data source. Returns: Object with status information
boolean
True if currently connected to the server.
string
Connection status: “connected”, “connecting”, “failed”, “waiting”, or “offline”.
number
Number of reconnection attempts made.
number
Estimated time of next reconnection attempt.
string
If failed, description of why the connection failed.

connection.reconnect()

Force an immediate reconnection attempt.

connection.disconnect()

Disconnect from the server.

connection.close()

Permanently close the connection.

connection.userId()

Get the user ID on this connection. A reactive data source.

Using Remote Collections

Access collections from a remote server:

Server-to-Server Connections

Connect Meteor servers to each other:

Connection Lifecycle Events

Listen to connection events:

DDP.onReconnect()

Register a callback to be called on reconnect.

Meteor.onConnection() (Server)

Register a callback to be called when a new DDP connection is made to the server. Locus: Server
function
required
The function to call when a new DDP connection is established.

Connection Object Properties (Server)

string
Globally unique identifier for this connection.
function
Close this DDP connection. The client will reconnect.
function
Register a function to be called when this connection is closed.
string
The IP address of the client.
object
HTTP headers sent by the client in the initial WebSocket handshake.

Multi-Server Architecture Example

Best Practices

  1. Connection Pooling: Reuse connections instead of creating new ones for each request.
  2. Error Handling: Always handle connection failures gracefully.
  1. Security: Use authentication for server-to-server connections.
  1. Cleanup: Close connections when no longer needed.