The Surreal class is the primary interface for connecting to a SurrealDB instance, managing connections, executing queries, and handling database sessions. It extends SurrealSession and inherits all session management and query execution capabilities.
By default, a Surreal instance operates with a default session scope, but you can create additional isolated sessions using the session management methods.
Extends: SurrealSession → SurrealQueryable
Source: api/surreal.ts
Constructor
Syntax
new Surreal(options?)Parameters
Parameter | Type | Description |
|---|---|---|
options | DriverOptions | Driver-wide configuration options for customizing engines, codecs, and implementations. |
Examples
import { Surreal } from 'surrealdb';
const db = new Surreal();import { Surreal } from 'surrealdb';
const db = new Surreal({
codecOptions: {
useNativeDates: true // Use native Date objects instead of DateTime
}
});Properties
status
Returns the current connection status.
Type: ConnectionStatus
Values: "disconnected" | "connecting" | "reconnecting" | "connected"
Example:
console.log(db.status); // "connected" isConnected
Returns whether the connection is currently established. This is equivalent to checking if status === "connected".
Type: boolean
Example:
if (db.isConnected) {
console.log('Database is connected');
} ready
A promise that resolves when the connection is established and ready, or rejects if a connection error occurs.
**Type:** `Promise`
Example:
await db.ready;
console.log('Connection is ready');Inherited properties
The Surreal class inherits all properties from SurrealSession, including:
namespace- Current namespacedatabase- Current databaseaccessToken- Current access tokenparameters- Session parameterssession- Session IDisValid- Session validity status
Connection methods
.connect()
Connect to a local or remote SurrealDB instance.
Calling connect() will reset and dispose of any existing sessions created with newSession().
db.connect(url, opts?)Parameters
Parameter | Type | Description |
|---|---|---|
url | string | URL | The endpoint URL to connect to (e.g., "ws://localhost:8000", "http://localhost:8000/rpc"). |
opts | ConnectOptions | Connection-specific options such as namespace, database, and authentication. |
Returns
`Promise` - Resolves when connection is successful
Examples
await db.connect('ws://localhost:8000');await db.connect('http://localhost:8000/rpc');await db.connect('ws://localhost:8000', {
namespace: 'my_namespace',
database: 'my_database'
});await db.connect('ws://localhost:8000', {
namespace: 'my_namespace',
database: 'my_database',
authentication: {
username: 'root',
password: 'root'
}
});await db.connect('ws://localhost:8000', {
reconnect: {
enabled: true,
attempts: 10,
retryDelay: 1000,
retryDelayMax: 10000,
retryDelayMultiplier: 2
}
}); .close()
Disconnect from the active SurrealDB instance.
db.close()Returns
`Promise` - Resolves when disconnection is successful
Example
await db.close();
console.log('Connection closed'); .health()
Check the health status of the connected SurrealDB instance.
db.health()Returns
`Promise` - Resolves if the instance is healthy, rejects otherwise
Example
try {
await db.health();
console.log('Database is healthy');
} catch (error) {
console.error('Health check failed:', error);
} .version()
Retrieve version information from the connected SurrealDB instance.
db.version()Returns
[`Promise`](/docs/languages/javascript/api/types/#versioninfo) - An object containing version information
Example
const info = await db.version();
console.log(info.version); // "surrealdb-2.1.0" .isFeatureSupported()
Check whether a specific feature is available in the current connection.
db.isFeatureSupported(feature)Parameters
Parameter | Type | Description |
|---|---|---|
feature | Feature | A feature from the Featuresobject (e.g. Features.LiveQueries, Features.Api). |
Returns
boolean - true if the feature is supported, false otherwise
Example
import { Surreal, Features } from 'surrealdb';
if (db.isFeatureSupported(Features.LiveQueries)) {
console.log('Live queries are supported');
}Session management methods
.sessions()
List all active sessions on the current connection.
db.sessions()Returns
`Promise` - An array of session IDs
Example
const sessionIds = await db.sessions();
console.log('Active sessions:', sessionIds); .newSession()
Create a new isolated session on the current connection. The new session will have its own namespace, database, variables, and authentication state, but will share the same connection.
Sessions are automatically restored when the connection reconnects. Call reset() on the returned session to destroy it.
db.newSession()Returns
`Promise` - A new [`SurrealSession`](/docs/languages/javascript/api/core/surreal-session) instance
Example
// Create a new isolated session
const session = await db.newSession();
// Use different namespace/database in the new session
await session.use({ namespace: 'other_ns', database: 'other_db' });
// Query in the new session context
const results = await session.select('users');
// Destroy the session when done
await session.reset(); .closeSession()
Close the primary session. This is equivalent to calling close() on the connection.
db.closeSession()Returns
`Promise` - Resolves when the session is closed
Example
await db.closeSession();Data management methods
.export()
Export the database contents as a SQL string.
db.export(options?)Parameters
Parameter | Type | Description |
|---|---|---|
options | Partial SqlExportOptions | Options to customize what gets exported. |
Returns
ExportPromise - A promise that resolves to the exported database as a SQL string. Has a .raw() method that returns the raw Response object.
Examples
const sql = await db.export();const sql = await db.export({
tables: ['users', 'posts'],
records: true
});const sql = await db.export({
records: false,
tables: true,
functions: true
});const response = await db.export().raw(); .import()
Import database contents from a SQL string or a readable stream.
db.import(input)Parameters
Parameter | Type | Description |
|---|---|---|
input | string | ReadableStream<string> | The SQL string or readable stream to import into the database. |
Returns
`Promise` - Resolves when the import is complete
Example
const sqlData = `
DEFINE TABLE users SCHEMAFULL;
DEFINE FIELD name ON users TYPE string;
CREATE users:john SET name = 'John Doe';
`;
await db.import(sqlData);
console.log('Data imported successfully'); .exportModel()
Export a SurrealML model from the database.
db.exportModel(name, version)Parameters
Parameter | Type | Description |
|---|---|---|
name | string | The name of the SurrealML model to export. |
version | string | The version of the model to export. |
Returns
ExportModelPromise - A promise that resolves to the exported model data. Has a .raw() method that returns the raw Response object.
Example
const modelData = await db.exportModel('my_model', '1.0.0');const response = await db.exportModel('my_model', '1.0.0').raw();Events
The Surreal class implements the EventPublisher interface and emits various events during the connection lifecycle. Subscribe to events using the subscribe() method.
connecting
Emitted when the connection attempt starts.
Payload: None
Example:
const unsubscribe = db.subscribe('connecting', () => {
console.log('Connecting to database...');
}); connected
Emitted when the connection is successfully established.
Payload: [version: string] - The SurrealDB version string
Example:
db.subscribe('connected', (version) => {
console.log('Connected to SurrealDB version:', version);
}); reconnecting
Emitted when the connection is attempting to reconnect after being disconnected.
Payload: None
Example:
db.subscribe('reconnecting', () => {
console.log('Attempting to reconnect...');
}); disconnected
Emitted when the connection is closed.
Payload: None
Example:
db.subscribe('disconnected', () => {
console.log('Disconnected from database');
}); error
Emitted when a connection error occurs.
Payload: [error: Error] - The error object
Example:
db.subscribe('error', (error) => {
console.error('Connection error:', error.message);
});Inherited events
The Surreal class also inherits and re-emits events from SurrealSession:
auth- Emitted when authentication state changesusing- Emitted when namespace/database changes
.subscribe()
Subscribe to connection and session events.
db.subscribe(event, listener)Parameters
Parameter | Type | Description |
|---|---|---|
event | keyof SurrealEvents | The event name to subscribe to. |
listener | Function | Callback function invoked when the event is emitted. |
Returns
() => void - An unsubscribe function to remove the event listener
Example
const unsubscribe = db.subscribe('connected', (version) => {
console.log('Connected:', version);
});
// Later, unsubscribe from the event
unsubscribe();Inherited methods
As Surreal extends SurrealSession, it inherits all authentication and query methods:
Authentication methods
signup()- Sign up a new usersignin()- Sign in with credentialsauthenticate()- Authenticate with a tokeninvalidate()- Invalidate the session
Session configuration methods
use()- Set namespace and databaseset()- Set a session parameterunset()- Remove a session parameterreset()- Reset the session
Query methods
As Surreal extends SurrealQueryable (via SurrealSession), it also inherits all query execution methods:
query()- Execute raw SurrealQLselect()- Select recordscreate()- Create recordsinsert()- Insert recordsupdate()- Update recordsupsert()- Upsert recordsdelete()- Delete recordsrelate()- Create graph relationshipslive()- Subscribe to live queriesrun()- Execute functions
Transaction method
beginTransaction()- Start a transaction
Type parameters
This class does not use generic type parameters.
Complete example
import { Surreal } from 'surrealdb';
// Create and connect
const db = new Surreal({
codecOptions: {
useNativeDates: true
}
});
// Subscribe to connection events
db.subscribe('connecting', () => console.log('Connecting...'));
db.subscribe('connected', (version) => console.log('Connected:', version));
db.subscribe('error', (error) => console.error('Error:', error));
// Connect to database
await db.connect('ws://localhost:8000', {
namespace: 'my_namespace',
database: 'my_database',
authentication: {
username: 'root',
password: 'root'
}
});
// Check connection status
console.log('Connected:', db.isConnected); // true
console.log('Status:', db.status); // "connected"
// Get version info
const version = await db.version();
console.log('Version:', version.version);
// Execute queries (inherited from SurrealSession/SurrealQueryable)
const users = await db.select('users');
console.log('Users:', users);
// Create a new isolated session
const session = await db.newSession();
await session.use({ namespace: 'other_ns', database: 'other_db' });
const otherData = await session.select('data');
// Export database
const backup = await db.export({ records: true });
console.log('Backup size:', backup.length);
// Close connection
await db.close();See also
SurrealSession - Session management and authentication
SurrealQueryable - Query execution methods
SurrealTransaction - Transaction support
Connection Engines - Engine-specific documentation
Data types - Working with data types