Redis Cloud for sessions in node heroku app - node.js

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

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

Node JS: Update Redis TTL

I hope that I can update Redis's TTL when the user is still active so that the user won't auto logout after 15 mints
Below is my code to save the user session
const session = require('express-session');
const redisStore = require('connect-redis')(session);
const redis = require("redis");
var client = redis.createClient();
var app = express();
app.use(session({
secret: 'MY_SECRET',
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: client,
ttl: 900
}),
saveUninitialized: true,
resave: true,
cookie: {
secure: true,
maxAge: 1500
}
}));
My question is, how do I extend the TTL when the user is still active in my website?
resave: true means that the socket will resave (and reset the TTL) every time the user hits the API. See express-session docs.

Redis error "ReplyError: ERR value is not an integer or out of range"

i am trying to store sessions in Redis but giving me an error.
i am using nodejs and express.
ReplyError: ERR value is not an integer or out of range
import express from 'express';
import redis from 'redis';
import redisConnect from 'connect-redis';
import session from 'express-session';
const app = express();
const redisStore = redisConnect(session);
const redisClient = redis.createClient();
app.use(
session({
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: redisClient,
ttl: 36000,
}),
secret: "ljsaflasjdsffafa",
resave: false,
saveUninitialized: false,
name: 'user',
cookie: {
path: '/',
httpOnly: true,
maxAge: 36000,
secure: false,
},
}),
);
app.listen(3000)
it's happening when I try to save session
The ReplyError is an indicator that your input is not always correct. You could activate the debug mode to see what is actually passed through. There should also be a bit more information on the error about the data passed through.

Redis not working on express-session

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

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

Resources