A single WebSocket connection can host multiple independent sessions, each with its own authentication, namespace, database, and parameters. This is useful for multi-tenant applications where requests act on behalf of different users over one shared connection. The SurrealClient is itself the root session.
Multiple sessions require a stateful connection and are only available over the WebSocket transport. Check support with client.supports(SurrealFeature.Sessions).
API references
Method | Description |
|---|---|
client.newSession() | Creates a new isolated session |
client.closeSession(session) | Closes a session |
Creating sessions
Each session created with .newSession() is a SurrealSession that exposes the same querying and authentication API as the client, but with isolated state.
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
val tenantA = client.newSession()
val tenantB = client.newSession()
tenantA.signin(buildJsonObject { put("user", "a"); put("pass", "a") })
tenantA.use("acme", "main")
tenantB.signin(buildJsonObject { put("user", "b"); put("pass", "b") })
tenantB.use("globex", "main")
// Each query runs as its own authenticated tenant, isolated from the other.
val aPeople = tenantA.query("SELECT * FROM person")
val bPeople = tenantB.query("SELECT * FROM person")Closing sessions
Close a session with .closeSession() when you no longer need it. This does not close the underlying connection.
client.closeSession(tenantA)Learn more
Session reference for the session API
Authentication for per-session credentials
Transactions — transactions run within a session