Best practice: adding userId field on the client or on the server?

Hi all, got a little dilemma that I’ve been thinking about for a while and was wondering if anyone could advise me on it.

Suppose I got a collection of private documents with a owner field that represented the ID of the user that created the document. What would be the preferable way to set it?

  • On the client, query Meteor.userId(), and send it as part of the document data as the owner field to the createDocument method. In the method Mongo inserts the document as it is, after validation.
  • On the client, just send the document data. In the method the is called on the server, add the owner field and set it to this.userId right before Mongo inserts the document, after data validation.

End result is the same. Querying the id from the client might be less secure, although it means I could add a SimpleSchema.RegEx.Id rule to the document schema to validate it. Adding it on server side means no need to validate, but if the method was to be accidentally called with no user logged in and valid document data would result to a owner-less document being created in the database?

Open to opinions on the matter. Thanks!

1 Like

General rule: do not trust data coming from the client

Always use this.userId when saving content in the server.

1 Like

Yes, as @rjdavid noted, never trust data supplied by the client. Since it seems you may be using SimpleSchema, I would highly recommend defining an autoValue on your schema for that field and setting denyUpdate for that field to true. For example.

new SimpleSchema({
        ownerId: {
            type: String,
            regEx: SimpleSchema.RegEx.Id,
            autoValue() {
                if (this.isInsert && (!this.isFromTrustedCode || !this.isSet)) {
                    return this.userId;
                } else {
            index: 1,
            denyUpdate: true,