req.session undefined and req.session.user_id not working

14,949

The session middleware checks if an incoming request matches the cookie path; if not, it doesn't bother continuing (and req.session won't even be created). In your situation, your cookie path is set to /public/, which doesn't match the request path /login.

I think you'd want to configure the session middleware cookie to use / as a path:

app.use(express.session({
  cookie: {
    path    : '/',
    httpOnly: false,
    maxAge  : 24*60*60*1000
  },
  secret: '1234567890QWERT'
}));
Share:
14,949
Zeeshan
Author by

Zeeshan

I am a Telecommunication Engineer, completed my masters in University of Ulm Germany. Worked with digital signal processing related to Synthetic aperture radar imaging and automotive FMCW radar. Also have intermediate skills of C, C#, php, perl, Matlab and Javascript.

Updated on August 31, 2022

Comments

  • Zeeshan
    Zeeshan over 1 year

    I am using Express and node for the session management with https. I want to create a session using express so that authentication and the session is made before the redirection to the static files in the public folder. Previously i was having a problem Trouble using express.session with https But it was solved by including path in the express.session as /public but now my req.session is showing as undefined but in the browser there is connect.sid cookie present

    The app.js is :

    var express = require('express')TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:59:24 at callbacks;
    var http = require('http');
    var https = require('https');
    var fs = require('fs');
    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('localhost:27017/svgtest1');
    var options = {
      key: fs.readFileSync('privatekey.pem'),
      cert: fs.readFileSync('certificate.pem')
    };
    
    var app = express();
    
    app.use(express.static(__dirname + '/public'));
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(express.cookieParser());
    app.use(express.session({cookie: {  path: '/public/',httpOnly: false , maxAge: 24*60*60*1000}, secret: '1234567890QWERT'}));
    
    //middle ware to check auth
    function checkAuth(req, res, next) {
      if (!req.session.user_id) {
        res.send('You are not authorized to view this page');
      } else {
        next();
      }
    }
    
    
    app.get('/', function(req, res) {
      console.log('First page called');
      res.redirect('loginform.html');
      console.log('redirected');
      res.end();
    });
    
    app.post('/login', function(req, res) {
      console.log('login called');
      var usrfield = req.body.usrfield;
      var passfield = req.body.passfield;
    
        console.log(req.session);
    
    
    // Play with the username and password
    
            if (usrfield == 'kk' && passfield == '123') {
                 req.session.user_id = 'xyz';
            res.redirect('svg-edit.html');
          } else {
            res.send('Bad user/pass');
          }
    
    
            console.log(usrfield);
            console.log(passfield);
            res.end();
        });
    

    Client Side :

    <html>
    
    <style media="screen" type="text/css">
    @import url("css/loginform_styles.css");
     </style>
    
        <head>
                <script type="text/javascript" src="annotationTools/js/md5.js" ></script>
                <script>
    
                    function validateForm()
                    {
                        var usrnamefield=document.forms["loginform"]["usrfield"].value;
                        var passwrdfield=document.forms["loginform"]["passfield"].value;
    
                        if ((usrnamefield==null || usrnamefield=="")||(passwrdfield==null || passwrdfield==""))
                          {
                            document.getElementById('valueerrorlayer').innerHTML ='Username or password field is empty';
                            //document.forms["loginform"]["errorshow"].innerHtml = 'username or password empty';
                          return false;
                          }
                        else return true;
                    }
                </script>
    
        </head>
    
        <body>
    
    
        <form name="loginform" id="loginform" action="https://localhost:8888/login" method="post" onsubmit="return validateForm()">
            <div id = "content" align = "center">
    
                <p align="center"><font size="7">LabelMe Dev</font></p> 
                <br />
                <br />
    
                <label> Please Enter the <b><i>Username</i></b></label>
                <br />
                <br />
    
                <input type="text"  name = "usrfield" id = "usrfield" onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()"/>
                <br />
                <br />
                <br />
    
                <label> Please Enter the <b><i>Password</i></b></label>
                <br />
                <br />
                <input type="password"  name = "passfield" id = "passfield" onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()"/>
                <br />
                <br />
                <br />
    
                <i><p id='valueerrorlayer' style="color:red;"> </p></i>
    
                <input type="submit" value="Submit"/>
            </div>
        </form>     
        </body>
    
    
    
    
    
    </html>
    

    The problem is that console.log(req.session); gives undefined so the req.session.user_id = 'xyz'; also not works and error 'TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:59:24 at callbacks' comes. I have gone through many questions but was not able to figure out.

    My website is static and all the *.html locates in the public directory

  • Zeeshan
    Zeeshan over 10 years
    But when i convert the path to '/' the problem of Trouble using express.session with https occurs which means when i goto localhost:8888 to get the 'loginform.html' the browser continously loads and no result prompts.
  • robertklep
    robertklep over 10 years
    @Zeeshan so what is the exact URL that you enter in your browser to get that HTML file?
  • Zeeshan
    Zeeshan over 10 years
    When I use :. var app = express(); app.use(express.static(__dirname + '/public')); app.use(express.favicon()); app.use(express.urlencoded()); app.use(express.json()); app.use(express.cookieParser()); app.use(app.router); app.use(express.methodOverride()); app.use(express.session({ cookie: { path : '/', httpOnly: false, maxAge : 24*60*60*1000 }, secret: '1234567890QWERT' })); then the routing problem is solved means i am redirected but on post this error occurs TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:72:24 at callbacks
  • robertklep
    robertklep over 10 years
    @Zeeshan that works because you're circumventing the express.session middleware like that. I have no idea why that specifically is causing the problem, because it works for me and also for the people answering your previous question.
  • Zeeshan
    Zeeshan over 10 years
    Ok for using express.session is any prerequisits required to install or its buildin in express 3.4.7 and also the cookie connect.sid is created with some value
  • robertklep
    robertklep over 10 years
    @Zeeshan no prerequisites are required for it to work. By the way, how are you getting an error on line 72 of app.js while you're only posting 58 lines of code in your question? Are you absolutely sure that you're not using any other code that might be causing a conflict or an error?
  • Zeeshan
    Zeeshan over 10 years
    no i am sure it was when i have created a test route in the line 72 and there i was checking. the position o app.use(app.router); also matters if i put before session the express.session is undefined but redirection works good and if i put it after app.use(session) then my page does not redirects
  • Zeeshan
    Zeeshan over 10 years
    I dont know how the error is fixed by changing the browser from mozilla to chrome but it works :D
  • murvinlai
    murvinlai about 10 years
    I have the similar problem. It doesn't work in Chrome but Safari is ok.