Access Redis inside Route Handler in Express 2.x
Solution 1:
Easiest Solution
You probably have a require() function that includes a redis lib in your app.js. Just take that line and add it to the top of your index.js file.
if you are using the node_redis module, simply include this:
var redis = require("redis"),
client = redis.createClient();
Alternative Approach
If you are looking to reuse the existing connection, try passing the client
variable to the function in index.js:
app.js
app.post('/signup', routes.myroute(client));
index.js
exports.myroute = function(client) {
// client can be used here
}
Solution 2:
You are using Express, and thus Connect, so make use of Connect middleware. Particularly the session middleware. Connect's session middleware has the concept of a store (somewhere to store session stuff). That store can be in memory (default) or in a database. So, use the redis store (connect-redis).
var express = require('express'),
RedisStore = require('connect-redis')(express),
util = require('util');
var redisSessionStoreOptions = {
host: config.redis.host, //where is redis
port: config.redis.port, //what port is it on
ttl: config.redis.ttl, //time-to-live (in seconds) for the session entry
db: config.redis.db //what redis database are we using
}
var redisStore = new RedisStore(redisSessionStoreOptions);
redisStore.client.on('error', function(msg){
util.log('*** Redis connection failure.');
util.log(msg);
return;
});
redisStore.client.on('connect', function() {
util.log('Connected to Redis');
});
app = express();
app.use(express.cookieParser());
app.use(express.session({
store: redisStore,
cookie: { path: '/',
httpOnly: true, //helps protect agains cross site scripting attacks - ie cookie is not available to javascript
maxAge: null },
secret: 'magic sauce', //
key: 'sessionid' //The name/key for the session cookie
}));
Now the Connect session magic will put session details on the 'req' object that is passed into every route. This way, you dont need to pass the redis client around all over the place. Let the req object work for you, cause you get it for free anyway in each route handler.
Make sure you do an: npm install connect-redis