Home

Awesome

connect-redis-sessions

Build Status Windows Tests Dependencies Status NPM version

Is a connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.

Example

// get the modules
var express = require( "express" );
var cookieParser = require( "cookie-parser" );
var ConnectRedisSessions = require( "connect-redis-sessions" );
var app = express();


// configute express
app
	.use( express.query() )
	.use( cookieParser() )
	.use( ConnectRedisSessions( { app: "myappname" } ) )

// listen for requests
app.use( function( req, res ){
	if( req.query.login ){
		// upgrade a session to a redis session by a user id
		req.session.upgrade( req.query.user_id );
	}
	if( req.sessin.id && req.query.logout ){
		// kill the active session
		req.session.destroy();
	}
	res.end( "Hello express redis sessions" );
});

Installation

npm install connect-redis-sessions

Usage

  1. you have to get the express middleware init method by var ConnectRedisSessions = require( "connect-redis-sessions" );
  2. init your express or express server var app = require( "express" )();
  3. init the express cookie parser app.use( express.cookieParser() );
  4. use express redis sessions as middleware app.use( ConnectRedisSessions( { app: "myappname" } ) );

<span style="color:red">Attension:</span> If you're using Express < 4.x then please use version 0.x otherwise use version 1.x of connect-redis-sessions. It schould work with connect and the older Express, but there could be eventual issues due to the new Express 4.x api behaviour i haven't found yet.

Initialisation

ConnectRedisSessions( options )

To init the session handling just add the options object as argument.

Options

_getAppName = function( req, callback ){ callback( null, "staticname" ) };

Session Object

After you have initializes the session handling every connect/express request object will contain a key called session. Within this Object you cann save rudimental keys of types String, Number and Boolean. These keys will be saved at the end of the request and will be availible within the next request.

And there are some additional methods and metadata

Properties

Methods

req.session.upgrade( user_id [, ttl ][, cb] )

upgrade a empty session to a real redis session by upgrading the session with the user_id.

Arguments

req.session.soid( [ dt,] cb )

Get all session of the logged in id.

Arguments

req.session.soapp( [ dt,] cb )

Get all session of an app.

Arguments

req.session.activity( [ dt,] cb )

Query the amount of active session within the last 10 minutes (600 seconds).

Arguments

req.session.destroy( [ cb ] )

Kill the current active session

Arguments

req.session.destroyall( [ cb ] )

Kill ALL session of the given user_id.

Arguments

req.session.save( [ cb ] )

Changed session data will allways be saved at the end of a request. But with this method you can force the saving of the session object to redis-sessions.

Arguments

req.session.reload( [ cb ] )

Reload the session from redis sessions

Arguments

req.session.getRedisSessionsModule()

Will return the internal instance of RedisSessions. You can use this to handle sessions of other users.

Returns

( RedisSessions ): The raw redis sessions module.

Examples

advanced init

// get the modules
var express = require( "express" );
var cookieParser = require( "cookie-parser" );
var bodyParser = require( "body-parser" );
var logger = require( "morgan" );
var ConnectRedisSessions = require( "connect-redis-sessions" );
var app = express();

// get the appname by the first part of the url
var _getAppName = function(req, cb) {
	var appname;
	appname = req._parsedUrl.pathname.split("/")[1];
	if (appname != null) {
		cb(null, appname);
	} else {
		// if nothing is returned a empty session will be availible
		cb(null);
	}
};

fnCRS = ConnectRedisSessions( { app: _getAppName, ttl: _timeSecDay, cookie: { maxAge: _timeSecDay * 1000 } } );

// configute express
_timeSecDay = 60 * 60 * 24
app
	.use( logger( "dev" ) )
	.use( express.query() )
	.use( bodyParser() )
	.use( cookieParser() )
	.use( fnCRS )


// an example how to get the internal redis-sessions instance out of the connect-redis-sessions module
redisSessionsInstance = fnCRS.handler.rds;

// listen for requests
app.use( function( req, res ){
	console.log( req.session );/*
		{
			"id": null,
			"d": {}
		}
	*/
	res.end( "no knwon user" );
});

check for a logged in user

// listen for requests
app.use( function( req, res ){
	if( req.session.id == void( 0 ) ){
		res.end( "user not logged in" );
	} else {
		res.end( "user " + req.session._meta.id + " is logged in" );
	}
});

upgrade a session with a user_id

