Cookie-Session and Express-session both not being presists - node.js

here is my config:
const session = require('express-session');
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
}))
set in route:
req.session.challenge = makeCredChallenge.challenge;
req.session.user_name = body.user_name;
using in other route:
console.log('challange from session', req.session.challenge)
console.log('username from session', req.session.user_nam
e)
but its undefine in other routes where I'm using it

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

MongoStore, Atlasdb return the mongoUrl and ClientPromise

I am getting error while trying to save session on mongodb. Here is my code.
//MIDDLEWARE FUNC
app.use(methodOverride('_method',{methods: ['POST','GET']}))
app.use(Express.static(path.join(__dirname, 'public')))
app.use(Express.urlencoded({extended:true}))
app.use(Express.json())
app.use(session({
secret: 'my_keyboard_cat',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.DB_URI,
dbName: 'sessions'
})
}))
app.use(flash())
app.use((req,res,next) => {
res.locals.flashMessages = req.flash()
next()
})
and error is : Assertion failed: You must provide either mongoUrl|clientPromise|client in options
/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
throw new Error('Cannot init client. Please provide correct options')
Error: Cannot init client. Please provide correct options

express session is not working with vuejs and axios

Session initialize in express.js also used passport.js for local-authentication which is working fine. But the session/cookie is not working
app.use(serveStatic(__dirname + '../../dist'));
mongoose.connect(config.database, function(err){
if(err) console.log(err);
console.log('Connected to DB');
})
app.use(cors({
origin:['http://localhost:8080'],
credentials: true // enable set cookie
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({ 'extended': 'false' }));
// required for passport
require('./config/passport')(passport); // pass passport for configuration
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
// session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
Get request with axios is below
axios.get(this.url + '/user', {withCredentials: true})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e)
})
Refer tutorial to store sessions or cookies using passport.js and express.js
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
instead of this try:
app.use(express.session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.session());

Default path for SQLite Store - Node.js

app.use(session({
store: new SQLiteStore,
secret:"xxxxxx",
saveUninitialized: false,
cookie: { maxAge: 60000 },
rolling: true,
resave: true
}));
By default new file with sessions named "sessions" is being created in a root directory. How to change default path?
var session = require('express-session');
var SQLiteStore = require('connect-sqlite3')(session);
app.use(session({
store: new SQLiteStore({dir:'./db/', db: 'sessions'}),
...

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

Resources