write method

  1. @override
Future<void> write(
  1. Request request,
  2. Response response,
  3. Session session
)
override

Writes the session data to the underlying storage.

This method persists the session data using a storage mechanism like a cookie, file, or database. It receives the request, response, and session objects.

The request object provides context for the session. The response object allows modifying the outgoing response (e.g., setting cookies). The session object contains the data to be saved.

Returns a Future<void> that completes when the session is successfully saved.

Example:

await store.write(request, response, session);

Implementation

@override
Future<void> write(
  Request request,
  Response response,
  Session session,
) async {
  if (session.isDestroyed) {
    response.setCookie(
      session.name,
      '',
      maxAge: 0,
      path: session.options.path ?? defaultOptions.path ?? '/',
      domain: session.options.domain ?? defaultOptions.domain ?? '',
    );
    return;
  }

  final sessionData = session.toMap();

  var encoded = jsonEncode(sessionData);
  encoded = _primaryCodec.encode(session.name, {'data': encoded});
  final serialized = Uri.encodeComponent(encoded);

  response.setCookie(
    session.name,
    serialized,
    maxAge: session.options.maxAge ?? defaultOptions.maxAge,
    path: session.options.path ?? defaultOptions.path ?? '/',
    domain: session.options.domain ?? defaultOptions.domain ?? '',
    secure: session.options.secure ?? defaultOptions.secure ?? false,
    httpOnly: session.options.httpOnly ?? defaultOptions.httpOnly ?? true,
    sameSite: session.options.sameSite ?? defaultOptions.sameSite,
  );
}