Is there any trick to get a unique user identifier, which doesn't change, when the user refreshes the browser? I've tried socket.io and sessionID from express, but those change when the user refreshes the browser.
Why? I'm trying to make a game without the need to log in. The User class will create a lobby with friends and then start the game, which will be locked for any other users, but I want to make the feature, that if the user who has already started/joined any game will refresh the browser, he will be reconnected to his game.
I'd already set up the database which is ready for the unique user identifier, so the lobby/game will know who will be authorized to join and who will be not.
Code of how my sessions are set up:
const sessions = require('express-session');
...
app.use(sessions({
secret: "thisismysecretkey",
saveUninitialized: true,
resave: false
}));
...
app.post("/lobby/:id", (req, res) => {
console.log(req.sessionID)
});
With this set up, the sessionID is constantly changing when the requests are from the same user.
P.S. Yes, the secret code is unsafe, I will change it after I will make it work.
I found out why my sessionID was changing upon every request. It was because I wasn't saving anything in the session (because I was just printing the sessionID, wondering if it will change), so the session was dropped and on new request the new session was created etc. I should have read more documentation on express sessions.
Anyway, if anyone was wondering how to save something in the session, here is an simple example which counts how many times you visited the website.
app.get("/test", function (req, res) {
console.log(req.sessionID, req.session);
if (req.session.page_views) {
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
And if your sessionID is still changing then check your session configuration (this one works)
app.use(
session({
secret: "thisismysecretkey",
saveUninitialized: true,
resave: true,
cookie: {
secure: false,
},
})
);