Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Session Management

Server-side session storage with support for memory and Redis stores for scalable session management.

Basic Session Setup

MoroJS provides built-in session management middleware with support for memory-based and Redis-based session storage.

Memory-Based Sessions

typescript

1import { session } from '@morojs/moro';
2
3// Memory-based sessions (development)
4app.use(session({
5  secret: 'your-secret-key',
6  store: 'memory',
7  cookie: {
8    maxAge: 24 * 60 * 60 * 1000, // 24 hours
9    httpOnly: true,
10    secure: process.env.NODE_ENV === 'production',
11    sameSite: 'strict'
12  }
13}));
14
15// Using sessions
16app.post('/login', (req, res) => {
17  req.session.userId = user.id;
18  req.session.role = user.role;
19  return { success: true };
20});
21
22app.get('/profile', (req, res) => {
23  if (!req.session.userId) {
24    return res.status(401).json({ error: 'Unauthorized' });
25  }
26  return { userId: req.session.userId };
27});
28
29app.post('/logout', (req, res) => {
30  req.session.destroy();
31  return { success: true };
32});

Session Features

  • • Secure session cookie with httpOnly flag
  • • Automatic session expiration
  • • Session data stored server-side
  • • Support for memory and Redis stores
  • • Automatic session cleanup

Redis Session Storage

Redis-Based Sessions

typescript

1import { session } from '@morojs/moro';
2
3// Redis sessions (production)
4app.use(session({
5  secret: process.env.SESSION_SECRET,
6  store: 'redis',
7  redis: {
8    host: 'localhost',
9    port: 6379,
10    password: process.env.REDIS_PASSWORD
11  },
12  cookie: {
13    maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
14    httpOnly: true,
15    secure: true,
16    sameSite: 'strict'
17  }
18}));
19
20// Sessions are automatically stored in Redis
21app.post('/login', (req, res) => {
22  req.session.userId = user.id;
23  req.session.role = user.role;
24  req.session.lastLogin = new Date().toISOString();
25  return { success: true };
26});

Best Practices

Do

  • • Use Redis for production deployments
  • • Set secure cookie flags in production
  • • Use strong session secrets
  • • Set appropriate maxAge values
  • • Destroy sessions on logout
  • • Store minimal data in sessions

Don't

  • • Store sensitive data in sessions
  • • Use memory store in production
  • • Use weak session secrets
  • • Set very long session expiration
  • • Store large objects in sessions
  • • Skip session cleanup

Related Features