Session vs Token Authentication: Which Is Right for Your Backend?

This article explains how session‑based and token‑based (JWT) authentication work in backend applications, compares their workflows, shows practical Express.js code examples, and helps you decide which method best fits your project's security and scalability needs.

21CTO
21CTO
21CTO
Session vs Token Authentication: Which Is Right for Your Backend?

Session‑Based Authentication

Session authentication stores a special code (Session ID) on the client to remember the user's identity, keeping them logged in until they log out.

1. User Login

The user sends an email and password to the server.

2. Verify Details

The server checks the credentials against stored user data.

3. Create Session

If valid, the server creates a session containing user information (e.g., user ID, permissions, expiration) and stores it securely on the server, often using express-session.

4. Return Session ID

The server sends the Session ID back to the client, typically as a cookie.

5. Use Session ID

For subsequent requests, the client automatically includes the Session ID cookie.

6. Server Checks

The server looks up the session data using the Session ID.

7. Grant Access

If the session is valid, the server knows the user is authenticated and returns the requested content.

When a user logs in, the server creates a session and sets a cookie containing the Session ID.

The browser automatically includes this cookie in later requests.

The express-session middleware extracts the Session ID from the cookie and retrieves the session data.

Data stored in req.session (e.g., userId) can be used to handle the request.

Code Example

const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({
  secret: 'your_secret_key',
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    maxAge: 60 * 30 // seconds
  }
}));

// Login
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  if (user) {
    req.session.userId = user.id; // Store user ID in session
    res.send('Login successful');
  } else {
    res.status(401).send('Invalid credentials');
  }
});

// Protected page
app.get('/home', (req, res) => {
  if (req.session.userId) {
    res.send(`Welcome, ${req.session.userId}!`);
  } else {
    res.status(401).send('Unauthorized');
  }
});

// Logout
app.get('/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      res.status(500).send('Error during logout');
    } else {
      res.redirect('/');
    }
  });
});

Token‑Based Authentication (JWT)

JWT authentication uses a digitally signed token that contains user information, allowing secure access without repeated logins.

1. User Login Request

The user sends email and password to the server.

2. Credential Verification

The server validates the credentials against stored user data.

3. Token Generation

Upon successful verification, the server creates a JWT containing claims such as user_id and permissions.

4. Token Signing & Hashing

The token is signed with a secret key and hashed (e.g., using SHA‑256).

5. Send Token

The server returns the token to the client, which typically stores it in the browser.

6. Token Storage Options

The token can be stored in an HttpOnly cookie, session storage, or local storage; HttpOnly cookies are recommended to mitigate XSS attacks.

7. Token Expiration & Security

Tokens have an expiration time to enhance security.

8. Include Token in Requests

Clients send the token in the Authorization header prefixed with "Bearer" for each request.

axios.get(URL, {
  headers: {
    'Authorization': 'Bearer ' + token,
  }
});

9. Server‑Side Verification

The server extracts the token from the request.

10. Token Validation & User Authentication

Using the secret key, the server verifies the token, extracts the claims, checks the user against the database, and grants access if valid.

Code Example

// Login
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  jwt.sign({ user }, secretKey, { expiresIn: '1h' }, (err, token) => {
    if (err) {
      res.status(500).send('Error generating token');
    } else {
      res.json({ token });
    }
  });
});

// Verify token middleware
function verifyToken(req, res, next) {
  const token = req.headers['authorization'];
  if (typeof token !== 'undefined') {
    jwt.verify(token.split(' ')[1], secretKey, (err, decoded) => {
      if (err) {
        res.status(403).send('Invalid token');
      } else {
        req.user = decoded.user;
        next();
      }
    });
  } else {
    res.status(401).send('Unauthorized');
  }
}

// Protected route
app.get('/dashboard', verifyToken, (req, res) => {
  res.send('Welcome to the Home page');
});

Differences Between the Two Methods

Storage location: Sessions are stored on the server, while JWTs are stored on the client.

Stateful vs. stateless: Sessions are stateful; JWTs are stateless, offering better scalability for distributed systems.

Expiration handling: Session expiration is managed by the server; JWT expiration is embedded in the token itself.

Security measures: JWTs include digital signatures and optional encryption, which can be more secure than typical cookie‑based sessions but may be vulnerable to CSRF if not protected.

Flexibility: JWTs can carry additional custom claims, making them useful for authorization and data transmission beyond simple authentication.

Which Method Should You Use?

The choice depends on the application’s requirements. Most projects adopt a hybrid approach: token‑based authentication for APIs and session‑based authentication for traditional web interactions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendAuthenticationJWTnodejsExpressSession
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.