Hassan Sardar
Hassan Sardar

Reputation: 4523

Maintain sessions in Node.js

How can I maintain my SESSIONS in Node.js?

For example, I want to store UserID in SESSION using Node.js. How can I do that in Node.js? And can I use that Node.js SESSION in PHP too?

I want the following in Node.js:

<?php $_SESSION['user'] = $userId; ?>

Upvotes: 14

Views: 3881

Answers (11)

Moman Raza
Moman Raza

Reputation: 168

You can use sessions in Node.js by using the 'express-session' package in Node.js.

You have to install express and express-session in your application:

const express = require('express');
const session = require('express-session');
const app = express();

"secret" is used for the cookie, and we have to add some secret for managing a session. "request" we use as a request variable as we use $_SESSION in PHP.

var sess;
app.get('/',function(req,res){ // Get request from the app side
sess = req.session;
sess.email; // Equivalent to $_SESSION['email'] in PHP.
sess.username; // Equivalent to $_SESSION['username'] in PHP.
});

Here is full documentation in Code for Geek about the session in Node.js if you want to learn in detail about the session in Node.js.

Upvotes: 0

Prashant Pathak
Prashant Pathak

Reputation: 1

Storing a session in Node.js is fairly easy but you need to understands its step, you could handle this manually, also you can use few NPM modules. Passport can help you to authenticate and login and store the session i would recommend you to read its documentation, Passport allow you to authenticate user with different other platform like Google, github many more.

If you are going to use passport use these below NPM module

  1. Passport
  2. Passport Local
  3. Express-flash
  4. Express-session

2 -Import these modules in your main app.js:

    const flash = require('express-flash')
    const session = require('express-session')
    const passport = require('passport')
    app.use(session({
        secret:'secret',
        resave:false,
        saveUninitialized:false
    }))

   app.use(flash())
   app.use(passport.initialize())
   app.use(passport.session())

3- Create the passport.js file. You can name anything. So basic understanding behind this is that you have to check the valid user coming from your input form, and you have to compare the email id with your model. If it is valid, check the password and then return the user. Once that is done, serialize and deserialize your user data to store in the session..

I would recommend to check this part in the documentation for more clear understanding: Overview

const localStrategy = require('passport-local').Strategy
const bycrypt = require('bcrypt')
const User = require('../model/User')

const initalize = function(passport) {
    const auth = async(email, password, done) => {
        try {
           const user = await User.findOne({email:email})

           if(!user) {
               throw new Error("Incorrect Email ..!")
           }
           const match = await bycrypt.compare(password, user.password)

           if(!match) {
               throw new Error('Incorrect Password..!')
           }

          return done(null, user)
        }
        catch (error) {
            console.log(error)
            done(null,false,error)
        }
    }

    passport.use(new localStrategy({usernameField:'email'}, auth))

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });
}

module.exports = initalize

4 - Now go to your login router and use the below code

    const passport = require('passport')

    require('../passport/passport')(passport)

    routes.get('/signin', (req,res) => {
        res.render('signin', {
            pageTitle: 'sign in'
        })
    })
    routes.post('/signin', passport.authenticate('local', {
        successRedirect: '/welcome',
        failureRedirect: '/',
        failureFlash: true
    }))

Upvotes: 0

vanya jain
vanya jain

Reputation: 13

Follow the below steps:

  1. npm install express-session --save

  2. Write the below code:

    var express = require('express');
    var session = require('express-session');
    var app = express();
    app.use(session({secret: 'your secret key', saveUninitialized: true, resave: true}));
    var userId = 1234;
    app.get('/', function (req, res, next) {
        req.session.userId = userId;
    });
    

Upvotes: 0

LALIT MOHAN
LALIT MOHAN

Reputation: 39

Session that gives access/permission to view a user's area, as well as it's a credential, so we can use it over the application.

I used jsonwebtoken to make a token which will has the user's details with time after a successful login attempt by the user. I stored it in Redis, and it can be used for a pre-declared time limit.

Upvotes: 1

Rahul Dey
Rahul Dey

Reputation: 107

You can handle the session in two ways.

  1. Using express-session
  2. Using JWT web token and handle your own session (token-based session handling).

I think token-based session handling is more important rather than using express-session. You will get a problem when you scale your server and also a problem with some single device login situation.

For checking I have a token-based session handling Node.js folder structure. You can check it, and it may be helpful.

Upvotes: -1

Siten
Siten

Reputation: 4533

To maintain a session is now older, and you should try with using JWT token. It is very effective and easy. But still to maintain the session in Node.js:

In your Express.js configuration:

var cookieParser = require('cookie-parser');
var session = require('express-session');

app.use(cookieParser());
    app.use(session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true,
        rolling: true,
        cookie: {
            path: '/',
            maxAge: 60000 * 1000
        },
        name: 'SID'
    }));

Store session after Login:

var session = req.session;
    if (user) {
        session.user = user._id;
        session.save();
        console.log(session);
    }

Check Session from middleware:

var session = req.session;
            if (session.user) {
                req.userid = session.user;
                next();
            } else {
                return res.status(401).send({
                    code: 401,
                    message: Constant.authentication_fails
                });
            }

Upvotes: 0

Lu&#237;s Gomes
Lu&#237;s Gomes

Reputation: 61

You don't need to do it by yourself. There are some amazing modules in Node.js that handle this kind of things for you.

You can use session middleware from Express.js, as suggested before.

However, I'd recommend you to use Passport.js. This module does the authentication part for you, has a lot of strategies that you could integrate in your website (log in with Facebook, Google, Twitter, etc.), and deals with all the session stuff automatically, using serializeUser() and deserializeUser() functions whenever you need to.

You can take a look at this here, within the "Sessions" section: Configure Passport.js

Upvotes: 1

Vaghani Janak
Vaghani Janak

Reputation: 611

First install the session package

npm install express-session --save

Initialization of the session on your server page

var express = require('express');

var session = require('express-session');

var app     = express();

app.use(session({secret: 'ssshhhhh', saveUninitialized: true, resave: true}));

Store session

sess = req.session;

var user_id = 1;

sess.user_id = user_id;

Access the session

sess = req.session;

sess.user_id

Upvotes: 17

Jahanzaib Aslam
Jahanzaib Aslam

Reputation: 2834

Let me divide your question in two parts.

  1. How can I maintain my SESSIONS in Node.js?
    Answer: Use express-session middleware for maintaining SESSIONS
  2. Can I use that a Node.js SESSION in PHP too?
    Answer: Yes, you can use that session in PHP too, but keep in mind you have to store that session in the database.

Upvotes: 9

user4466709
user4466709

Reputation:

You could use the express-session middleware.

Combine it with connect-redis or connect-mongo to store your sessions inside a database and save memory if memory is valuable to you (like in a cloud setup).

express-sessions (npm)

If you store it in, say, MongoDB, use the PHP MongoDB driver to pick it up from there.

Upvotes: 3

Ben Barkay
Ben Barkay

Reputation: 5622

ExpressJS has official session middleware, and it is also the current de-facto standard web framework for Node.js.


If you wish to implement session support on your own, this is how the implementation is normally done, upon every request:

  1. Check if the cookie contains a session ID
    • If not, create a session object that is either stored in memory, on file, or in a database (or a combination of those), and set the session id in the response cookie to match this object's identifier.
    • If the cookie does contain a session ID, locate the session object by the ID.
  2. Provide the obtained/created object from step 1 as the persisted session object for the request.

You will also have to implement some timeout mechanism, so that after a while the session objects are deleted, at least from memory.

Upvotes: 8

Related Questions