Publications for authenticated users

I've decided to replace the previous article on publishing to authenticated users. Here i'll explain perhaps a more correct approach, with further explaination and examples.

As a general rule, if a publication only publishes data to authenticated users, we should only subscribe to it when we are signed-in. There are a couple of reasons why.

Let's say our publication looks like so:

// Notes owned by an individual user
Meteor.publish('notes', function() {
  check(this.userId, String);
  return Notes.find({ userId: this.userId });

If we are not signed-in and we subscribe to this publication, the subscription handle ready method will never return true.

Not only are we unnecessarily communicating with the server (the client already knows we're not signed-in), but it can be a problem if we are relying on the subscription state in order to show a loading indicator. Hint: Your page won't stop loading!

Example using iron-router

The key part is what's going on within our waitOn method.

  layoutTemplate: 'layout',
  loadingTemplate: 'loading'

if (Meteor.isClient)
  Router.onBeforeAction('loading'); {
  this.route('notes', { path: '/' });

NotesController = RouteController.extend({
  waitOn: function() {
    if (Meteor.userId())
      return Meteor.subscribe('notes');
  data: function() {
    return {
      notes: Notes.find({ userId: Meteor.userId() })

Iron Router's waitOn method is a reactive computation. Any time the result of Meteor.userId() changes, it will re-run. And of course if Meteor.userId() returns an id, we'll subscribe.

See also

Publish and subscribe

Iron Router waitOn