Where to put Meteor.publish and Meteor.subscribe calls?

I know that Meteor.publish is server side and Meteor.subscribe is client side, but I’m not 100% clear on which files (or locations within files, such as methods or callbacks) that I’m supposed to invoke these calls.

I recommend checking out the examples

meteor create --list

The publish part is anywhere in your server code (not in a callback or method).

The subscribe part can be either application wide on your client, or template specific.

I personally have file structure that looks like this server/publications/userPublications.js on the server. Depending on what I’m publishing I usually have one file per collection to publish with that way I can keep track of where I’m defining my pubs.

As for subscriptions, I have become partial to subscribing in the onCreated callback in a given template. For example I will do

Template.foo.onCreated(function(){
  var self = this;
  self.subscribe("bar"); 
});

Following from what @jamgold has said.

I have a file in a /server/ dir called publish.js.
Just have all my publish code in there.
They are only actioned whenever a client tries to subscribe…

In the past I have always put my subscriptions in my router code.
However now with template based subscriptions being available, I am moving some out of the router and into the template onCreated hooks.

I am still working out where it is best to put the global subscriptions.
I’ve got it working at the moment by using the main layout templates onCreated

Is there any advantage to putting Meteor.subscribe calls in Template.onCreated rather than the Router’s waitOn callback function?

I think it largely comes down to your app and how it is structured.

Sacha has a great blog post covering this discussion: https://www.discovermeteor.com/blog/template-level-subscriptions/

There is another thread with some more posts and suggestions…

Holy crap, I totally forgot about Template.subscribe. Thanks for the link!

I currently have my publications stored in /server/publications.js. I was wondering if it’s safe to store subscriptions somewhere like /client/subscriptions.js, or is that not a smart idea?