Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda