mcpField
S
serverpod-sessions

serverpod-sessions

github.com/serverpodDevelopment3.3k44 installsUpdated 1d ago
Repository

About serverpod-sessions

A Serverpod skill explaining session lifetimes, available session types, and safe manual session management. It highlights cleanup, error logging, and avoiding use of a request session after its lifetime ends.

Key features

  1. 01Session types and lifetimes
  2. 02Automatic session lifecycle management
  3. 03Manual sessions with withSession
  4. 04Cleanup callbacks
  5. 05Guidance on avoiding closed sessions

Use cases

  1. 01Choose a session type for a task
  2. 02Manage a session for internal work
  3. 03Avoid using request sessions after return

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/serverpod/serverpod --skill serverpod-sessions

After installing, type/serverpod-sessionsin Claude Code to confirm it loaded.

Details

From the project README

Serverpod Sessions

A Session provides access to database, cache, storage, messages, passwords, and logging. The framework creates and closes sessions automatically; only InternalSession requires manual management. Do not store a request session for work that outlives the request/stream/future call.

Session types

TypeCreated forLifetime
MethodCallSessionEndpoint methodsSingle request
WebCallSessionWeb server routesSingle request
MethodStreamSessionStream methodsStream duration
FutureCallSessionFuture callsTask execution
InternalSessionManual creationUntil closed

Manual sessions (InternalSession)

Prefer withSession, which closes the session for you and attaches the error and stack trace to the logs if the callback throws:

await Serverpod.instance.withSession((session) async {
  await doWork(session);
});

When the lifetime cannot be expressed as a callback, create the session manually and always close it in a finally block:

var session = await Serverpod.instance.createSession();
try {
  await doWork(session);
} finally {
  await session.close();
}

Unclosed sessions leak memory and never persist logs. Using a closed session throws StateError.

Cleanup callbacks

session.addWillCloseListener((session) async {
  // Runs just before session closes (all session types)
});

Common pitfall: using session after method returns

Sessions close when the endpoint returns. Do not capture for later use:

// BAD — session already closed when callback runs
Timer(Duration(seconds: 5), () => user.updateLastSeen(session));

Fix: Use a future call (session.serverpod.futureCalls.callWithDelay(...)) or open a new session inside the callback with Serverpod.instance.withSession(...).

Comments

Markdown supported