Keep express sessions on NodeJS restart - node.js

I use express-session
app.use(require('express-session')({ resave: false, saveUninitialized: false }));
And I would like to know if it's possible to keep sessions after NodeJS server restart ?
Thank you very much
(User is disconnected after every server reload)

Sessions are stored in memory so if your NodeJS server restarts, all the session data is lost.
You will have to use a database to store the session data.
The documentation has a list of modules available to connect with the database.
https://www.npmjs.com/package/express-session#compatible-session-stores

Related

How to destroy the session (store)?

For authentification I'm trying to understand, how sessions work. With help of documentation of express session and Sessions in Node JS I got it work.
Now I'm figuring out, what to do, that users can log out. In the documentation of express session is to read "The default server-side session storage, MemoryStore, is purposely not designed for a production environment." They recommand a compatible session store.
I have choosen connect-redis. They call it an "in-memory data structure store". Now I'm wondering, what is the difference between redis and the database, that I would like to use (back4app).
If I implement connect-redis
const RedisStore = require('connect-redis')(session);
const redis = require("redis").createClient();
let sess = {
store: new RedisStore({ host: 'localhost', 6379, client: redis }),
secret: cryptoString,
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 1 * 60 * 1000,
},
}
server.use(session(sess));
the user object from back4app stills undefined. (Without redis the user object exists.)
As mentioned I have tryed Parse.User.logOut(). It doesn't work. The console says Parse.User is null.
Please, explain
what is the difference between back4app and redis? Do I need both?
how do I enable log out?
For all with the same problem. This is my other question in this context. It will help you to see the whole picture.

Node.js Handle session with database

Basically I have a Node.js web application which uses the express-session module to handle sessions.
It works perfectly but with 1 expectation which ruins this option for me. If the Server crashes or I deploy a new release, the sessions get wiped out complety and thats unacceptable for me. Also its bad that I cant share the session between my main and my backup server.
So my goal is to handle the session via a external cloud database, just think of it as a "casual mysql database".
But here is the point were I just get confused on how to do that. I can assign unique ids to the sessions and depending on those load the resources from the database, but how can I re-recognize the users if these sessions get wiped away?
I am lacking alot of knowledge about sessions, but since this is quite a critical topic for me I post a question here.
You can use any of those stores (or write your own) :
https://www.npmjs.com/package/express-session#compatible-session-stores
I'm using the connect mongo to store sessions in my mongo DB, code looks like this (app.js) :
import session from 'express-session';
const MongoStore = require('connect-mongo')(session);
...
...
api.use(session({
secret: global.config.secrets.session,
saveUninitialized: false, // don't create session until something stored
resave: false, //don't save session if unmodified
store: new MongoStore({
mongooseConnection: mongoose.connection,
touchAfter: 24 * 3600 // time period in seconds
})
}));

Managing persistence sessions in NodeJS

i'm trying to set up a very basic session manager. So, first i came with this code:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
// define session store
app.use(session({
secret: 'meh',
saveUninitialized: true,
resave: true,
store: new MongoStore({
db : 'express'
})
}));
My current setup is nodejs/express4 with all modules installed locally.
now, how can i share this app without having problems with connect-mongo? because, if i run it on other machine, i get this error:
"error connection to database:failed to connect to [127.0.0.1:27017]..."
Do you know what may be wrong ?
The most obvious mistake here would be: there is no running MongoDB instance on the other machine.
If you want to connect to a remote server you have to specify the location and (hopefully) credentials. Have a look at: https://github.com/kcbanner/connect-mongo#options

session storage on mongo DB is creating one line on DB for each http request and not one per login/sign up

Using connect-mongo to handle session storage, I am getting a lot of empty sessions in my mongo database (using mongolab), probably on every request (or very often). Here is an example:
{
"_id": "oThxLcz3PtztDWVxcKZvoADC",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}",
"expires": {
"$date": "2013-07-10T22:45:52.383Z"
}
}
As you can see, there is no user defined in the object. I read in another issue that it might be a difference of time between the server and the client so the cookies are expiring instantly but that's not the case, the sessions are working fine. Any idea how to have only a line every time somebody logs in or signs up? I don't want to pay extra storage on my database.
For info, I am using 2 dynos on Heroku and mongolab and my set up is:
app.use(express.session({ secret: 'secretkey',
store: new MongoStore({
url:'mongodb://db:user#link:27468/dbname'
})
}));
I can't help you debug that issue, but I can suggest using connect-redis instead. The Redistogo nano instance on Heroku is free, and should support automatically expiring unused sessions so that you won't need a pricier option.

A few questions about express.cookieSession()

On my node.js server (running express and socket.io), when a person connects, I add them to an array and save their location in the array into their session so each connection has access to their own information like so:
session.person_id = people.length;
session.save();
people.push(new Person());
//people[session.person_id] => Person
And the only thing that I save in the session is person_id. I have been using express.session() to handle this, which has been working fine until I started sending information to everyone who is connected at once. As I loop through their connections and get their sessions, sometimes (I can't figure out how to dupe the error) session exists but not session.person_id.
Anyways I'm hoping that by changing how I store the session, it can help me figure out my problem. So I have a few questions that I can't find answers to anywhere.
Where is the cookie from express.cookieSession() stored? Server-side or client-side?
Does express.cookieSession() allow for multiple servers running behind a load-balancer?
Is it possible for a user to manipulate session data when using express.cookieSession()?
1 - Where is the cookie from express.cookieSession() stored? Server-side or client-side?
The cookie is sent on the replies from the server, and the browser sends that cookie back with each request.
2 - Does express.cookieSession() allow for multiple servers running behind a load-balancer?
Yes, if you use a shared store (like RedisStore)
3 - Is it possible for a user to manipulate session data when using express.cookieSession()?
Not if you use signed cookies (the default for session cookies in express when you provide a secret when initializing the session.
var redis = require('redis').createClient();
app.use(express.session({
secret: "some random string",
store: new RedisStore({client: redis})
}));

Resources