Basics / Sessions

Session & Flash Messages

HTTP is a stateless protocol. To preserve information across requests, Archery provides a robust session system powered by secure cookies and an in-memory session registry backed by database persistence.

The Session Lifecycle

Out of the box, Archery assigns a unique session token to every visitor using the archery_guest_session cookie. This session powers CSRF validation and temporary data storage.

When a user logs in, the framework manages an elevated AuthSession that ties their browser securely to a registered User account.

Accessing the Session

You can access the active session for the current request using the thisSession extension property available on any HttpRequest:

final session = request.thisSession;

if (session != null) {
  print('Active session token: ${session.token}');
  print('Last activity: ${session.lastActivity}');
}

The Session object provides three dictionaries for storing data:

  • data: General-purpose session storage.
  • errors: Used to store validation failures.
  • flashMessages: Used to store success/informational notes.
request.thisSession?.data['cart_id'] = 12345;

Flash Messages

It's extremely common to want to store data during one request, such as a successful form submission, and display it during the very next request (usually after a redirect). This is exactly what Flash Messages are designed to do.

Flashing Data

You can flash a message to the session using the elegant request.flash helper:

router.post('/profile', (request) async {
  // Update profile logic...

  request.flash(
    key: 'success', 
    message: 'Your profile has been updated!'
  );
  
  return request.redirectBack();
});

By default, this stores the message in the flashMessages bucket. You can also specify the target bucket by providing a FlashMessageType:

request.flash(
  key: 'email', 
  message: 'This email is already taken.',
  type: FlashMessageType.error
);

Flash messages are automatically cleared after they have survived their intentional short lifespan across the request-response boundary.