Redis not working on express-session - node.js

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'
}));

Related

trying to connect to Redis using typescript and nodejs

I am trying to connect to Redis using typescript and nodejs but I keep getting **
error TS2693: 'RedisStore' only refers to a type, but is being used as a value here.**
let redisCLient = createClient({legacyMode: true});
redisCLient.connect().catch(console.error);
declare module "express-session" {
interface SessionData {
isLoggedIn: boolean;
}
}
// middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cors());
app.use(
session({
secret: "reddit_apples_should_be_next",
resave: false,
saveUninitialized: false,
store: new RedisStore({client: redisCLient}),
})
);
You can do stuff like this
Basic Redis setup
Import statements
const express = require('express');
const session = required('express-session');
const redis = require('redis');
const connectRedis = require('connect-redis');
const app = express();
app.use(express.json());
connection
const RedisStore = connectRedis(session);
const redisClient = redis.createClient(
port: 6379,
host: 'localhost'
});
configure session middleware
app.use(session({
store: new RedisStore({client: redisClient}),
secret: 'mySecret',
saveUninitialized: false,
resave: false,
name:'sessionId',
cookie: {
//secure false for non https request , keep false in production
secure: false,
// if true, prevents client side JS from reading the cookie
httpOnly: true,
//session age in millisec // 30 mins
maxAge: 1000 * 60 * 30
}
}));

Unable to use sessions in node.js

I developing login page.
If user successfully logs in , then I want to store user_Id into session variable,which I will be using to authenticate other pages.
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(bodyParser.json());
app.use('/user', userRoutes);
app.use('/', index);
app.use(cookieParser());
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}));
User router
var express = require('express');
var router = express.Router();
User = require('../models/user');
//Login User
router.post('/login', function (req, res) {
var user = new User(req.body);
User.login(user, function (err, user) {
if (err) {
res.sendStatus(500);
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
req.session.name = user.id;
res.json(user.id);
});
});
Problem is if I execute this code I am getting Cannot set property 'name' of undefined
What I am doing wrong?
Please Help.
Problem is that your routes are already setup before session so you have to reorder the code.
Move these lines
app.use('/user', userRoutes);
app.use('/', index);
Below the app.use(session) declaration.
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}))

Redis Cloud for sessions in node heroku app

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);

Share sessions with redis and passport on a subdomain?

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
}
})

how can get the current session user information in nodejs on socket event?

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.

Resources