// listen for requests
app.use( function( req, res ){
	var user_id = "myuser_id" // code to get your user_id 
	req.session.upgrade( user_id, req.query.sessionttl, function(){
		console.log( req.session );/*
			{
				"id": "myuser_id",
				"d": {},
				"_meta": {
					"id": "myuser_id",
					"r": 1,
					"w": 1,
					"ttl": 86400,
					"idle": 0
				}
			}
		*/
		res.end( "user " + user_id + " has logged in" );
	}); 
});

write data to the session

// listen for requests
app.use( function( req, res ){
	req.session.meaning = 42;
	req.session.foo = "bar";
	console.log( req.session );/*
		{
			"id": "myuser_id",
			"meaning": 42,
			"foo": "bar",
			"d": {
				"meaning": 42,
				"foo": "bar"
			},
			"_meta": {
				"id": "myuser_id",
				"r": 2,
				"w": 1,
				"ttl": 86400,
				"idle": 10
			}
		}
	*/
	res.end( "data written to session" );

});

read data out of a session

// listen for requests
app.use( function( req, res ){
	res.end( "session data " + req.session.foo + " says " + req.session.meaning );

});

get all active user sessions

// listen for requests
app.use( function( req, res ){
	req.session.soid( function( err, sessions ){
		if( err ){
			res.end( "ERROR" );
			return
		}
		res.end( JSON.stringify( sessions ) );/*
			[{
				id: 'myuser_id',
				r: 3,
				w: 2,
				ttl: 86400,
				idle: 10
			},
			{
				id: 'myuser_id',
				r: 1,
				w: 1,
				ttl: 7200,
				idle: 56040
			}] 
		*/
	});
});

kill a session

// listen for requests
app.use( function( req, res ){
	req.session.destroy()
});

Release History

VersionDateDescription
v2.0.02018-12-10updated deps + removed support for node < 6
v1.3.22016-07-26Fixed #13 to prevent error output invalidValue: d
v1.3.12016-07-26Fixed configurations of automated tests by travis and appveyor
v1.3.02016-07-25Updated dev env. and added mocha tests
v1.2.02014-11-28Added ttl to upgrade method + Issues by thynson
v1.0.32014-09-11Added return of sessionhandler object on initialisation
v1.0.22014-04-25Small bugfix for cookie handling
v1.0.12014-03-17Updated readme with external express/connect middleware
v1.0.02014-03-17fixed cookie set for express 4.x
v0.2.02014-03-07express 0.4.0 support
v0.1.52013-12-04Added method SessionObject.getRedisSessionsModule() to receive the internal redis session instance
v0.1.42013-11-20Fixed No d supplied error on upgrade
v0.1.32013-10-15Fixed error on missing callback
v0.1.22013-10-15Added example check for a logged in user to readme
v0.1.12013-10-15Fixed module to be compatible with express and changed readme examples from connect to express
v0.1.02013-10-04Initial commit

Related Projects

NameDescription
redis-sessionsThe redis session module this middleware module is based on
tcs_node_authAuthentication module to handle login and register with a integrated mail double-opt-in logic.

downloads

Other projects

NameDescription
node-cacheSimple and fast NodeJS internal caching. Node internal in memory cache like memcached.
rsmqA really simple message queue based on redis
redis-heartbeatPulse a heartbeat to redis. This can be used to detach or attach servers to nginx or similar problems.
systemhealthNode module to run simple custom checks for your machine or it's connections. It will use redis-heartbeat to send the current state to redis.
rsmq-clia terminal client for rsmq
rest-rsmqREST interface for.
nsq-loggerNsq service to read messages from all topics listed within a list of nsqlookupd services.
nsq-topicsNsq helper to poll a nsqlookupd service for all it's topics and mirror it locally.
nsq-nodesNsq helper to poll a nsqlookupd service for all it's nodes and mirror it locally.
nsq-watchWatch one or many topics for unprocessed messages.
connect-redis-sessionsA connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.
redis-notificationsA redis based notification engine. It implements the rsmq-worker to safely create notifications and recurring reports.
hyperrequestA wrapper around hyperquest to handle the results
task-queue-workerA powerful tool for background processing of tasks that are run by making standard http requests
soyerSoyer is small lib for server side use of Google Closure Templates with node.js.
grunt-soy-compileCompile Goggle Closure Templates ( SOY ) templates including the handling of XLIFF language files.
backlunrA solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js
domelA simple dom helper if you want to get rid of jQuery
obj-schemaSimple module to validate an object by a predefined schema

The MIT License (MIT)

Copyright © 2013 Mathias Peter, http://www.tcs.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.