send a variable with a value to front end of all routes node.js

Viewed 338

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.

1 Answers

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) => { ... }
Related