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.
Related
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
}
}));
I set a session variable called user upon login:
req.session.authenticated_user = user;
When I set the session again later it doesn't update:
req.session.authenticated_user = somenewvalue;
This will still contain the original value of user. App module:
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var redisClient = redis.createClient();
const sessionMiddleware = session({ secret: 'foo' });
app.use(session({
store: new redisStore({ client: redisClient }),
secret: 'secretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: false, sameSite: true, expires: 7200000 }
}))
app.use('/users', sessionChecker, usersRouter);
My router:
var express = require('express');
var router = express.Router();
var user_controller = require('../controllers/userController')
/* GET user update. */
router.get('/user_login/login', user_controller.user_login_get);
/* POST user update. */
router.post('/user_login/login', user_controller.user_login_post);
/* GET user update. */
router.get('/:username/update', user_controller.user_update_get);
/* POST user update. */
router.post('/:username/update', user_controller.user_update_post);
How can I update a session variable in node?
Answered here: Sessions won't save in Node.js without req.session.save()
req.session won't update automatically if req is a Post request. For Post requests, one must call req.session.save() unless data is sent out through res.send, res.redirect, etc.
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.
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);
i'm using Redis to store sessions in my node.js app, hosted on heroku, but redis is keeping the session stored, how can i make them expire automatically?
My express app is configured this way:
var app = express.createServer(
express.static(__dirname + '/public', { maxAge: 31557600000 }),
express.cookieParser(),
express.session({ secret: 'secret', store: new RedisStore({
host: 'myredishost',
port: 'port',
pass: 'myredispass',
db: 'dbname'
})})
);
As the Connect session middleware docs state, you need to set the maxAge property on the cookie object:
express.session({ secret: 'secret', store: ..., cookie: { maxAge: 60000 }});
Read more about that here: http://senchalabs.github.com/connect/middleware-session.html
They will expire based on the cookie if you're using req.session.cookie.maxAge.