Can we store session in Database? - node.js

Can we store session in database Mysql not in memory using passport module.
I am using nodejs, express and mysql
Thanks

Passport module doesn't provide sessions to your application, it uses connect or express session.
connect/express sessions may (and should!) be persistent and there are plenty of session stores available on npm.
With a quick search I found two implementations of connect/express mysql session store:
connect-mysql
express-mysql-session
Just take any one of them and use as your session store with express-session (or conncect.session):
var express = require('express');
var session = require('express-session');
var SessionStore = require('express-mysql-session')
var app = express();
var sessionStore = new SessionStore(/*options*/);
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: true,
saveUninitialized: true
}))

Related

Redis Store + Express Session

I notice that some of the project will use redis store and express session to save the user session
For example:
const session = require('express-session');
var redis = require("redis");
var redisStore = require('connect-redis')(session);
var client = redis.createClient();
var app = express();
app.use(session({
secret: 'scret',
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: client,
ttl : 7200
}),
saveUninitialized: true,
// rolling: false,
resave: true,
cookie: {
maxAge: 2 * 60 * 60 * 1000
}
}));
What is the reason that we need to use these two Session Management function at the same time?
express-session can be set up with different "stores" to save session data.
MemoryStore comes with the package express-session.
The authors of express-session warn about this default store.
Warning The default server-side session storage, MemoryStore, is
purposely not designed for a production environment. It will leak
memory under most conditions, does not scale past a single process,
and is meant for debugging and developing.
Redis is one of the compatible session stores and in this case is used "as a replacement" of a default store.

Store Node JS express sessions using Azure Redis Cache

I have tried to build an Express 4 Web App using Azure. I found on several articles that I can store the sessions in Azure Redis Cache. However, how should I connect my web app to the redis cache?
var session = require('express-session');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);
var client = redis.createClient(6380, 'MyHost', { auth_pass: 'MyPass', tls: { servername: 'MyHostName' } });
app.use(session({
secret: 'keyboard cat',
key: 'sid',
resave: false,
saveUninitialized: false,
store: new RedisStore(client);
}));
But then it returns an error when I run the app. Saying
TypeError: this.client.unref is not a function
How can I solve this? Thanks!
You might make a mistake in RedisStore constructor.
Change the following line of code store: new RedisStore(client); as below:
store: new RedisStore({client: client});

ExpressJS session save in cookie

I want create session cookie for track user in site. For this purposes I use "express-session" middleware:
var express = require('express');
var session = require('express-session');
app.use(session({
name: 'cookie',
secret: 'my express secret',
saveUninitialized: true,
resave: true,
cookie: {}
}));
But after NodeJS restart cookie loosing. I can't find cookie session storage like as "Compatible Session Stores". I don't want using database to save sessions, I want configure "express-session" to store all data to cookies. Is it possible?
You can use cookie-session.
To install: npm install cookie-session --save
And include in your app file, for example:
var cookieSession = require("cookie-session");
app.use(cookieSession({
name: "session",
keys: ["key-1","key-2"]
}));

Best Session Storage Middleware for Express + PostgreSQL

I'm looking for sessionstore for production app because I have error message:
Warning: connect.session() MemoryStore is not designed for a
production environment, as it will leak memory, and will not scale
past a single process
My code:
var express = require('express');
var ECT = require('ect');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var _ = require('lodash');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secrets.sessionSecret,
}));
app.use(passport.initialize());
app.use(passport.session());
var app = module.exports = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(app.get('port'), function() {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
I don't know what is the best solution for my production app. I'm using sequelize as ORM with PostgreSQL.
I will be very grateful with any opinion.
Though an answer has been accepted, I think a more elaborated answer is in order, so that people who actually want to use Express with PostgreSQL for consistent session storage can have a proper reference.
Express has the session module to handle the sessions though it defaults to in-memory storage that is suitable for development stages but not for production
Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
So for PostgreSQL there is a dedicated simple connector called connect pg simple
Once you import the connect-pg-simple you . need to pass it the session import like this:
const session = require('express-session')
const pgSession = require('connect-pg-simple')(session)
When you add the session as middleware you'll have to pass it its settings
app.use(session(sessionConfig))
and in your sessionConfig, this would be where you set all your session parameters you need to add a store option that would look like this (adding the full set of options though for the matter at hand just note the store option):
const sessionConfig = {
store: new pgSession({
pool: sessionDBaccess,
tableName: 'session'
}),
name: 'SID',
secret: randomString.generate({
length: 14,
charset: 'alphanumeric'
}),
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7,
aameSite: true,
secure: false // ENABLE ONLY ON HTTPS
}}
The new instance of pgSesision takes two options, the pool which is the config setup to access the PostgreSQL DB and the table name.
The DB connection setting should look like this:
const sessionDBaccess = new sessionPool({
user: DB_USER,
password: DB_PASS,
host: DB_HOST,
port: DB_PORT,
database: DB_NAME})
Also note that the session pool must be initiated:
const sessionPool = require('pg').Pool
I got it working with connect-pg-simple.
Create a session table with the provided table.sql, and pass in a connection string or an object.
If you have just to store session you can use redis or maybe mongoDB if you want persistence.

Why does node express req.session disappear with redis?

Node.js express sessions work perfectly for me with this code:
var express = require("express");
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
cookie: {maxAge: pembapp.dayInMilliseconds * 180},
secret: 'mysecret',
key: 'mykey'
}));
I can access req.session.whatever with no problem.
Now I want to use redis to store session data in case a server restart is needed, so the code becomes this:
var express = require("express");
var app = express();
var RedisStore = require('connect-redis')(express);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
cookie: {maxAge: pembapp.dayInMilliseconds * 180},
secret: 'mysecret',
key: 'mykey',
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
prefix: 'myprefix',
pass: 'mypasswd'
})
}));
When I add the redis code, req.session is now undefined! Can't figure this out for the life of me. Why would req.sesion "disappear" when I add a redis store for sessions???
I think we can close this one out. Perhaps I wasn't connecting to redis when req.session was undefined. I did find that I needed to explicitly call req.session.save() when using redis, which wasn't needed without redis.
Judging from the questions I've seen out there, ff someone could create a clear node.js example using redis-connect for persistent sessions, for node newbies, starting from scratch, I think you'd make a bunch of folks very happy.
Are you sure it is connecting to the Redis database?

Resources