xerox28
xerox28

Reputation: 21

How to make session variables in node.js and pass it from route to route?

Let say that I have "home" route and "food" route. In "home" route I collected user data from database, I want to pass username to "food" route. I want to use session to do that, but I didn`t find solution for that. In PHP is very easy by using

$_SESSION['username'] = username;

From google I learned that in node.js I can do something like this

const express = require('express');
const session = require('express-session');
const app = express();
var sess;
app.get('/',function(req,res){
     sess=req.session;

     sess.email; // equivalent to $_SESSION['email'] in PHP.
     sess.username; // equivalent to $_SESSION['username'] in PHP.
});

But I learned as well that using a global variable for the session won’t work for multiple users. You will receive the same session information for all of the users. This person recommend to use Redis, but it require to install another software. Is there any better way to save data to session variables in node.js and pass it to another route similar to what I can do in PHP?

Upvotes: 2

Views: 1839

Answers (1)

Mario Santini
Mario Santini

Reputation: 3003

You have to create a session object and pass it to expressjs app in order to access the sessions.

This is the example from the documentation:

var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}))

And then you can access the session from the request object in handlers:

app.get('/', function(req, res, next) {
    if (req.session.views) {
        req.session.views++
        res.setHeader('Content-Type', 'text/html')
        res.write('<p>views: ' + req.session.views + '</p>')
        res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
        res.end()
    } else {
        req.session.views = 1
        res.end('welcome to the session demo. refresh!')
    }
})

Upvotes: 2

Related Questions