Selected topic
Session Management
Prefer practical output? Use related tools below while reading.
javascript
const express = require('express');
const session = require('express-session');const app = express();
// Create a session middleware with 30 minutes expiration time
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 1800000 } // 30 minutes in milliseconds
}));
let count = 0;
// Get user ID from session or create a new one if it doesn't exist
app.get('/', (req, res) => {
const userId = req.session.userId;
if (!userId) {
req.session.userId = Math.floor(Math.random() * 100000);
} else {
count++;
console.log(User ${userId} has visited the page ${count} times);
}
res.send('Welcome to our website!');
});
// Clear session data on logout
app.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/');
});
In this example:
express-session middleware./), we check if a user ID is stored in the session. If not, we generate a new one using Math.floor(Math.random() 100000). If it exists, we increment a counter and log a message to the console.
/logout endpoint is hit, we clear the session data by calling req.session.destroy().