Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

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.

Solution 5:

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

Post a Comment for "Maintain Sessions In Node.js"