Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda