title: request session not persistent - express-session
body: <p>I'm trying to have a session containing user data in the node.js/express FW.
  I'm using express-session. I'm not using session store yet.
  I have 2 pages in the client (angular) where I iterate between - Login and Dashboard. The idea is to create the session after successful login, then routing to the dashboard page. In the dashboard page I have an anchor with routinlink to the login:</p>
  
  <pre><code>&lt;a [routerLink]="['/login']" &gt;BackToLogin&lt;/a&gt;  
  </code></pre>
  
  <p>When navigating back to the loginPage (when activating a route), I execute a service with an end-point to the express server which check if the request has a session with a request in it (I expect it to be). <strong>The problem is that I see that the session is not the same session (the id changes)</strong></p>
  
  <p>See my code:
  Node.js side - server.js file:</p>
  
  <pre><code>const express = require('express');
  const app = express();
  const bodyParser = require('body-parser');
  const cors = require('cors');
  
  const session = require ('express-session'); 
  var cookieParser = require('cookie-parser');
  const SESS_NAME = 'sid'; 
  
  app.use(session({
      name:SESS_NAME,
      key: 'user_sid',
      resave:false, 
      saveUninitialized:false, 
      secure: process.env.NODE_ENV ==="production",  
      secret:'&lt;some random text&gt;', 
      cookie:{
  
              httpOnly: true, 
              secure: process.env.NODE_ENV ==="production", 
              expires: 60000 
             }
  }));
  
  app.use(bodyParser.text());
  app.use(bodyParser); 
  app.use(bodyParser.urlencoded({ 
      extended: true
  }));
  
  app.use(cors()); //No limitation for test reasons
  
  app.use(cookieParser());
  
  //disabled on purpose
  //var sessionManagement = require('./middleware/sessionManagement'); 
  // API   
  app.use("/", require("./api/v1/routes.js"))//This file includes:
  /*
  const express = require('express');
  const router = express.Router();
  router.use("/login", require('./login'));
  router.use("/session", require('./session'));
  module.exports = router;
  */
  ...etc
  app.listen(config.port, () =&gt; console.log(`Process ${process.pid}: Listening on port ${config.port}`));
  </code></pre>
  
  <p>login.js on the server: responsible for validating user and store user data in session:</p>
  
  <pre><code>const express = require('express');
  const router = express.Router();
  const schema = require('./objectSchemaJson.schema.json');
  const scehmaCheck = require('../../middleware/checkForSchema')(schema);//this is 
  a schema check (middleware) - if suceeded continue (next)
  
  const storeSession = (req, dataResult) =&gt;
  {
      if (&lt;dataResult return with valid use data&gt;) //This is "where the magic happanes"
      {
          req.session.user = { 
              username: &lt;get userName from dataResult&gt;, 
              ID: &lt;Get ID from dataResult&gt;, 
              Role: &lt;Get Role from dataResult&gt; 
          }    
      }
  }
  router.use("/", scehmaCheck, (req, res, next) =&gt; {
      return GetUserDataFROmDB(req.body).then((dataResult) =&gt; { //reaching the DB - not mentioned here on purpose
          storeSession(req, dataResult); // This is where the session set with user data
          res.status(200).json(dataResult);
      }).catch((err) =&gt; {
          next({
              details: err
          })
      });
  });
  
  module.exports = router;
  </code></pre>
  
  <p>This is the end point on the server that responsible for getting the session - session.js - <strong>This is where the problem appears - the res.session has a session ID which is different that the one I created after the login</strong></p>
  
  <pre><code>const express = require('express');
  const router = express.Router();
  
   hasSession : function(req, res) //This is where the problem appears - the res.session has a session ID which is different that the one I created after the login
  {
      if (req.session.user)
      {
          res.status(200).json(
              {
                  recordsets: [{Roles: req.session.Roles, UserName: req.session.user.username}]
              });
      }
      else{
          res.status(200).json({});
      }
  }
  
  router.use("/", (req, res, next) =&gt; { return sessionManagement.hasSession(req, res, next)});
  
  module.exports = router;
  </code></pre>
  
  <p>Client side:</p>
  
  <pre><code>//HTML:
  &lt;div&gt;
    &lt;label&gt;Username:&lt;/label&gt;
    &lt;input type="text" name="username" [(ngModel)]="userName" /&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;label&gt;Password:&lt;/label&gt;
    &lt;input type="password" name="password" [(ngModel)]="password"/&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;button (click)="login()"&gt;Login&lt;/button&gt;
  &lt;/div&gt;
  
  //COMPONENT:
  
  login()
    {
      this.srv.login(this.userName, this.password).subscribe(result =&gt; 
        {
          if (&lt;result is valid&gt;)
          {
            this.router.navigate(['/dashboard']);
          } 
  
        }
      );
    }
  
  //This reach the node.js endpoint and routing to the session.js end point - it is executes when the router-outlet activated in the app.component:
  /*
      onActivate(componentRef : any)
        {
          if (componentRef instanceof LoginComponent)
          {
            componentRef.getSession();
          }
        }
  */
  
  
  
  getSession() : void
    {
      this.sessionService.getSession().subscribe( result =&gt; 
        {
          if (&lt;result is valid&gt;)
          {
            this.router.navigate(['/dashboard']);
          }
        });
    } 
  </code></pre>
  
  <p>I found a similar question on github - no solution yet:
  <a href="https://github.com/expressjs/session/issues/515" rel="nofollow noreferrer">https://github.com/expressjs/session/issues/515</a>
  but it might be a cookie &lt;-> server configuration issue.</p>