Why won’t req.session set with node.js

Why won’t req.session set with node.js


I can’t seem to get set anything for


I’m trying to store oauth token and the secret into a session so i can check them after the authorize callback. Here is my code

var express = require('express'),
    app     = express(),
    server  = require('http').createServer(app),
    io      = require('socket.io').listen(server),
    oauth   = require('oauth'),
    tumblr  = require('tumblr.js'),
    client  = {
        consumer_key: '1n9fMPxCBFBbcIGRImYKSK5wwDL6yux64S4DxEwiwzHTNuaIoD',
        consumer_secret: 'bW9YKbnwgxexyVx1AaxQr1QoemEkjd29p5U1WpbZ8r1XEH41C0'
    consumer = new oauth.OAuth(
        "http://www.tumblr.com/oauth/request_token", "http://www.tumblr.com/oauth/access_token",
        client.consumer_key, client.consumer_secret, "1.0A", "", "HMAC-SHA1");


app.configure('dev', function(){
    app.use(express.session({ secret: "topsecret" }));

app.get('/home', function(req, res){
    consumer.getOAuthRequestToken(function(err, oauth_token, oauth_token_secret, results){
            //req.session.oauth.token = oauth_token;
            console.log('oauth.token: ' + oauth_token);
            //req.session.oauth.token_secret = oauth_token_secret;
            console.log('oauth.token_secret: ' + oauth_token_secret);

app.get('/oauth/testapp', function(req, res){

When I uncomment

req.session.oauth.token = oauth_token;

I get an error “cannot read property ‘oauth’ of undefined” also req.session displays undefined in the console.

Problem courtesy of: Josh Bedo


You’re trying to set the property token on an object oauth on the session. If the oauth object is not initialized, it will be undefined, and you can’t set the token attribute. You first need to initialize the oauth object in the session. You could for instance do

req.session.oauth = {token: theToken}

This will create an object in the session and also set the token property of that object.

@robertklep figured out the other half of the solution: Make sure you’re running with the correct environment. Since you have used dev in app.configure, you have to run node with NODE_ENV=dev for the configuration to be applied.

Solution courtesy of: NilsH


Leave a Reply

Your email address will not be published. Required fields are marked *