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

141
Visualizações
Send variables to all routes in expressjs

I have req.session variables that I am setting upon login, like so:

req.session.loggedin = true
req.session.firstname = loginDetails.firstName;

what I want to do is pass this information to ALL routes (I have nearly 60, and don't want to go through all of them and add these in manually), and also every route I have calls the front-end using this:

res.render('page.ejs', {data: rows}), so I would ideally want it to pass it to the front-end pages so I can access them there too. Not sure if this is possible, but worth a shot! thx 4 the help in advance!
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can create a middleware function and add variables to an existing express-session.

app.js

const express = require("express");
const session = require("express-session");

// express app
const app = express();
app.use(express.json());

// init example session with express session
app.use(session({ resave: true, secret: "123456", saveUninitialized: true }));

// use a middleware function
app.use((req, res, next) => {
  if (!req.session.initialised) {
    // init variables you want to set in req.session
    req.session.loggedin = true;
    req.session.firstname = "john doe";
  }
  next();
});

// test api endpoint
app.use("/testroute", require("./routes/api/test"));

// run server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Then you can query your variables like req.session.firstname in any other route in the request object. You can also update it from your routes

test.js

// testroute
const router = express.Router();

router.get("/", async (req, res) => {
  // get variables from request object
  try {
    console.log(req.session.firstname);
    console.log(req.session.loggedin);

    // this would update the session variable if uncommented
    // req.session.firstname = "dagobert"
    // console.log(req.session.firstname);
    res.status(200).json({ message: `Your firstname is ${req.session.firstname}` });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

module.exports = router;
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