Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!