Giter Club home page Giter Club logo

connect-redis's Introduction

Build Status npm code-style Downloads

connect-redis provides Redis session storage for Express.

Installation

connect-redis requires express-session to installed and one of the following compatible Redis clients:

Install with redis:

npm install redis connect-redis express-session

Install with ioredis:

npm install ioredis connect-redis express-session

Importing

connect-redis supports both CommonJS (require) and ESM (import) modules.

Import using ESM/Typescript:

import RedisStore from "connect-redis"

Require using CommonJS:

const RedisStore = require("connect-redis").default

API

Full setup using redis package:

import RedisStore from "connect-redis"
import session from "express-session"
import {createClient} from "redis"

// Initialize client.
let redisClient = createClient()
redisClient.connect().catch(console.error)

// Initialize store.
let redisStore = new RedisStore({
  client: redisClient,
  prefix: "myapp:",
})

// Initialize session storage.
app.use(
  session({
    store: redisStore,
    resave: false, // required: force lightweight session keep alive (touch)
    saveUninitialized: false, // recommended: only save session when data exists
    secret: "keyboard cat",
  }),
)

RedisStore(options)

Options

client

An instance of redis or ioredis.

prefix

Key prefix in Redis (default: sess:).

Note: This prefix appends to whatever prefix you may have set on the client itself.

Note: You may need unique prefixes for different applications sharing the same Redis instance. This limits bulk commands exposed in express-session (like length, all, keys, and clear) to a single application's data.

ttl

If the session cookie has a expires date, connect-redis will use it as the TTL.

Otherwise, it will expire the session using the ttl option (default: 86400 seconds or one day).

interface RedisStoreOptions {
  ...
  ttl?: number | {(sess: SessionData): number}
}

ttl also has external callback support. You can use it for dynamic TTL generation. It has access to session data.

Note: The TTL is reset every time a user interacts with the server. You can disable this behavior in some instances by using disableTouch.

Note: express-session does not update expires until the end of the request life cycle. Calling session.save() manually beforehand will have the previous value.

disableTouch

Disables resetting the TTL when using touch (default: false)

The express-session package uses touch to signal to the store that the user has interacted with the session but hasn't changed anything in its data. Typically, this helps keep the users session alive if session changes are infrequent but you may want to disable it to cut down the extra calls or to prevent users from keeping sessions open too long. Also consider enabling if you store a lot of data on the session.

Ref: https://github.com/expressjs/session#storetouchsid-session-callback

disableTTL

Disables key expiration completely (default: false)

This option disables key expiration requiring the user to manually manage key cleanup outside of connect-redis. Only use if you know what you are doing and have an exceptional case where you need to manage your own expiration in Redis.

Note: This has no effect on express-session setting cookie expiration.

serializer

Provide a custom encoder/decoder to use when storing and retrieving session data from Redis (default: JSON.parse and JSON.stringify).

Optionally parse method can be async if need be.

interface Serializer {
  parse(string): object | Promise<object>
  stringify(object): string
}
scanCount

Value used for count parameter in Redis SCAN command. Used for ids() and all() methods (default: 100).

connect-redis's People

Contributors

01231 avatar abhijoshi2k avatar anotherpit avatar bachp avatar chirag04 avatar clement avatar garrensmith avatar iamolegga avatar jakemitchellxyz avatar knoxcard avatar knoxcard2 avatar louischatriot avatar masa-shin avatar mikaturunen avatar msamblanet avatar naholyr avatar nathan818fr avatar pasieronen avatar patriksimek avatar r3wt avatar rudfoss avatar slnpacifist avatar strml avatar stuartpb avatar tj avatar toddself avatar undozen avatar vkartk avatar vodolaz095 avatar wavded avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

connect-redis's Issues

Doesn't throw error if redis isn't found

Currently using this within an express app, with redis installed on localhost. However, when I moved the code to a new server without redis, no errors were thrown, express wrote to console fine as if it was working but didn't respond to any requests.

