Performance: Session-based vs token-based auth
This concept affects page load speed and interaction responsiveness by influencing server requests and client-side processing during authentication.
const jwt = require('jsonwebtoken'); const express = require('express'); const app = express(); app.get('/profile', (req, res) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).send('Unauthorized'); try { const user = jwt.verify(token, 'secret'); res.send(`Hello ${user.name}`); } catch { res.status(401).send('Unauthorized'); } });
const express = require('express'); const session = require('express-session'); const app = express(); app.use(session({ secret: 'secret', resave: false, saveUninitialized: true })); app.get('/profile', (req, res) => { if (req.session.user) { res.send(`Hello ${req.session.user.name}`); } else { res.status(401).send('Unauthorized'); } });
| Pattern | Server Memory Usage | Request Latency | Scalability | Verdict |
|---|---|---|---|---|
| Session-based Auth | High (stores sessions) | Higher (session lookup per request) | Lower (needs sticky sessions or shared store) | [X] Bad |
| Token-based Auth | Low (stateless tokens) | Lower (local token verification) | Higher (easier horizontal scaling) | [OK] Good |
const jwt = require('jsonwebtoken');
const token = req.headers.authorization?.split(' ')[1];
try {
const user = jwt.verify(token, 'secretKey');
res.send(`User ID: ${user.id}`);
} catch {
res.status(401).send('Unauthorized');
}function auth(req, res, next) {
if (!req.session.user) {
res.status(401).send('Not logged in');
}
next();
}Pass the test and this pattern moves unknown