Home > Blockchain >  Can res.locals Be Accessed By Clients?
Can res.locals Be Accessed By Clients?

Time:11-26

Context

I am storing the entire user object in res.locals.loggedUser like this in the server:

app.use(async (req, res, next) => {
     const user = await User.findById(req.session.userid);
     res.locals.loggedUser = user;

     next();
});

After setting res.locals.loggedUser, I can access it through ejs in client side like this:

<% if(loggedUser) { %>
     <p>Your name: <%= loggedUser.name %></p>
<% } %>

The entire user object consists of these fields:

    _id: {
        ObjectId("123abc")
    },
    name: {
        type: String,
        required: [true, 'Your name is required.']
    },
    email: {
        type: String,
        required: [true, 'Email cannot be blank.'],
        unique: true
    },
    phone: {
        type: Number,
        required: [true, 'You must provide your phone number.'],
        unique: true
    },
    hashpassword: String,
    date: {
        joined: {
            type: Date
        }
    },

Question

Can clients get access to the rest of the fields of the user object like the hashpassword field? Or is res.locals only available to the server?

Thank You!

CodePudding user response:

Can res.locals Be Accessed By Clients?

No.

res.locals exists only on the server - it is not available to the client.

The contents of res.locals can be used by your server-side template/template engine in building a web page like you already do with <% if(loggedUser) { %> that will be sent to the client, but there will be nothing from res.locals in the web page unless you specifically add something to your template that inserts something from res.locals into the web page.

  • Related