• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

217
Views
Setting default value for global variable if undefined

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'],
  });
};
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error