EPRM, operation node permitted

I just want to test connect-redis out alitle bit, but it doesn't seem to work. My plan is create a server with express then get the request from browser, then store request param value in redis. Below is my code

var express = require('express'),
RedisStore = require('connect-redis');

var app = express.createServer();
app.use(express.cookieParser());
app.use(express.session({
secret: 'something',
store: new RedisStore,
}));

app.get('/', function(req, res){
req.session.token = req.param('token');
console.log(req.session.id);
});

app.listen(4000);

Pretty simple stuff, but it just won't run, it keeps saying "error: redis connection to 127.0.0.1:6379 failed - EPERM, operation not permitted "

improvement: dont require('redis') if client is passed in (which will allow support for haredis)

If you allow the redis client to be passed in, there shouldnt be any need to depend on redis module. Should just require('redis') in a lazy fashion.

ie:

    this.client = options.client || new redis.createClient(options.port || options.socket, options.host, options);

should be

    this.client = options.client || new require('haredis').createClient(options.port || options.socket, options.host, options);

For what its worth : haredis: https://github.com/carlos8f/haredis

example.js ECONNREFUSED

i got this error when i try to run the example.js
any idea why?

muthiafi:connect muthiafi$ node example.js
Connect server started on port 3000

node.js:66
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ECONNREFUSED, Connection refused
at Stream._onConnect (net.js:499:18)
at IOWatcher.onWritable as callback

supply redis params as URL, ร  la redis-url?

I'm hoping @mranney is into this for node_redis itself, but if not...

I'm using Redis via RedisToGo on Heroku and the connection details are supplied as a URL. @ddollar has a very simple node module that handles this already https://github.com/ddollar/redis-url - however it would be nice to handle this in connect-redis directly.

Ideally this would just pass-through to node_redis if we can get issue 243 closed satisfactorily. In the meantime it could use redis-url instead :)

Happy to provide implementation, tests and pull request if this sounds good?

Unexpected token g???

Express
500 SyntaxError: Unexpected token g
at Object.parse (native)
at module.exports.RedisStore.get (/Users/daniel/Fracture/pro/node_modules/connect-redis/lib/connect-redis.js:98:23)
at try_callback (/Users/daniel/Fracture/pro/node_modules/redis/index.js:520:9)
at RedisClient.return_reply (/Users/daniel/Fracture/pro/node_modules/redis/index.js:590:13)
at ReplyParser.RedisClient.init_parser (/Users/daniel/Fracture/pro/node_modules/redis/index.js:263:14)
at ReplyParser.EventEmitter.emit (events.js:88:17)
at ReplyParser.send_reply (/Users/daniel/Fracture/pro/node_modules/redis/lib/parser/javascript.js:283:10)
at ReplyParser.execute (/Users/daniel/Fracture/pro/node_modules/redis/lib/parser/javascript.js:197:22)
at RedisClient.on_data (/Users/daniel/Fracture/pro/node_modules/redis/index.js:476:27)
at Socket. (/Users/daniel/Fracture/pro/node_modules/redis/index.js:79:14)

question: does connect-redis store sessions first in / first out?

I'm sorry if this is a dump question, I'm new to redis, I use it as the session store for an express.js app.

My redisdb is hosted on redistogo.com, and I wonder what happens when my db is full and another session comes in. Will the oldest session be replaced with the new one?

Callbacks should be moved outside of try-blocks

There are several places where callbacks are called inside try-blocks. This makes errors further in the chain dangerous and difficult to notice, as they will cause the catch block to fire an errback in some spurious moment. There is issue #37, but the fix there is quite noisy and so may have hidden the intention here.

default usage appers to throw error in crypto.js for current versions of connect, express and connect-redis

