SurrealSession
The SurrealSession class represents a scoped contextual session attached to a SurrealDB connection. It provides authentication, session configuration, and inherits all query execution methods from SurrealQueryable.
Sessions allow you to maintain isolated contexts with their own namespace, database, variables, and authentication state, while sharing the underlying connection.
Extends: SurrealQueryable
Extended by: Surreal
Source: api/session.ts
Constructor
The constructor is typically not called directly. Use Surreal.newSession() or forkSession() to create new sessions.
Properties
namespace
Returns the currently selected namespace for this session.
Type: string | undefined
Example:
console.log(session.namespace);
database
Returns the currently selected database for this session.
Type: string | undefined
Example:
console.log(session.database);
accessToken
Returns the current authentication access token for this session.
Type: string | undefined
Example:
if (session.accessToken) {
console.log('Session is authenticated');
}
parameters
Returns all parameters currently defined on the session.
Type: Record<string, unknown>
Example:
console.log(session.parameters);
session
Returns the unique session ID. For the default session, undefined is returned.
Type: Uuid | undefined
Example:
const sessionId = session.session;
console.log('Session ID:', sessionId);
isValid
Returns whether the session is valid and can be used. This is always true for the default session, but will be false for sessions that have been disposed via reset() or closeSession().
Type: boolean
Example:
if (session.isValid) {
await session.select('users');
} else {
console.log('Session has been closed');
}
Session Management Methods
.forkSession()
Create a new session by cloning the current session. The new session inherits all properties from the parent session including namespace, database, variables, and authentication state.
Sessions are automatically restored when the connection reconnects. Call reset() on the created session to destroy it.
Method Syntax
session.forkSession()
Returns
Promise<SurrealSession> - A new session instance
Example
const childSession = await session.forkSession();
console.log(childSession.namespace);
console.log(childSession.database);
await childSession.use({ database: 'other_db' });
console.log(session.database);
console.log(childSession.database);
await childSession.reset();
.closeSession()
Closes the current session and disposes of it. After this method is called, the session cannot be used again, and isValid will return false.
Method Syntax
session.closeSession()
Returns
Promise<void> - Resolves when the session is closed
Example
await session.closeSession();
console.log(session.isValid);
Transaction Methods
.beginTransaction()
Create a new transaction scoped to the current session. Transactions allow you to execute multiple queries atomically.
Call commit() on the transaction to apply changes, or cancel() to discard them.
Method Syntax
session.beginTransaction()
Returns
Promise<SurrealTransaction> - A new SurrealTransaction instance
Example
const txn = await session.beginTransaction();
try {
await txn.create(new RecordId('users', 'john'), {
content: { name: 'John Doe', email: 'john@example.com' }
});
await txn.create(new RecordId('posts', '1'), {
content: { author: new RecordId('users', 'john'), title: 'Hello' }
});
await txn.commit();
console.log('Transaction committed successfully');
} catch (error) {
await txn.cancel();
console.error('Transaction cancelled:', error);
}
Session Configuration Methods
.use()
Switch to the specified namespace and/or database for this session.
Leaving the namespace or database undefined will leave the current value unchanged, while passing null will unset the selected namespace or database.
Method Syntax
session.use(what)
Parameters
| Parameter | Type | Description |
|---|
what required | NamespaceDatabase | null | Object specifying namespace and/or database to switch to. |
Returns
Promise<NamespaceDatabase> - The newly selected namespace and database
Examples
Switch Both Namespace and Database
await session.use({
namespace: 'production',
database: 'main'
});
Switch Only Database
await session.use({
database: 'analytics'
});
Unset Database
await session.use({
database: null
});
.set()
Define a variable for the current session. Variables can be used in SurrealQL queries with the $ prefix.
Method Syntax
session.set(variable, value)
Parameters
| Parameter | Type | Description |
|---|
variable required | string | The name of the variable (without the $ prefix). |
value required | unknown | The value to assign to the variable. |
Returns
Promise<void> - Resolves when the variable is set
Example
await session.set('user_id', '12345');
const result = await session.query(
'SELECT * FROM posts WHERE author = $user_id'
).collect();
.unset()
Remove a variable from the current session.
Method Syntax
session.unset(variable)
Parameters
| Parameter | Type | Description |
|---|
variable required | string | The name of the variable to remove (without the $ prefix). |
Returns
Promise<void> - Resolves when the variable is removed
Example
await session.unset('user_id');
.reset()
Resets the current session to its initial state, clearing authentication state, variables, and selected namespace/database.
For non-default sessions, this also closes and disposes of the session.
Method Syntax
session.reset()
Returns
Promise<void> - Resolves when the session is reset
Example
await session.reset();
console.log(session.namespace);
console.log(session.accessToken);
console.log(session.parameters);
Authentication Methods
.signup()
Sign up a new record user to the SurrealDB instance.
When this method is called, the authentication property passed to connect() will be ignored. You are responsible for handling session invalidation by listening to the auth event.
Method Syntax
session.signup(auth)
Parameters
| Parameter | Type | Description |
|---|
auth required | AccessRecordAuth | The authentication details including access method and record data. |
Returns
Promise<Tokens> - The authentication tokens (access and refresh tokens)
Example
const tokens = await session.signup({
namespace: 'my_namespace',
database: 'my_database',
access: 'user_access',
variables: {
email: 'user@example.com',
password: 'secure_password',
name: 'John Doe'
}
});
console.log('Access token:', tokens.access);
console.log('Refresh token:', tokens.refresh);
.signin()
Sign in to the SurrealDB instance with authentication credentials.
When this method is called, the authentication property passed to connect() will be ignored. You are responsible for handling session invalidation by listening to the auth event.
Method Syntax
session.signin(auth)
Parameters
| Parameter | Type | Description |
|---|
auth required | AnyAuth | Authentication details (system user, record user, or access method). |
Returns
Promise<Tokens> - The authentication tokens
Examples
System User Authentication
const tokens = await session.signin({
username: 'root',
password: 'root'
});
Record User Authentication
const tokens = await session.signin({
namespace: 'my_namespace',
database: 'my_database',
access: 'user_access',
variables: {
email: 'user@example.com',
password: 'secure_password'
}
});
.authenticate()
Authenticate the session using an existing access token or access and refresh token combination.
When authenticating with a refresh token, a new refresh token will be issued and returned.
When this method is called, the authentication property passed to connect() will be ignored. You are responsible for handling session invalidation by listening to the auth event.
Method Syntax
session.authenticate(token)
Parameters
| Parameter | Type | Description |
|---|
token required | string | Tokens | The access token string or tokens object with access and refresh tokens. |
Returns
Promise<Tokens> - The authentication tokens (may include new refresh token)
Examples
Authenticate with Access Token
await session.authenticate(accessToken);
Authenticate with Refresh Token
const newTokens = await session.authenticate({
access: oldAccessToken,
refresh: refreshToken
});
console.log('New access token:', newTokens.access);
console.log('New refresh token:', newTokens.refresh);
.invalidate()
Invalidate the authentication for the current session, signing the user out.
Method Syntax
session.invalidate()
Returns
Promise<void> - Resolves when authentication is invalidated
Example
await session.invalidate();
console.log('User signed out');
Events
The SurrealSession class emits events that you can subscribe to for tracking session state changes.
auth
Emitted when the authentication state changes for this session.
Payload: [tokens: Tokens | null] - The new authentication tokens, or null if invalidated
Example:
session.subscribe('auth', (tokens) => {
if (tokens) {
console.log('Authenticated with token:', tokens.access);
} else {
console.log('Authentication invalidated');
}
});
using
Emitted when the namespace or database changes for this session.
Payload: [using: NamespaceDatabase] - Object containing the new namespace and database
Example:
session.subscribe('using', (using) => {
console.log('Now using:', using.namespace, '/', using.database);
});
.subscribe()
Subscribe to session events.
Method Syntax
session.subscribe(event, listener)
Parameters
| Parameter | Type | Description |
|---|
event required | keyof SessionEvents | The event name to subscribe to (“auth” or “using”). |
listener required | Function | Callback function invoked when the event is emitted. |
Returns
() => void - An unsubscribe function
Example
const unsubscribe = session.subscribe('auth', (tokens) => {
console.log('Auth changed:', tokens);
});
unsubscribe();
Inherited Methods
As SurrealSession extends SurrealQueryable, it inherits all query execution methods:
Complete Example
import { Surreal } from 'surrealdb';
const db = new Surreal();
await db.connect('ws://localhost:8000');
await db.use({ namespace: 'test', database: 'test' });
await db.signin({
username: 'root',
password: 'root'
});
const session = await db.newSession();
await session.use({
namespace: 'production',
database: 'main'
});
await session.set('user_role', 'admin');
session.subscribe('auth', (tokens) => {
console.log('Session auth changed:', tokens ? 'authenticated' : 'signed out');
});
session.subscribe('using', (using) => {
console.log('Using:', using);
});
const tokens = await session.signin({
namespace: 'production',
database: 'main',
access: 'user_access',
variables: {
email: 'user@example.com',
password: 'password'
}
});
const users = await session.select('users');
const txn = await session.beginTransaction();
await txn.create('logs:1', { content: { message: 'User logged in' } });
await txn.commit();
const childSession = await session.forkSession();
await childSession.use({ database: 'analytics' });
await childSession.reset();
await session.closeSession();
See Also