Shrikant
Shrikant

Reputation: 334

Global variable for Node Express

I'm using Node Express with EJS. I have a Login module which does all user session related jobs (like for login- generate token, Verify token). So in app.js before sending request to particular module I call login->controller->verifyToken

// app.js
const user = require('./controllers/login');
app.use('/dashboard', user.verifyToken,  dashboard);
app.use('/network', user.verifyToken, network);

user.verifyToken - verifies the token from request header and gives me user details like name, profile pic, etc. I want to store these user details in a Global variable so that I can access it in all the pages. So I did this.

userHeader = authData.user; // without var, let

But with this I can access variable at view files (.ejs). But I cant access this variable at other module .JS files. I think reason behind this is that all view files are executed afterwards, whereas .js files get executed at the time of 'require'.

What is the best way to handle this?

Upvotes: 0

Views: 1084

Answers (1)

Shrikant
Shrikant

Reputation: 334

This is what I have done to overcome my problem. I have used both session and a variable

userHeader = authData.user;

res.cookie('userHeader', userHeader, {
    maxAge: 3 * 60 * 60 * 1000, // 3 hours
});

I'm using userHeader variable directly on ejs files and on other Node modules files I'm getting userHeader variable from response cookie first and then using it.

Upvotes: 1

Related Questions