TypeError: Not a string or buffer
at Object.createHmac (crypto.js:129:21)
at Object.sign (/Users/alz/Sites/virtual-environments/pictonic/node_modules/connect/lib/utils.js:137:6)
at Object.serialize (/Users/alz/Sites/virtual-environments/pictonic/node_modules/connect/lib/middleware/session/cookie.js:115:17)
at ServerResponse.writeHead (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/node_modules/connect/lib/middleware/session.js:264:46)
at ServerResponse._implicitHeader (http.js:808:8)
at ServerResponse. (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/node_modules/connect/lib/middleware/session.js:278:31)
at next (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/node_modules/connect/lib/http.js:173:13)
at pass (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/lib/router/index.js:219:24)
at Router._dispatch (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/alz/Sites/virtual-environments/pictonic/node_modules/express/lib/router/index.js:45:10)

i believe this is a similar issue to http://stackoverflow.com/questions/9488568/node-js-session-with-infinite-loop

Throws segfault in 0.6.0

This works in my 0.4.x installs, but not in 0.6.0 - latest versions on all these modules.

> var express = require('express');
undefined
> var RedisStore = require('connect-redis')(express);
undefined
> var lol = new RedisStore();
undefined
> [1]    15285 segmentation fault  node

pic:

connect redis segfault

I don't have much more info.

OS X Lion - redis/hiredis is installed. redis is running on default port.

Cannot call method 'toString' of undefined

I have gotten redis to store cookie data and have checked the key / value with redis-cli. Now it is acting up, so it has worked before.

I am using the connect-redis module for my express.session() store and I am getting this error both locally and on my live server. Both production (aws) and development (local) servers have their own install of redis running locally 127.0.0.1:6379. What seems to be the problem?

/Users/thomas/Desktop/project/node_modules/connect-redis/node_modules/redis/index.js:525
            throw err;
                  ^
TypeError: Cannot call method 'toString' of undefined
    at ServerResponse.writeHead (http.js:980:45)
    at ServerResponse.res.writeHead (/Users/thomas/Desktop/project/node_modules/express/node_modules/connect/lib/patch.js:75:22)
    at ServerResponse._implicitHeader (http.js:931:8)
    at ServerResponse.OutgoingMessage.end (http.js:766:10)
    at ServerResponse.module.exports.res.end (/Users/thomas/Desktop/project/node_modules/express/node_modules/connect/lib/middleware/logger.js:148:13)
    at res.end (/Users/thomas/Desktop/project/node_modules/express/node_modules/connect/lib/middleware/session.js:282:13)
    at module.exports.RedisStore.set (/Users/thomas/Desktop/project/node_modules/connect-redis/lib/connect-redis.js:130:18)
    at try_callback (/Users/thomas/Desktop/project/node_modules/connect-redis/node_modules/redis/index.js:522:9)
    at RedisClient.return_reply (/Users/thomas/Desktop/project/node_modules/connect-redis/node_modules/redis/index.js:592:13)
    at RedisReplyParser.RedisClient.init_parser (/Users/thomas/Desktop/project/node_modules/connect-redis/node_modules/redis/index.js:265:14)
7 Dec 12:17:00 - [nodemon] app crashed - waiting for file changes before starting...

Here's some sample code

var  RedisStore = require('connect-redis')(express)
  , store = new RedisStore();

app.use(express.session({"store":store, "secret": config.session.secret }));

not passing test.js for me

node.js
thow e; //process.nextTick error, or 'error' event in first tick

TypeError: Cannot read property 'prototype' of undefined
it refers to connect-redis.js 32:39

when running test.js

Any ideas.

minimize redis commands when using RedisStore / connect-redis as SessionStore

