A common illustration of setting up sessions in Express is provided below. Feel free to customize the code based on your specific requirements.
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your_secret_key', // Replace with a secure secret key
resave: false, // Prevents session from being saved if not modified
saveUninitialized: true, // Allows saving new sessions even if they are not modified
cookie: { secure: false } // Use true for HTTPS environment
}));
app.use(express.json()); // For handling JSON data
app.use(express.urlencoded({ extended: true })); // For parsing URL-encoded data
const PORT = 8080;
// Route to store data in session and redirect
app.post('/save-to-session', (req, res) => {
const { myVariable } = req.body;
req.session.myVariable = myVariable;
res.redirect('/next-page');
});
// Route to retrieve data from session
app.get('/next-page', (req, res) => {
const myVariable = req.session.myVariable;
if (myVariable) {
res.send(`The variable stored in session is: ${myVariable}`);
} else {
res.send('Variable not found in session');
}
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});