How to keep track when session expires in express session

Hello guys, sorry to disturb you all; can someone explain how can I do in order to keep track when a session expires , for e,g after 5sec without refreshing the web-page
// Access the session as req.session
app.get('/', (req,res) => {
console.log(req.session);
if (req.session.viewCount) {
req.session.viewCount++;
viewCount++;
}
else {
req.session.viewCount = 1;
viewCount = 1;
}
console.log(`${req.session.id}`);
res.send(`<h1> Hello world...view count(s): ${req.session.viewCount}`);
});
// Access the session as req.session
app.get('/', (req,res) => {
console.log(req.session);
if (req.session.viewCount) {
req.session.viewCount++;
viewCount++;
}
else {
req.session.viewCount = 1;
viewCount = 1;
}
console.log(`${req.session.id}`);
res.send(`<h1> Hello world...view count(s): ${req.session.viewCount}`);
});
12 Replies
Faker
FakerOP3d ago
The session expires after 5sec but I want to be redirected to kind of a "time-out" page because the user don't know that the session has expired
ἔρως
ἔρως2d ago
how do you know that the session expires in 5 seconds? and why do you want to send users to a page every 5 seconds?
Jochem
Jochem2d ago
I'm going to assume you mean 5 seconds as an example that's easy to test. There's a couple of common ways: Either you redirect on the first failed request after the session expires, or you keep track of the session time in both the frontend and the backend. For the first option, usually that's fine because the user doesn't really care whether the session is still alive if they're not doing anything with the site. For the second option, the reason you keep track of it on both ends is that generally speaking once a page is loaded or an api call made and responded to, there's no further connection to the client. Any action by the user will create a new connection, but the server has no path to that user. You track the time in the browser and handle the expiration in the frontend because you can have continuously running code there. the very simple way is to send a timestamp of expiry along to the frontend so that you can set a timeout of the appropriate length and do what you need to do on the frontend but like I said, usually you just do the first option and not really worry about it the only time I'd use the second option, is if I was using a token that has an expiring access token and a refresh token
Faker
FakerOP2d ago
I set the maxAge of cookie to 5000ms, it's for testing Yep I see, I will try it out and revert back, thanks ! There is something known as "keep-alive" , I think it is some kind of attribute in headers, do that have anything to play with what you mentioned please
Jochem
Jochem2d ago
In that is a similar concept but no more than that
ἔρως
ἔρως2d ago
thats for http 1.1, to keep the tcp connection alive so it doesnt have to do all the dns and ssl/tsl handshake stuff again that wont do anything for you
Faker
FakerOP2d ago
yep I see, so I can just ignore the "keep-alive" thing ?
Jochem
Jochem2d ago
yeah
Faker
FakerOP2d ago
by the way, I was able to do the session management session !!
import express from 'express';
import session from 'express-session';
import path from 'path';
import { fileURLToPath } from 'url';

const app = express();
const port = 8080;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let viewCount = 0;


// Use the session middleware
const sessionOptions = {
secret: 'super secret secret',
cookie: {maxAge: 8000} // 5sec
// resave: false, // don't save session for each request if unmodified
// saveUninitialized: false // don't create session until something is stored - interacting with session
}
app.use(session(sessionOptions));

// Access the session as req.session
app.get('/', (req,res) => {
console.log(req.session);
if (req.session.viewCount) {
req.session.viewCount++;
viewCount++;
}
else {
req.session.viewCount = 1;
viewCount = 1;
}
console.log(`${req.session.id}`);
res.sendFile(path.join(__dirname, '../public/HTML/index.html'));
});

app.get('/data', (req,res) => {
if (!req.session.viewCount) {
return res.status(440).json({
"errorMsg": "Server timed out"
});
}
res.json({
"name":"John Doe",
"age": 40
})
})


app.listen(port, () => {
console.log(`Server started on port: ${port}`);
})
import express from 'express';
import session from 'express-session';
import path from 'path';
import { fileURLToPath } from 'url';

const app = express();
const port = 8080;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let viewCount = 0;


// Use the session middleware
const sessionOptions = {
secret: 'super secret secret',
cookie: {maxAge: 8000} // 5sec
// resave: false, // don't save session for each request if unmodified
// saveUninitialized: false // don't create session until something is stored - interacting with session
}
app.use(session(sessionOptions));

// Access the session as req.session
app.get('/', (req,res) => {
console.log(req.session);
if (req.session.viewCount) {
req.session.viewCount++;
viewCount++;
}
else {
req.session.viewCount = 1;
viewCount = 1;
}
console.log(`${req.session.id}`);
res.sendFile(path.join(__dirname, '../public/HTML/index.html'));
});

app.get('/data', (req,res) => {
if (!req.session.viewCount) {
return res.status(440).json({
"errorMsg": "Server timed out"
});
}
res.json({
"name":"John Doe",
"age": 40
})
})


app.listen(port, () => {
console.log(`Server started on port: ${port}`);
})
I don't know if it is efficient but it worked and I understand how things work :c I use the first method where we have invalid request... seems easier for now
ἔρως
ἔρως2d ago
depends... but for this, you can ignore it dont forget that the session can be terminated in multiple ways: - client clears the cookies - the client doesnt communicate to the site for longer than the timeout - the client has an invalid session token - the server is restarted/restored/reverted - an automatic task clears "useless" cookies
Faker
FakerOP2d ago
yep I see, what is the last point, for the automatic clask, didn't know it exist
ἔρως
ἔρως2d ago
im not sure if it exists for express js, but it does for other languages
Want results from more Discord servers?
Add your server