When i am watching the commands in the redis-cli via the MONITOR command, i can see that there are at least 11 commands on a single requests.
I have RedisStore configured as described in the expressjs documentation. I am not storing any information in the session. I am not calling session.save() or redisStore.set or something.
The only thing i do is on a valid login i store the use object in the store, but the logs beneath came from the request to the login page.

    1319547230.129921 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"
    1319547230.135155 "setex" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs" "14400" "{\"lastAccess\":1319547230130,\"cookie\":{\"originalMaxAge\":14400000,\"expires\":\"2011-10-25T16:53:50.135Z\",\"httpOnly\":true,\"path\":\"/\"},\"error\":\"Access denied\"}"
    1319547230.193424 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"
    1319547230.194347 "setex" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs" "14400" "{\"lastAccess\":1319547230193,\"cookie\":{\"originalMaxAge\":14400000,\"expires\":\"2011-10-25T16:53:50.194Z\",\"httpOnly\":true,\"path\":\"/\"},\"error\":\"Access denied\"}"
    1319547230.194826 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"
    1319547230.195936 "setex" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs" "14400" "{\"lastAccess\":1319547230195,\"cookie\":{\"originalMaxAge\":14400000,\"expires\":\"2011-10-25T16:53:50.195Z\",\"httpOnly\":true,\"path\":\"/\"},\"error\":\"Access denied\"}"
    1319547230.196972 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"
    1319547230.197591 "setex" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs" "14400" "{\"lastAccess\":1319547230197,\"cookie\":{\"originalMaxAge\":14400000,\"expires\":\"2011-10-25T16:53:50.197Z\",\"httpOnly\":true,\"path\":\"/\"},\"error\":\"Access denied\"}"
    1319547230.198899 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"
    1319547230.199500 "setex" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs" "14400" "{\"lastAccess\":1319547230199,\"cookie\":{\"originalMaxAge\":14400000,\"expires\":\"2011-10-25T16:53:50.199Z\",\"httpOnly\":true,\"path\":\"/\"},\"error\":\"Access denied\"}"
    1319547230.685981 "get" "sess:bhoT0peGyfFibks5uyilSWxU.fgnTjTqX3661xn5eRIwzEm4s1vQTTEJKX5mcTmBSROs"

It would be great to minimize the amount of commands to a very minimum. Maybe batching and caching some data, or maybe the SessionStore does some unnecessary commands anyway.
What do you think?

Redis version

I've spent 2 hours figuring out why sessions do not work. In the end I found that SETEX command isn't supported by my redis server.

On the project page there is info that redis >= 1.3.0 is required, however on the redis website different info. http://redis.io/commands/setex - "since 2.0.0"

May be it is a good idea to pass an error (if it occurs) with the callback?

incorrect number online ?

Hi

I set { maxAge: 1000 } in example.js.

It seems that the number online is always increasing (on page refresh):

online : 13

views: 1

My guess is that the expire in the redis is not working correctly ?

atomic session update

Hey guys,

I am trying to manage uploads through sessions, so for every uploaded file, a new entry will be made in the req.session object. Since i support concurrent uploads, if i just do req.session.photos[photo.id] = photo; req.session.save(); There could possibly be race conditions since the updates are not atomic (where a later save would just override the earlier req.session.photos object)

can someone enlighten me whether it is possible to get atomic updates (since redis does support atomic update)?

Thanks a lot :)

Jason

use a hash instead

can't think of any immediate reason not to, it would be faster as well as less clutter, easier to manage etc

Race conditions

The situation is following. There are two HTTP requests, one is fast the other is slow. Then we have following

  1. slow request came
  2. fast request came
  3. fast request added session field
  4. fast request finished and saved session
  5. slow request finished and also saved session

The problem is that slow request stores session data erasing the fast request session data that already written. That's the evil race conditions that are inevitable.

Are there any ideas of how to prevent erasing sessions data by "long-poll" requests? Current sessions are very unfriendly to long polls

odd issues

Hi

I'm using this lib to store session data in the latest express as a RedisStore.

If I log in with 'bobby', and then log out and log in as 'weepy', it sometimes seems to forget somewhere along the way and revert back.

The sessionID appears to be similar. The redis store seems to tally with this (i.e. the sessionID key gives a value which changes).

hrm - sorry I can't be more specific.

Deprecated documentation on main page

Hi TJ,

Example code is deprecated now. You should replace cookieDecoder with cookieParser:

var connect = require('connect')
      , RedisStore = require('connect-redis');

connect.createServer(
  connect.cookieParser(),
  // 5 minutes
  connect.session({ store: new RedisStore })
)

Express session store gives failed - connect ECONNREFUSED

Following the example on express.js docs and repeated here, running on local ubuntu vm

var RedisStore = require('connect-redis')(express);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));

I get
Express server listening on port 3000 in production mode [Error: Redis connection to 192.168.68.129:3001 failed - connect ECONNREFUSED]

Any ideas?

how can I handle error event in connect-redis?

how can I handle error event in connect-redis?
from node-redis readme:
"client will emit error when encountering an error connecting to the Redis server. Note that "error" is a special event type in node. If there are no listeners for an "error" event, node will exit."

Please add a license.

Hey TJ,

I assume this library is MIT as that is what your other libraries are published under, but it would be nice to get confirmation.

thanks,
Brock

Usage Examples

Can you provide an example of how to write and get session variables?

Cannot Authenticate Redis Connection

this is the error I am receiving:
TypeError: Object # has no method 'auth'

this is the code producing the error:

var session_store = new redis_store({ 
    maxAge: 60000 * 60 * 24 * 28,
    reapInterval: 60000 *60 * 24 * 7,
    host: settings.redis_host,
    port: settings.redis_port,
    }) 

var redisAuth = function() { session_store.client.auth( settings.redis_pass ); sys.puts('connected to redis'); }
session_store.client.addListener('connected', redisAuth);
session_store.client.addListener('reconnected', redisAuth);
redisAuth();

Cannot read property 'session' of undefined

Hi,

I'm getting this error when trying to run my server.js file:

node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'session' of undefined
at new (/root/node-v0.4.7/node_modules/connect-redis/lib/connect-redis.js:34:22)
at Object. (/var/www/gamersband/library/node/server.js:11:23)
at Module._compile (module.js:404:26)
at Object..js (module.js:410:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at Array. (module.js:423:10)
at EventEmitter._tickCallback (node.js:126:26)

I was previously working on dev environment and never had this issue. It appeared when I put the whole thing on the production server. I don't know what's going on, any idea on what could cause this?

Thx

Session gets regenerated automatically if db number is not 0

Hello,

I am using express and connect's middleware session to manage my sessions. I chose a Redis store and would like to use connect-redis to use it with connect-session. Everything works fine if I use the following Redis Store:

var redisStore = new RedisStore({ host: "localhost"
                                , port: "6379"
                                , db:"0"
                                });

But if I want instead to use the following config, the session gets automatically regenerated at every request, so the session data is reinitialized every time:

var redisStore = new RedisStore({ host: "localhost"
                                , port: "6379"
                                , db:"9"   // Any value that's not 0
                                });

Am I the only one experiencing this issue? Thanks in advance,
Louis

Precision: the correct Redis DB gets used. But if it is any DB that's not 0, every page refresh creates a new key/value pair corresponding to a new session.

Update Array of Type Mixed

Hi,

i'm currently trying to save an array of Informations inside a Log entry, but i just cant get it to work i want to lock the max Infomation saved to 20 rows, but it jsut doesnt work it just saves the new one... help please xD

here is my model:

var log = new mongoose.Schema({
    Info: Array,

    Type: {
        type:      String,
        "default": "undefined"
    },

    Class: {
        type:      String,
        "default": "undefined"
    },

    Message: {
        type:      String,
        "default": "undefined"
    },

    Counter: {
        type:      Number,
        "default": 0
    },

    Last: {
        type:      Date
    }
});

here is my code where i update:

logModel.findOne({
    Message: newEntry.Message
}, function (err, doc) {
    if ( doc ) {
        // This should lock the max length to 20 ...
        if(doc.Info.length > 20) {
            while(doc.Info.length >= 20) {
                doc.Info.shift();
            }
        }
        // add the new one...
        doc.Info.push(newEntry.Info[0]);
        doc.Counter++;
        doc.Last = newEntry.Info[0].Date;

        // mark modified
        doc.markModified("Info");
        doc.save(function (err, newdoc) {
            console.log(doc.Info.length, newdoc.Info.length);
            console.timeEnd('Processed Log Entry ' + currentNumber + '/' + data.length);
            callback();
        });
    } else {
        newEntry.Last = newEntry.Info[0].Date;
        newEntry.save(function (err) {
            console.timeEnd('Processed Log Entry ' + currentNumber + '/' + data.length);
            callback();
        });
    }
});

Simply not working.

I've upgraded from Express 2.x to 3.x and now it seems like my real-time dnode stuff isn't working. It turns out that it has to do with the connect-redis module.

Beginning of app.js:

require('./globals');
var yarn = require('yarn');
var url = require('url');

var browserify = require('browserify');
var browserijade = require('browserijade');

var express = require('express');

var app = module.exports = express();
var server = app.listen(8003);

var RedisStore = require('connect-redis')(express);
global.sessionStore = new RedisStore(global.config.redis.options);//global.sessionStore = new express.session.MemoryStore();


// App Configuration

app.configure(function(){
    app.engine('ejs', require('ejs-locals'));
    app.set('views', __dirname + '/views');

    app.locals.open = '<?';
    app.locals.close = '?>';

    app.use(express.static(__dirname + '/public'));
    app.use(express.cookieParser('foo bar baz'));
    console.log(express.session);
    app.use(express.session({
        secret:'foo bar baz',
        store: global.sessionStore,
        cookie: {
            httpOnly: false,
            maxAge: false
        }
    }));
    app.use(express.bodyParser({uploadDir: __tempdir}));
    app.use(browserify(__dirname + '/public/scripts/base.js', {
            debug: true,
            watch: true
        })
        .use(browserijade(__dirname + '/views')));

parts of sock.js:

var shoe = require('shoe');
var dnode = require('dnode');
var Session = require('express').session.Session;

// Event emitter for this controller
var events = require('events');
var emitter = new events.EventEmitter;


// Array of connected clients (browsers)
var clients = [];

// Map of array of functions, that restrict event listening access, to an event name
var eventRestrictions = {};


var controller = module.exports = function(server){
    sock.install(server, '/sock');
};

var sock = shoe(function(stream){
// ...
// Allows clients to authenticate using the express sessionId (cookie) through dnode
server.authenticate = function(sessionId, cb){
    global.sessionStore.get(sessionId, function(err, session){
        if (err) return;// cb(err);

        if (!session)
            return;// cb(new Error('no session data'));

        // Express session
        var session = new Session({
                session: session,
                sessionId: sessionId,
                sessionStore: global.sessionStore
            }, session);

        // Map the session to the sessionId
        sessions[sessionId] = session;

        if (session.user)
        {
            var userId = session.user.userId;

            controller.emit('user.'+userId+'.status', true);

            // Map the sessionId to the userId
            sessionIds[userId] = sessionId;
        }

        // Attach session data to the client object
        client.sessionId = sessionId;
        client.session = session;

        cb(session);
    })
}
// ...

Basically what's happening is the authentication function is exposed to client through dnode. The cb argument is never invoked for the client. Inspecting using node-inspector, I find that global.sessionStore.get doesn't invoke it's second argument. This is obviously a bug then, because it should work.

[SOLVED] - Problem in Ubuntu 10.04 (package version doesn't have setex command)

Hi,

I was trying to test connect-redis in a machine running Ubuntu 10.04. Obtained a install of Redis from the available package:

$ apt-get install redis-server

Don't !!.. I spent i couple of hours debugging the library in order to know why I couldn't store the sessionId. The reason is simple, the library uses the comand setex [mykey] [value], which is not available in the version of redis from the ubuntu package.

So, what you can do? simple, uninstall that package! (or do not install it), and compile the version from the website redis.io (currently the version is 2.2.5), this would work.

The reason I'm writing this "issue" is, so you could add it in the README, in order to save someone else from my "couple-hours-failure".

Thanks in advance.

Enable logging

It would be nice to enable logging messages for my development environment so I can see values in redis selected, inserted, and destroyed. I notice there are a lot of debug(...) statements, but I don't believe these print to the console.

Define connect deps in package.json

Currently, I get the following error after doing an npm install connect-redis, and using store: new RedisStore in my app.js:

node.js:134
throw e; // process.nextTick error, or 'error' event on first tick

^

Error: Cannot find module 'connect'
at Function._resolveFilename (module.js:320:11)
at Function._load (module.js:266:25)
at require (module.js:348:19)
at Object. (/Users/rakesh/Projects/asdf/node_modules/connect-redis/lib/connect-redis.js:12:13)
at Module._compile (module.js:404:26)
at Object..js (module.js:410:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at require (module.js:348:19)
at Object. (/Users/rakesh/Projects/asdf/node_modules/connect-redis/index.js:2:18)

It seems like the error is because require("connect") is used in connect-redis, but it isn't found because I haven't npm installed connect with -g (global install). It's the connect I got with the express deps that's being used.

Report specific error if Redis isn't running

I just spent about 2 hours debugging code that wasn't broken because I kept getting req.session.foo was undefined as an error when trying to access that property in some random middleware I was working on with Express.

I wrote the code like 5 different ways and kept getting the error. Then after an exhaustive 2 hours I thought myself, "what else can it be... imagine if I forgot to start the Redis server?".

Yeah, of course I forgot to start it heh. As soon as I started it then everything worked perfectly.

My recommendation is if you fail to connect to Redis it should throw a specific error. An undefined property error when trying to use session properties requires thinking to pin point the problem. An error such as "Hey moron, is your Redis server running?" would have saved me a lot of time.

Express Guide for redis connect seems to be no longer valid.

Following http://expressjs.com/guide.html#session-support I started with

var express = require('express');
var RedisStore = require('connect-redis')(express);
console.log("REDIS:" + RedisStore);

ps. it also fails when doing the 'new RedisStore' like with TypeError: undefined is not a function but figure that's not as important cause it's already null.
However get 'REDIS:undefined' and can't move forward. Using just 'var RedisStore = require('connect-redis')' it doesn't complain but sessions are not stored. Am I doing something wrong or is the doc out of date both on connect-redis github and express' guide?

Is connect-redis affected by the change to connect-v0.5.5 secret thing

this one:
session() middleware requires the "secret" option string for security

I tried adding a key: secret object like so:
app.use(express.session({key: 'k33k33', secret: 'superSecret!', store: new RedisStore}));

but still get the error. Would that be correct? Note that that I didn't have this error until I tried running my app on joyent's no.de.

should have option to select a particular keyspace

e.g.

var RedisStore = module.exports = function RedisStore(options) {
    options = options || {};
    Store.call(this, options);
    this.client = new redis.createClient(options.port, options.host, options);
    this.client.select(options.keyspace || 0)  // <======== here
};

Where to pass in options as listed in readme?

How to pass in options as listed in readme such as db, port, host...

I normally use it as RedisStore = require('connect-redis')(express) and don't know how to configure the server with options.

touch session only on save && changes detect

Hi, I use redis session for short requests and socketio long connections together on different nodes.
For my task I am reload session on sockeit clients on subscribe event from redis. But send events and reload on every rquest is bad way...

For this I must change code for detect session changes after create(first read from store), and if NO changes make by request just touch session age. And if have changes update session in store and publish message with update session id.

Will be good to add this feature ( modify detect and touch only if no changes maken )

Connect-redis and Express 3.x

Hello,

I just upgraded to express 3.0.0beta2. I have implemented sessions like this:

var RedisStore = require('connect-redis')(express);
app.sessionStore = new RedisStore({port : config.redis_port, host: config.redis_host, pass: config.redis_pass});
app.use(express.session({
    secret: "cookie",
    store: app.sessionStore,
    cookie: {
        maxAge: 14400000
    }
}));

Later in my app, I was able to do app.sessionStore.get('sid', function(err, session){});. This is now always returning undefined for session and err.

Is there a new way to lookup session data outside of req.

Thank you!

RedisStore session and Socket.IO

Hi, I'd like to use redis as persistent sessionStore inside Socket.IO, probably I'm missing something because if I write the sessionStore from inside socket.io it is written in the memory store and not in redis.

some code parts:

express    = require 'express'
http       = require 'http'
redis      = require 'redis'
connect    = require('connect')
RedisStore = require('connect-redis')(express)

SessionSockets = require('session.socket.io')

app = module.exports = express()
app.set('port', 3000)
server = app.listen app.get('port')
io = require('socket.io').listen server

cookieParser = express.cookieParser('your secret sauce2')

# Redis as sessioStore
sessionStore = new RedisStore


sessionSockets = new SessionSockets(io, sessionStore, cookieParser)

sessionSockets.on "connection", (err, socket, session) ->

# ..
  socket.on "ping", (data) ->

    # Doesn't work, counter IS NOT saved in redis
    if session.counter
      ++session.counter
    else
      session.counter=1

    console.log '@sess2: '+JSON.stringify session


app.get "/test", (req, res) ->
  body = ""
   # Works, view IS saved in redis
  if req.session.views
    ++req.session.views
  else
    req.session.views = 1
    body += "<p>First time visiting? view this page in several browsers :)</p>"
  res.send body + "<p>viewed <strong>" + req.session.views + "</strong> times.</p>"

The connect.sid session is in redis but "counter" is in memorystore I think

redis 127.0.0.1:6379> get sess:o0wxRV+ykXOIxT3FNwsIG9OX
"{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"}}"

see also:
wcamarao/session.socket.io#2 (comment)

Redis hangs up every 2 hours

We've recently set up JSLogger to use a Redis machine on Redis4you. We are using it on NodeJS for sessions with connect-redis middleware and ExpressJS.
Everything seemed to work fine, except that we get some connection problems each 2 or 3 hours that breaks the Node server. This is the log:

/home/jslogger/jslogger/node_modules/connect-redis/node_modules/redis/index.js:525
            throw err;
                  ^
Error: socket hang up
    at createHangUpError (http.js:1360:15)
    at ServerResponse.OutgoingMessage._writeRaw (http.js:507:26)
    at ServerResponse.OutgoingMessage._send (http.js:476:15)
    at ServerResponse.OutgoingMessage.end (http.js:887:18)
    at res.end (/home/jslogger/jslogger/node_modules/express/node_modules/connect/lib/middleware/session.js:281:15)
    at module.exports.RedisStore.set (/home/jslogger/jslogger/node_modules/connect-redis/lib/connect-redis.js:130:18)
    at try_callback (/home/jslogger/jslogger/node_modules/connect-redis/node_modules/redis/index.js:522:9)
    at RedisClient.return_reply (/home/jslogger/jslogger/node_modules/connect-redis/node_modules/redis/index.js:592:13)
    at RedisReplyParser.RedisClient.init_parser (/home/jslogger/jslogger/node_modules/connect-redis/node_modules/redis/index.js:265:14)
    at RedisReplyParser.EventEmitter.emit (events.js:96:17)

I've got the same issue with Redis on a machine at RedisToGo. The guys that provide the server have no clue why would this happen. They got some similar issues before for a PHP project. The found an workaround for that by surrounding the PHP code with a try catch block:

try{
   while(true){
       do_stuff_with redis();
   }
}catch(Exception $e){
    reconnect();
}

Unfortunately, I can not apply the same workaround for my Node project.

They also suspect that it might be a problem with the older Redis versions as for Redis 2.6 there is an option for disconnecting clients who are idle.

Did someone else had this issue before? Is there a fix for it? Is it fixed in Redis 2.6?

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.