- Install the required packages:
npm install express express-session
- Import the packages in your Node.js application:
const express = require('express');
const session = require('express-session');
- Set up the session middleware with the necessary configurations:
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Adjust as needed based on your deployment environment
}));
- Implement a middleware to check for session existence and handle redirection if needed:
app.use((req, res, next) => {
if (!req.session.user && req.path !== '/login') {
res.redirect('/login');
} else {
next();
}
});
- Create a route for the login page:
app.get('/login', (req, res) => {
res.render('login'); // Adjust this based on your template engine or rendering method
});
- Handle login POST request to set the session:
app.post('/login', (req, res) => {
// Authenticate user (replace this with your authentication logic)
const { username, password } = req.body;
// Example: check username and password
if (username === 'your_username' && password === 'your_password') {
req.session.user = username;
res.redirect('/');
} else {
res.redirect('/login');
}
});
- Implement a route for the main page, where session is required:
app.get('/', (req, res) => {
res.send(`Welcome, ${req.session.user}!`);
});
- Add a logout route to clear the session:
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
console.error('Error destroying session:', err);
}
res.redirect('/login');
});
});
- Handle the back button issue by setting appropriate headers:
app.use((req, res, next) => {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
});
- Start the Express server:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});