Multiple sessions
The JavaScript SDK allows you to create multiple isolated sessions within a single connection. Each session maintains its own namespace, database, variables, and authentication state, while sharing the underlying connection to SurrealDB. This is useful when different parts of your application need to operate under different credentials or contexts simultaneously.
API References
| Method | Description |
|---|---|
db.newSession() | Creates a new isolated session on the connection |
session.forkSession() | Creates a copy of a session, inheriting its state |
session.closeSession() | Destroys a session and releases its resources |
session.reset() | Resets a session's state without destroying it |
Creating isolated sessions
Call .newSession() on a Surreal instance to create a new session. The new session starts with no namespace, database, or authentication, and must be configured independently.
Sessions support all the same query methods as the main Surreal instance, including .query(), .select(), .create(), .update(), .delete(), and more.
Forking an existing session
The .forkSession() method creates a new session that inherits the namespace, database, variables, and authentication state from the parent session. This is useful when you need a temporary context that starts with the same setup.
The forked session operates independently after creation. Changes to the parent session do not affect the fork, and vice versa.
Automatic cleanup with await using
Sessions support the await using declaration. When you declare a session with await using, JavaScript automatically closes the session when execution leaves the current scope.
This is equivalent to manually calling session.closeSession() in a finally block, but with cleaner syntax.
Closing and resetting sessions
When you are done with a session, call .closeSession() to destroy it and release server-side resources.
If you want to clear a session's state without destroying it, use .reset(). This removes all variables and invalidates authentication, but keeps the session alive for reuse.
Note
Reconnection behavior
Sessions are automatically restored when the underlying connection reconnects after a drop. The SDK re-establishes each session's namespace, database, variables, and authentication state on the server. If a session used the authentication property from the original .connect() call, it will be re-authenticated automatically.
Sessions that were authenticated via .signin() or .signup() rely on the auth event for re-authentication. See Authentication for details.
Subscribing to session events
Each session emits its own events, independent of other sessions and the main Surreal instance. You can subscribe to the auth and using events on any session.
Learn more
SurrealSession API reference for the full session interface
Surreal.newSession() for session creation details
Authentication for session-level authentication
Transactions for atomic operations within sessions