Skip to content

Session-Based Authentication — Server-Side Session Auth Patterns

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Session Based Authentication. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Session-based authentication stores authentication state server-side, providing immediate revocation and centralized session control.

// Session-based auth with Redis
const session = require('express-session');
const RedisStore = require('connect-redis').default;

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  name: 'scan_session',
  cookie: {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
  }
}));

// Login with session
app.post('/auth/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await authenticateUser(email, password);

  if (!user) return res.status(401).json({ error: 'Invalid credentials' });

  req.session.userId = user.id;
  req.session.role = user.role;
  req.session.createdAt = Date.now();

  res.json({ message: 'Authenticated' });
});

// Session revocation
app.post('/auth/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) return res.status(500).json({ error: 'Logout failed' });
    res.clearCookie('scan_session');
    res.json({ message: 'Logged out' });
  });
});

Session-based auth provides immediate revocation capabilities and server-side audit trails for all active sessions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro