title: How to restrict Meteor.publish() based on a url param?
body: <p>I am new to Meteor and to server-side Javascript. I've been stuck on a seemingly trivial problem: I want to restrict data published by the server according the a path or query string. For example when accessing foo.com/cars/123 I would like the 'cars' collection to only contain the record of car '123'. </p>
  
  <p>I can't find the way to access complete URL in the server-side code where I am calling Meteor.publish().</p>
  
  <p>I first tried to look for some variable that would contain the complete URL and then parse it. I could only find Meteor.absoluteUrl(), which only contains the protocol, host and the port, but the path and query string are stripped.</p>
  
  <p>I tried creating routes that can capture the url params, but when I place Meteor.publish inside the route function no data gets published. It kind of works when I capture the param value in a router, save it as global and then use it when publishing:</p>
  
  <pre><code>// main.js
  
  Meteor.startup(() =&gt; {
    WebApp.connectHandlers.use("/", function(req, res, next) {
      const params = require('url').parse(req.url, true).query;
      global.carId = params['carId'];
  
      next();
    });
  
  });
  
  // cars.js
  
  export default CarData = new Mongo.Collection('car-data');
  
  if (Meteor.isServer) {
      Meteor.publish('carData', function tasksPublication() {
          return CarData.find({id: global.carId || 'demo'});
      });
  }
  </code></pre>
  
  <p>However it would not work with parallel requests, I'd need to use a request-scoped variable instead, which I cannot figure out neither.</p>
  
  <p>Finally I considered replacing the global variable by a global map indexed by Meteor.connection._lastSessionId, but it does not feel like a robust solution.. </p>
  
  <p>I will be grateful for your hints!</p>
  
  <p><strong>EDIT: The solution I found</strong></p>
  
  <pre><code>// cars.js
  
  export default CarData = new Mongo.Collection('car-data');
  
  if (Meteor.isServer) {
      Meteor.publish('carData', carId) =&gt; {
          return CarData.find({id: carId});
      });
  }
  
  // frontend
  
  const urlParams = new URLSearchParams(window.location.search);
  const flowId = urlParams.get("carId");
  Meteor.subscribe('carData', carId);
  </code></pre>