Sessions

suggest change

HTTP is inherently stateless. Web applications maintain state across requests—such as logged-in user identities, flash notifications, or shopping cart contents—using sessions.

In Dart server-side development (using frameworks like Shelf, Dart Frog, or Serverpod), sessions are typically managed via session cookies referencing server-side stores (like in-memory caches or Redis).


Session Architecture

Client (Browser)                        Dart Server (Shelf)                   Session Store
       |                                         |                                  |
1. POST /login (credentials)                     |                                  |
       | --------------------------------------> |                                  |
       |                                         | 2. Create session & token        |
       |                                         | -------------------------------> | (Store data)
       | 3. Set-Cookie: session_id=abc; HttpOnly |                                  |
       | <-------------------------------------- |                                  |
       |                                         |                                  |
4. GET /dashboard (Cookie: session_id=abc)       |                                  |
       | --------------------------------------> | 5. Fetch session for 'abc'       |
       |                                         | -------------------------------> |
       |                                         | <------------------------------- | (User: Alice)
       | 6. HTTP 200 (Dashboard Content)         |                                  |
       | <-------------------------------------- |                                  |

Building a Session Store

A session store provides asynchronous lookup, creation, and invalidation:

import 'dart:math';

class Session {
  final String id;
  final Map<String, dynamic> data;
  final DateTime expiresAt;

  Session({required this.id, required this.data, required this.expiresAt});

  bool get isExpired => DateTime.now().isAfter(expiresAt);
}

abstract class SessionStore {
  Future<Session?> get(String sessionId);
  Future<Session> create(Map<String, dynamic> data, {Duration ttl = const Duration(hours: 24)});
  Future<void> destroy(String sessionId);
}

class InMemorySessionStore implements SessionStore {
  final Map<String, Session> _store = {};
  final _random = Random.secure();

  String _generateToken() {
    final values = List<int>.generate(32, (i) => _random.nextInt(256));
    return values.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
  }

  @override
  Future<Session> create(Map<String, dynamic> data, {Duration ttl = const Duration(hours: 24)}) async {
    final id = _generateToken();
    final session = Session(
      id: id,
      data: Map<String, dynamic>.from(data),
      expiresAt: DateTime.now().add(ttl),
    );
    _store[id] = session;
    return session;
  }

  @override
  Future<Session?> get(String sessionId) async {
    final session = _store[sessionId];
    if (session == null) return null;
    if (session.isExpired) {
      _store.remove(sessionId);
      return null;
    }
    return session;
  }

  @override
  Future<void> destroy(String sessionId) async {
    _store.remove(sessionId);
  }
}

Shelf Session Middleware

In a Shelf backend, middleware intercepts incoming HTTP requests, parses the Cookie header, looks up the active session, and attaches it to the request context:

import 'package:shelf/shelf.dart';

Middleware sessionMiddleware(SessionStore store) {
  return (Handler innerHandler) {
    return (Request request) async {
      final cookieHeader = request.headers['cookie'];
      String? sessionId;

      if (cookieHeader != null) {
        // Parse "session_id=value" from cookie string
        final cookies = cookieHeader.split(';').map((c) => c.trim());
        for (final cookie in cookies) {
          if (cookie.startsWith('session_id=')) {
            sessionId = cookie.substring('session_id='.length);
            break;
          }
        }
      }

      Session? session;
      if (sessionId != null) {
        session = await store.get(sessionId);
      }

      // Attach session to request context
      final updatedRequest = request.change(context: {
        'session': session,
        'sessionStore': store,
      });

      return await innerHandler(updatedRequest);
    };
  };
}

Complete Shelf Application Example

Here is how to wire routes for login, reading session data, and logout:

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

void main() async {
  final sessionStore = InMemorySessionStore();
  final app = Router();

  // Login: creates a new session and sets the HttpOnly cookie
  app.post('/login', (Request request) async {
    // In production, validate user credentials against database here
    final session = await sessionStore.create({'username': 'alice', 'role': 'admin'});

    final cookieVal = 'session_id=${session.id}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400';

    return Response.ok('Logged in successfully', headers: {
      'Set-Cookie': cookieVal,
    });
  });

  // Protected route: reads session data from context
  app.get('/profile', (Request request) {
    final session = request.context['session'] as Session?;
    if (session == null) {
      return Response.forbidden('Unauthorized: no valid session found');
    }

    final username = session.data['username'];
    final role = session.data['role'];
    return Response.ok('Welcome $username! Your role is $role.');
  });

  // Logout: destroys session and clears cookie
  app.post('/logout', (Request request) async {
    final session = request.context['session'] as Session?;
    if (session != null) {
      await sessionStore.destroy(session.id);
    }

    final expiredCookie = 'session_id=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0';
    return Response.ok('Logged out', headers: {'Set-Cookie': expiredCookie});
  });

  final handler = const Pipeline()
      .addMiddleware(logRequests())
      .addMiddleware(sessionMiddleware(sessionStore))
      .addHandler(app.call);

  final server = await io.serve(handler, 'localhost', 8080);
  print('Server running on http://${server.address.host}:${server.port}');
}

Redis-Backed Distributed Sessions

For clustered Dart servers where requests may be handled by different isolate instances or multiple container pods, persist sessions in Redis using package:redis:

import 'dart:convert';
import 'package:redis/redis.dart';

class RedisSessionStore implements SessionStore {
  final Command _cmd;

  RedisSessionStore(this._cmd);

  @override
  Future<Session> create(Map<String, dynamic> data, {Duration ttl = const Duration(hours: 24)}) async {
    final id = 'sess_${DateTime.now().microsecondsSinceEpoch}';
    final serialized = jsonEncode(data);
    await _cmd.send_object(['SET', 'session:$id', serialized, 'EX', ttl.inSeconds.toString()]);
    return Session(id: id, data: data, expiresAt: DateTime.now().add(ttl));
  }

  @override
  Future<Session?> get(String sessionId) async {
    final res = await _cmd.send_object(['GET', 'session:$sessionId']);
    if (res == null) return null;
    final data = jsonDecode(res.toString()) as Map<String, dynamic>;
    return Session(id: sessionId, data: data, expiresAt: DateTime.now().add(const Duration(hours: 1)));
  }

  @override
  Future<void> destroy(String sessionId) async {
    await _cmd.send_object(['DEL', 'session:$sessionId']);
  }
}

Security Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents