I have a node server running right now, I use npm forever
to keep it running when I'm not developing and I use npm nodemon
for when I edit (restarts app on edit/upload).
I noticed that whenever I restart my app, session data is lost and my players have to re-login to their accounts. It's not a huuuge deal, but I was wondering if there was a way to edit my server.js page without restarting the app, and logging everybody out?
(Note that this only applies for server.js or module edits. .html
and .js
pages that are served don't require a restart)
(Second note: I am using mysql, nodejs, angularjs, express.io for all this, just in case anybody asks)
Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );
sessionStorage is a browser side API for storing values locally for the life of the browser session, that does not automatically get transmitted to the server. NodeJS is a framework and engine for creating server side applications.
and then store the session like this: let session = require("express-session"); app. use(session({ secret: "secret", resave: false, saveUninitialized: true, cookie: {secure: true, httpOnly: true, maxAge: 1000 * 60 * 60 * 24 } })); This session will be stored during your visit on the webpage.
Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.
There isn't a way to edit a file (and have the changes loaded) without rebooting the server and reloading the file. Instead, store your session data somewhere other than memory. I know you're using MySQL, so use the connect-mysql package (there are other packages like this for redis, MongoDB, etc).
It's as simple as putting this in your app.js
file:
var MySQLStore = require('connect-mysql')(express)
, options = {
config: {
host : 'place.stuff',
user: 'RUJordan',
password: 'hunter2',
database: 'SomeKittensIsGreat'
}
};
app.use(express.session({
secret: 'UpvoteThisAnswer',
store: new MySQLStore(options),
cookie: { maxAge: 2592000000 } // 30 days
}));
This will place a HTTP-only (i.e. the user can't see/use it) cookie on each user's computer. Even after a server reboot, connect-mysql
will be able to like a user with their session data in MySQL via this cookie.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With