Home > Software design >  Setting default value for global variable if undefined
Setting default value for global variable if undefined

Time:05-17

Objective

Pass the role (e.g. admin) of a user to all my view templates without having to do it in each individual route.

What I'm trying

Adding user roles (called with req.oidc.user...) as a res.local in app.js.

Code (app.js)

app.use((req, res, next) => {
  res.locals.role = req.oidc.user['https://localhost:3000.com/roles'] ?? "null"
})

Problem

I was hoping the ?? "null" would add a value of "null" to the roles when a user is not logged in so I can handle conditional logic in the templates with

'if !role === 'admin' do x. 

Instead, I'm just getting an error of Cannot read properties of undefined (reading 'https://localhost:3000.com/roles') (understandable as there's nothing there when not logged in!)

Is there a better way to pass a values that will be undefined until a user logs in to my views without doing the below in every single route in (controller.js):

index = (req, res) => {
  res.render("index", {
    role: req.oidc.user['https://localhost:3000.com/roles'],
  });
};

CodePudding user response:

As you've said, your code is trying to read a value from a variable that might be undefined.

You can either use a condition to check wether req.oidc.user exists before reading from it or have optional chaining in order to "short-circuit" the expression to undefined without causing an error.

This is your code with optional chaining:

app.use((req, res, next) => {
    res.locals.role = req.oidc.user?.['https://localhost:3000.com/roles'] ?? "null";
});

Side note, I suggest not using "null" as your default value. Maybe use an empty string ("") which is also a falsy value.

  • Related