Dart HttpSession
last modified October 18, 2026
The HttpSession class in Dart provides server-side session
management for web applications. It allows storing user-specific data
between HTTP requests.
Sessions are essential for maintaining state in stateless HTTP. Dart's HttpSession uses the DARTSESSID cookie to track sessions.
Basic Definition
HttpSession represents a server-side session that persists
across multiple HTTP requests from the same client. It's part of Dart's
dart:io library.
Key features include key-value storage, session timeout control, and automatic session ID generation. Sessions are typically used for user authentication and preferences.
Basic Session Usage
This example shows basic session creation and data storage.
import 'dart:io';
void main() async {
var server = await HttpServer.bind('localhost', 8080);
server.listen((request) async {
var session = request.session;
session['visits'] = (session['visits'] ?? 0) + 1;
request.response.write('Visits: ${session['visits']}');
await request.response.close();
});
}
We create a server that tracks visit counts using sessions. The session is
available through the request.session getter. Each client gets a
unique session with persistent data, and Dart handles ID generation.
$ dart main.dart // Access http://localhost:8080 in browser // Output: Visits: 1 (increments on refresh)
Session Timeout Configuration
This example demonstrates setting session timeout duration.
import 'dart:io';
void main() async {
var server = await HttpServer.bind('localhost', 8080);
var timeout = 1800;
// The session timeout is specified in seconds.
server.sessionTimeout = timeout;
server.listen((request) async {
request.session['seen'] = true;
request.response.write('Session timeout: $timeout seconds');
await request.response.close();
});
}
We configure the server-wide session timeout to 1800 seconds (30 minutes). After inactivity, sessions expire automatically. The timeout applies to all sessions.
$ dart main.dart // Output: Session timeout: 1800 seconds
Session Data Management
This example shows comprehensive session data operations.
import 'dart:io';
void main() async {
var server = await HttpServer.bind('localhost', 8080);
server.listen((request) async {
var session = request.session;
var response = request.response;
if (request.uri.path == '/login') {
session['username'] = 'user123';
session['last_login'] = DateTime.now();
response.write('Logged in');
}
else if (request.uri.path == '/logout') {
session.destroy();
response.write('Logged out');
}
else {
response.write('''
Username: ${session['username']}
Last login: ${session['last_login']}
''');
}
await response.close();
});
}
We implement login/logout functionality with session storage. The destroy() method clears session data completely. Session values persist between requests.
$ dart main.dart // Access /login, then / to see stored data // Access /logout to clear session
Session ID Handling
This example demonstrates working with session IDs directly.
import 'dart:io';
void main() async {
var server = await HttpServer.bind('localhost', 8080);
server.listen((request) async {
var session = request.session;
var response = request.response;
response.write('''
Session ID: ${session.id}
Is new: ${session.isNew}
''');
await response.close();
});
}
We display the automatically generated session ID and whether the session is new. The isNew property helps identify first-time visitors.
$ dart main.dart // Output shows unique session ID and true/false for new session
Session Timeout Callback
This example registers a callback that runs when a session expires.
import 'dart:io';
void main() async {
var server = await HttpServer.bind('localhost', 8080);
server.sessionTimeout = 1800;
server.listen((request) async {
var session = request.session;
session.onTimeout = () {
print('Session timed out');
};
request.response.write('Session timeout callback registered');
await request.response.close();
});
}
The onTimeout callback is invoked when the session expires after
inactivity. This is useful for cleaning up session-specific resources.
$ dart main.dart // Registers a callback for when the session expires
Best Practices
- Minimize data: Store only essential data in sessions
- Secure transport: Serve session traffic over HTTPS
- Timeout: Set an appropriate session timeout
- Cleanup: Destroy sessions after logout
- Validation: Validate session data on each request
Source
Dart HttpSession Documentation
This tutorial covered Dart's HttpSession class with practical examples showing session management, configuration, and security best practices.
Author
List all Dart tutorials.