Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; ?>
like image 254
Hassan Sardar Avatar asked Nov 07 '13 05:11

Hassan Sardar


People also ask

Does Nodejs have sessions?

Most frameworks use their own session management middleware. For example, express , the most popular server framework for Node. js, has the accompanying express-session for session management.

What is a session Nodejs?

NodeJS (3 Part Series) It means when a HTTP Request completes the browser and server communication stops. So, We use the session to maintain and remember the user's state at server. We can store the user's session in database, files or server memory. In this tutorial we will learn how to use session in Node.

How do I handle multiple sessions in node JS?

Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.

How do I save a node JS session?

Session management can be done in node. js by using the express-session module. It helps in saving the data in the key-value form. In this module, the session data is not saved in the cookie itself, just the session ID.


2 Answers

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
like image 139
Vaghani Janak Avatar answered Sep 20 '22 19:09

Vaghani Janak


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.
like image 41
Jahanzaib Aslam Avatar answered Sep 20 '22 19:09

Jahanzaib Aslam