Proper way to "reject" a subscription?

Let’s say I have some private data. If someone tries to subscribe to it, it will reject them.

Meteor.publish('secretData', function() {
  if(this.userId) {
    return SecretData.find();
  throw new Meteor.Error(401, "You have to be logged in to view this");

I want to make sure that this publication definitely cannot be subscribed to by a user who is not logged in, and abort to a 401 page if they try to. What is the proper way to do this?

Your mixing your routing concerns with your data concerns. If I’m on the home page of my application, a completely publicly accessible page, not signed in, and I open my browser console and type Meteor.subscribe('secretData') I would certainly not expect my page to change and take me to another page. That’s a duty of the router, not your data.

Instead of throwing an error, simply call this.ready in your publish function, and your subscription will be ‘ready’, just without data. If you want to be more explicit call this.error and give a callback to Meteor.subscribe to do something with that error

Extending what louis posted i would suggest you only return data if your user is a valid user like you did in your example.
If the user is not valid just call this.ready to return “nothing” / an empty subscription.

In your view you could decide now how to behave depending on your data.

Example logic:

if user is logged in or there is data:
render data
render "please login to see data"

This especially 9-11 should be interesting for you.

1 Like