Sessions

express-session

Authentication and Session Management are the two pillars of security in a web application. While Authentication verifies who a user is, Session Management remembers that the user is logged in as they navigate between different pages.


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.

  1. Login: The user sends credentials.

  2. Creation: The server verifies them and creates a Session ID, which it stores in a database or memory (like Redis).

  3. Cookie: The server sends this Session ID back to the browser in a Set-Cookie header.

  4. 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. Instead of the server storing a session, the user carries their own "ID badge" called a JSON Web Token (JWT).

  1. Login: User sends credentials.

  2. Signing: The server creates a JWT signed with a Secret Key.

  3. Storage: The token is sent to the client, which usually stores it in localStorage or an HttpOnly cookie.

  4. Verification: The client sends the token in the Authorization header (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]
  }
};


.