Best Practice - Method working on server - error on client

I have a method that I defined in a both folder accessible by both server and client. However this method has to get infos about another user. While the method is working on server side (as server can access the users library) it sends an error on client side (as the client is not supposed to see other’s info). Is the best practice to simply put this method on the server side ? I guess they are consequences in term of ressources ? Are they visible ?

Simplified version of the code is as follow :

Meteor.methods({
    'messages.insert'(message, toId) {
        let toUser = Meteor.users.findOne({_id : toId});

        if(!toUser){
            throw new Meteor.Error('not authorized code 12')
        }

        let createdAt = moment().valueOf();

        return Messages.insert({
           toId,
           message
        })
    }
})

On client side I see the error 12 as client not supposed to access other users but on server it works and even writes in the database. Would like it to work without error 12 on client. Ideas ? recommendations ?

thanks in advance

Is your method defined in Server code only or on both Client and Server?

Update: Sorry, you provided the answer to that in your question. Since the code runs twice (first in the client and then on the server), it may be possible that the client code does the insert but the client code does not. Are you subscribed to the User you are trying to find on the client?

You say the user is not suppose to access the other users, but also that you would like not to get the error on the client… not sure which one. But to avoid the client side error, just make sure your code does not run on client (either move the method to server side only, or wrap the code you want on server only in a Meteor.isServer block)

If you want to keep the optimistic UI, you can check this.isSimulation and skip the error on the client.

Methods that run on both throw out the result from the client when the server comes back as the server is the ‘source of truth’.

Example:

Meteor.methods({
    'messages.insert'(message, toId) {
        if (!this.isSimulation) {
            let toUser = Meteor.users.findOne({_id : toId});

            if(!toUser){
                throw new Meteor.Error('not authorized code 12')
            }
        }

        let createdAt = moment().valueOf();

        return Messages.insert({
           toId,
           message
        })
    }
})

2 Likes