I am using npm subdomain, inside my app I have routes that fake a subdomain
// looks like app.localhost:3000
router.get('/subdomain/app', app.dashboard);
So I have a login page on a subdomain and a login page on a non subdomain page. They don't share sessions, so I have to login twice. I want to setup redis, but I don't know how.
// here is my session middleware, I tried using .localhost
app.use(session({ secret: 'something', domain: '.localhost', }));
I have seen where people are using redis like
app.use(express.session({
store:new RedisStore({
host: config.redis.session.host,
port: config.redis.session.port,
db: config.redis.session.db
}),
secret: config.session_secret
}));
This seems like it could solve my issue but I have no clue how to setup a redisStore and where the config data comes from?
Can someone explain to me how to use redis so that when a user logs in on either app.example.io or example.io that he/she is logged in for good, no need to log in twice?
You need to require following modules.
connect-redis
express-session
cookie-parser
Then use the following sample code:
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser());
app.use(session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379})
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Source : How to save and retrieve session from Redis
Here is how I did it, this is the most important piece - domain: .yourdomain.io Make sure to have that preceeding dot before your domain.
var express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
sessionMiddleware = null,
redis = require('redis'),
conn_redis = {
path: '/var/run/redis/redis.sock',
socket_keepalive: true
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const connectRedis = require('connect-redis')(expressSession),
uid = require('uid-safe').sync
sessionMiddleware = expressSession({
store: new connectRedis(conn_redis),
secret: 'xxxxxxxxxxxxxxxxxxxxx',
name: 'session_name',
resave: false,
rolling: true,
saveUninitialized: false,
logErrors: true,
cookie: {
path: '/',
domain: '.yourdomain.io'
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
}
})
Related
Can't seem to figure out how to use redis store for sessions with Express 4, some sample code looks like:
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(cookieParser());
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379,
}),
secret: 'secret',
resave: false,
saveUninitialized: true
}));
app.get('/', function (req, res) {
console.log(req.session); // undefined! :(
});
app.listen(3000);
As you can see the req.session above always seems to be undefined, and obviously unable to store any variables in there...
Of course, the most frustrating problems have the simplest answers... Redis client was never installed. Link for anyone in the future - http://redis.io/topics/quickstart :facepalm:
looks like you forgot to start redis. try typingservice redis-server start on your server cli. hope it'll help :)
The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));
I have an express app that was using redis cloud to store sessions in Heroku. It was working fine a few months ago, but I have just revisited it and it is no longer working. It seems there is no session, and throws the error TypeError: Cannot read property 'user' of undefined, the offending line of code is
if (!req.session.user) {
...
...
}
Maybe I'm configuring things incorrectly
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require('redis-url').connect(config.redis_url);
var sessionMiddleware = session({
store: new RedisStore({
host: config.redis_host,
port: config.redis_port
}),
secret: 'Its a secret.',
cookie: { secure: true },
saveUninitialized: true,
resave: true
});
The corresponding config file is
module.exports = {
mongo_url: process.env.MONGOLAB_URI || 'mongodb://127.0.0.1:27017/psa',
redis_url: process.env.REDISCLOUD_URL || 'redis://localhost:6379',
redis_host: taken from process.env.REDISCLOUD_URL,
redis_port: taken from process.env.REDISCLOUD_URL,
port: process.env.PORT || 5000
};
This works locally forman start web when I define the session middleware as follows
var sessionMiddleware = session({
secret: 'VkWdLXauq6ya',
saveUninitialized: true,
resave: true,
store: new RedisStore({
client: redis
}),
cookie: {
path: '/',
maxAge: 3600000
},
name: 'sessionCookie'
});
Are you using the cookieParser middleware? You'll need:
app.use(express.cookieParser());
Seems like it is similar to this other stackoverflow question.
How are you using the created session middleware? eg:
var sessionMiddleware = session({
That creates a Function that can be used in your express stack. However, it does nothing until you actually use it, like:
var app = express();
app.use(sessionMiddleware);
First of all i'm rookie with nodejs, i started to learn it about 3-4 days and i read lots of articles but they made me more confuse!
var app = express();
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
key : 'session',
secret: 'mySecretKey',
store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
var server= require('http').Server(app) ;
var io = require('socket.io')(server);
var passportSocketIo = require("passport.socketio");
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'session',
secret: 'mySecretKey',
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail,
}));
It works great and check socket connection access, but there's a little big problem for me.
How i can access the session id on socket messages?
i want to search session data in my session store and find the current users information.
this piece of code seems not working:
io.on('connection',function(socket) {
socket.on('myevent',function(){
console.log("Session: ", socket.session);
});
});
I found
socket.request.user
It changed in new version.
I'm trying get access to session data in express so I thought I would try declaring a connect-redis session store when configuring express. However, I cannot see why this doesn't work:
var express = require('express');
var http = require('http');
var RedisStore = require('connect-redis')(express);
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));
//app.use(express.session({ secret: "keyboard cat" }));
app.use(app.router);
app.get('/', function(req, res){
console.log('/');
req.session.items = [ 'apple', 'orange' ];
res.end('items configured');
});
app.get('/items', function(req, res){
console.log('/items: ', req.session.items);
var s = JSON.stringify(req.session.items);
res.end('items: ' + s);
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The '/' route simply configures items with the session.
The '/items' route displays the list of items in the session.
It works using the standard expressjs session store.
It doesn't work using connect-redis (req.session is undefined)
I'm assuming the redis store will be instantiated and destroyed as the app loads/unloads (or do I need it running outside of node/express app?)
Any ideas?
req.session will be undefined if RedisStore can't connect to your Redis server. So it's either not running, or it's not running on the default location that RedisStore is looking for it (127.0.0.1:6379).
In case of the latter, you can configure the location using the options argument to the RedisStore constructor.
Give this a try.
var express = require('express');
var redis = require("redis");
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var client = redis.createClient();
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({
secret: 'ssshhhhh',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
resave: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/',function(req,res){
// create new session object.
if(req.session.key) {
// if email key is sent redirect.
res.redirect('/admin');
} else {
// else go to home page.
res.render('index.html');
}
});
app.post('/login',function(req,res){
// when user login set the key to redis.
req.session.key=req.body.email;
res.end('done');
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
} else {
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
link : https://codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/
You should invoke RedisStore constructor (with ())
app.use(express.session({ secret: "keyboard cat", store: new RedisStore()}));