0
0
Node.jsframework~5 mins

Session-based vs token-based auth in Node.js

Choose your learning style9 modes available
Introduction

Authentication helps websites know who you are. Session-based and token-based are two ways to do this simply and safely.

When you want to keep users logged in on a website with server control.
When building an app that needs to work across many devices or services.
When you want to store user login info on the server for easy logout.
When you want a stateless system that scales well without server memory.
When you want to share login info between different parts of a system easily.
Syntax
Node.js
Session-based:
// Server stores session info
req.session.user = { id: '123', name: 'Alice' };

Token-based:
// Server sends token to client
const token = jwt.sign({ id: '123' }, 'secret');
// Client sends token back in headers
Authorization: Bearer <token>

Session-based stores user info on the server, linked by a cookie.

Token-based sends a signed token to the client, no server storage needed.

Examples
This saves user info in a session on the server after login.
Node.js
// Session-based example
app.post('/login', (req, res) => {
  req.session.user = { id: '1', name: 'Bob' };
  res.send('Logged in with session');
});
This creates a token and sends it to the client after login.
Node.js
// Token-based example
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
  const token = jwt.sign({ id: '1', name: 'Bob' }, 'secret');
  res.json({ token });
});
Sample Program

This Node.js app shows both session-based and token-based login and profile routes. You can test login and then access profile routes to see how each method works.

Node.js
import express from 'express';
import session from 'express-session';
import jwt from 'jsonwebtoken';

const app = express();
app.use(express.json());

// Session setup
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

// Session-based login
app.post('/session-login', (req, res) => {
  req.session.user = { id: '42', name: 'Alice' };
  res.send('Logged in with session');
});

// Session-based protected route
app.get('/session-profile', (req, res) => {
  if (req.session.user) {
    res.send(`Hello ${req.session.user.name}, this is your session profile.`);
  } else {
    res.status(401).send('Not logged in');
  }
});

// Token-based login
app.post('/token-login', (req, res) => {
  const token = jwt.sign({ id: '42', name: 'Alice' }, 'secret', { expiresIn: '1h' });
  res.json({ token });
});

// Token-based protected route
app.get('/token-profile', (req, res) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.status(401).send('No token provided');

  jwt.verify(token, 'secret', (err, user) => {
    if (err) return res.status(403).send('Invalid token');
    res.send(`Hello ${user.name}, this is your token profile.`);
  });
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
OutputSuccess
Important Notes

Session-based auth keeps data on the server, so logout is easy by deleting the session.

Token-based auth is stateless, good for APIs and mobile apps, but logout needs token expiration or blacklist.

Always use HTTPS to keep cookies and tokens safe from attackers.

Summary

Session-based auth stores user info on the server linked by cookies.

Token-based auth sends a signed token to the client to prove identity.

Choose session for simple web apps, token for scalable or multi-device apps.