Sessions
express-session
Authentication and Session Management are the two pillars of security in a web application
1. Authentication vs. Authorization: The Theory
Theory: These two terms are often confused but serve distinct purposes
Authentication (AuthN): The process of verifying credentials (e.g., checking if the email and password match the database)
. Authorization (AuthZ): The process of checking permissions (e.g., can this logged-in user delete a post, or are they just a viewer?)
.
2. Session-Based Authentication (The Classic Way)
Theory: In this model, the server is responsible for remembering the user
Login: The user sends credentials
. Creation: The server verifies them and creates a Session ID, which it stores in a database or memory (like Redis)
. Cookie: The server sends this Session ID back to the browser in a
Set-Cookieheader. Verification: For every subsequent request, the browser automatically sends the cookie. The server looks up the ID in its storage to see who the user is
.
Pros/Cons:
Pros: Easy to revoke sessions (logout instantly)
. Cons: Harder to scale because the server must "remember" every active user (Stateful)
.
3. Token-Based Authentication (JWT)
Theory: This is the standard for MERN stack applications
Login: User sends credentials
. Signing: The server creates a JWT signed with a Secret Key
. Storage: The token is sent to the client, which usually stores it in
localStorageor anHttpOnlycookie. Verification: The client sends the token in the
Authorizationheader (Bearer <token>). The server verifies the signature—it doesn't need to check a database .
4. Implementation in Express
Setting up Sessions
Using the express-session library
const session = require('express-session');
app.use(session({
secret: 'your-secret-key', // Used to sign the session ID cookie
resave: false,
saveUninitialized: true,
cookie: { secure: false, maxAge: 60000 } // Setting cookie properties
}));
app.post('/login', (req, res) => {
// After DB check...
req.session.user = { id: 1, name: 'Tharun' }; // Data stored on server
res.send('Logged in');
});Setting up JWT
Using the jsonwebtoken library
const jwt = require('jsonwebtoken');
// 1. Generate Token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });[cite: 1]
// 2. Auth Middleware
const protect = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];[cite: 1]
if (!token) return res.status(401).json({ message: 'No token' });[cite: 1]
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);[cite: 1]
req.user = decoded; // Attach user info to request
next();
} catch (err) {
res.status(401).json({ message: 'Invalid token' });[cite: 1]
}
};.