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

156
Visualizações
send a variable with a value to front end of all routes node.js

I have req.session values that are being stored upon login. But what I want to do is access them on every page of my app (front-end(ejs)), but i don't want to go into every single route/function i have and pass it. So i was wondering if there is a universal way to pass req.session to the front-end from one route and access them on all pages?

my routes look like this:

app.get('/', (req, res) => {
   res.render("index.ejs");
})

sorry if this is an odd question, but wondering if there is universal ways to do things like this.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In authentication, you probably need these two things:

  • Front end: Context to form a global state around authentication information
  • Back end: Retrieve user info based on session id sent & Middleware to authenticate the requests

You should set up something like authContext to fetch information of sessionID from backend, and trigger some function on login and logout to revise the authentication. You may want to research React Context to figure out how to apply "global state", if you are not familiar with that.

In the backend, use middleware to authenticate every HTTP request and apply that middleware to the route you want to apply authentication.

Which can go something like this:

async function auth (req, res, next) {
  try {
    const session = await MySessions.findById(req.sessionID);
    if (!session) throw 'Not authenticated'
    else next()
  } catch (error) {
    // Response will be rejected, and wont be passed to route due to not sending next()
    return res.status(401).send({ error })
  }
}

// Example of applying middleware auth to route you need.
router.delete('/:postId', auth, async (req, res) => { ... }
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