Sessions in Node JS

How can I maintain my SESSIONS in Node JS ? E.g 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

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

In Node Js.


1 Solution
Solution

ExpressJS has official session middleware, 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 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.