0

Experimenting with Meteor due to this question, I came to the following conclusion:

Defined in a shared directory (client/server), this will throw an Reference Error:

if(Meteor.isServer) {
    // could depend on server logic, this is not Meteor.isServer!
    serverVar = true;
}    

Meteor.methods({
    myMethod: function() {
        if(serverVar) {
            return "secret";
        } else {
            throw Error();
        }
    }
}

Then, on the client:

Meteor.call("myMethod", function(err, res) {
    console.log(res);
}

Leads to: ReferenceError: serverVar

But this code, being defined on the server side only, runs flawlessly:

// could depend on server logic, this is not Meteor.isServer!
serverVar = true;

Meteor.methods({
    myMethod: function() {
        if(serverVar) {
            return "secret";
        } else {
            throw Error();
        }
    }
}

Note that I only switched to a server-side directory instead of a shared one and removed the if-clause.

I thought that both approaches should be equivalent, ignoring the fact that code is visible on the client when only limited by Meteor.isServer.

This leads me to the conclusion that Meteor, using the first approach, tries to run code on the client when it is not explicitly limited to the server. Is that true?! What could be another explanation?

Community
  • 1
  • 1
Xiphias
  • 4,468
  • 4
  • 28
  • 51

3 Answers3

1

dont use Meteor.isServer()

Meteor.isServer can be used to limit where code runs, but it does not prevent code from being sent to the client.

check this answer to structure your meteor app

Community
  • 1
  • 1
pahan
  • 2,445
  • 1
  • 28
  • 36
0

Okay, I got it. Using the first approach, Meteor throws a ReferenceError. This is due to the client-side simulation of the function. This feature is described in the documentation here.

So the code works with both approaches, but when also being defined on the client, it throws that ReferenceError. This does not happen anymore when limiting the scope to the server.

Xiphias
  • 4,468
  • 4
  • 28
  • 51
0

I think you might just need a var serverVar; at the very top (shared)

matb33
  • 2,820
  • 1
  • 19
  • 28