Session-based authentication helps keep users logged in by remembering them on the server. It stores user info safely between requests.
0
0
Session-based auth with express-session
Introduction
You want users to log in and stay logged in while using your website.
You need to protect pages so only logged-in users can see them.
You want to keep track of user data without asking them to log in every time.
You want a simple way to manage user sessions without tokens.
You want to store user info securely on the server side.
Syntax
Express
const session = require('express-session'); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { secure: false } }));
secret is a string used to sign the session ID cookie. Keep it safe.
resave false means don't save session if nothing changed.
Examples
This sets up sessions with a secret and saves new sessions even if empty.
Express
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));This configures the cookie to be sent only over HTTPS (secure).
Express
app.use(session({
secret: 'mySecret',
cookie: { secure: true }
}));Sample Program
This example shows a simple Express app using express-session to handle login, protect a dashboard page, and logout. User info is stored in the session.
Express
const express = require('express'); const session = require('express-session'); const app = express(); app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'simpleSecret', resave: false, saveUninitialized: false, cookie: { secure: false } })); // Simple user database const users = { user1: 'pass1', user2: 'pass2' }; // Login form app.get('/login', (req, res) => { res.send(`<form method='POST' action='/login'> <input name='username' placeholder='Username' required /> <input name='password' type='password' placeholder='Password' required /> <button type='submit'>Login</button> </form>`); }); // Handle login app.post('/login', (req, res) => { const { username, password } = req.body; if (users[username] && users[username] === password) { req.session.user = username; res.send(`Welcome, ${username}! <a href='/dashboard'>Go to Dashboard</a>`); } else { res.send('Invalid login. <a href="/login">Try again</a>'); } }); // Protected dashboard app.get('/dashboard', (req, res) => { if (req.session.user) { res.send(`Hello ${req.session.user}, this is your dashboard. <a href='/logout'>Logout</a>`); } else { res.send('Please <a href="/login">login</a> first.'); } }); // Logout app.get('/logout', (req, res) => { req.session.destroy(err => { if (err) { return res.send('Error logging out'); } res.send('Logged out. <a href="/login">Login again</a>'); }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
OutputSuccess
Important Notes
Always keep your session secret private and strong.
Set cookie.secure to true only if your site uses HTTPS.
Sessions store data on the server, so they are safer than storing info in cookies.
Summary
Session-based auth keeps users logged in by storing info on the server.
Use express-session middleware to manage sessions easily.
Protect routes by checking if session user info exists.