Skip to main content

Publish/Subscribe API

Meteor’s pub/sub system controls which data is sent from the server to the client. Source: packages/ddp-server/livedata_server.js, packages/ddp-client/

Publications (Server)

Meteor.publish()

Publish a record set to clients. Locus: Server
name
string | null
required
Name of the record set. If null, the set has no name and the record set is automatically sent to all connected clients.
func
function
required
Function called on the server each time a client subscribes. Inside the function, this is the publish handler object.

Universal Publications (null)

Publications with null name are sent to all clients automatically:

Custom Publications

For advanced use cases, manually control published data:

Publication Context (this)

Inside a publish function, this provides:
userId
string
The id of the logged-in user, or null if no user is logged in.
connection
object
The connection object for this subscription.
ready
function
Call when the initial snapshot is complete. Triggers onReady callback on client.
onStop
function
Register a callback to run when the subscription is stopped.
error
function
Stop this subscription and signal an error to the client.
stop
function
Stop this subscription.
added
function
Inform the subscriber that a document has been added.
changed
function
Inform the subscriber that a document has been modified.
removed
function
Inform the subscriber that a document has been removed.

Subscriptions (Client)

Meteor.subscribe()

Subscribe to a record set. Returns a handle that provides stop() and ready() methods. Locus: Client
name
string
required
Name of the subscription. Matches the name of the server’s publish() call.
...args
any
Optional arguments passed to publisher function on server.
callbacks
object | function
Optional. May include onStop and onReady callbacks. If a function is passed instead of an object, it is interpreted as an onReady callback.

Subscription Handle

The object returned by Meteor.subscribe() has these methods:

handle.stop()

Stop this subscription.

handle.ready()

True if the server has marked the subscription as ready. A reactive data source.

handle.subscriptionId

The subscription ID.

Reactive Subscriptions

Subscriptions in Tracker.autorun automatically resubscribe when dependencies change:

Template Subscriptions

With Blaze templates:

Publication Strategies (Server)

Optimize performance by choosing different merge strategies:

Security

Never publish sensitive data:

Complete Example