Search code examples
javascriptmeteorscopeglobal-variables

Handling global variables in Meteor


I'm using a query on both server and client (pub/sub). So I have something like this at a few different locations.

const FOO = 'bar';
Collection.find({property:FOO})

Foo may potentially change and rather than have to update my code at separate locations, I was thinking it may be worth it to abstract this away to a global variable that is visible by both client and server.

I created a new file 'lib/constants.js' and simply did FOO = 'bar; (note no keyword). This seems to work just fine. I found this solution as the accepted answer How can I access constants in the lib/constants.js file in Meteor?

My question is if this a desired pattern in Meteor and even general JS.

I understand I can abstract this away into a module, but that may be overkill in this case. I also think using session/reactive vars is unsafe as it can kinda lead to action at a distance. I'm not even gonna consider using settings.json as that should only be for environment variables.

Any insights?


Solution

  • I don't think the pattern is that bad. I would put that file in /imports though and explicitly import it.

    Alternatively, you can write into Meteor.settings.public from the server, e.g., on start-up, and those values will be available on the client in the same location. You can do this without having a settings file, which is nice because it doesn't require you to make any changes between development and production.

    Server:

    Meteor.startup(() => {
      // code to run on server at startup
      Meteor.settings.public.FOO = 'bar';
    });
    

    Client:

    > console.log(Meteor.settings.public.FOO);
    bar