# Surreal

The Surreal class is the main entry point for connecting to and interacting with a SurrealDB instance.

The `Surreal` class is the primary interface for connecting to a SurrealDB instance, managing connections, executing queries, and handling database sessions. It extends [`SurrealSession`](/docs/reference/javascript/api/core/surreal-session.md) 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`](/docs/reference/javascript/api/core/surreal-session.md) → [`SurrealQueryable`](/docs/reference/javascript/api/core/surreal-queryable.md)

**Source:** [api/surreal.ts](https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/api/surreal.ts)

## Constructor

### Syntax
```ts title="Constructor Syntax"
new Surreal(options?)
```

### Parameters

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>options</code> <label label="optional" /></td>
            <td><code><a href="/docs/reference/javascript/api/types/#driveroptions">DriverOptions</a></code></td>
            <td>Driver-wide configuration options for customising engines, codecs, and implementations.</td>
        </tr>
    </tbody>
</table>

### Examples

```ts title="Basic Usage"
import { Surreal } from 'surrealdb';

const db = new Surreal();
```

```ts title="With Custom Options"
import { Surreal } from 'surrealdb';

const db = new Surreal({
    codecOptions: {
        useNativeDates: true // Use native Date objects instead of DateTime
    }
});
```

## Properties

### `status` {#status}

Returns the current connection status.

**Type:** [`ConnectionStatus`](/docs/reference/javascript/api/types/#connectionstatus)

**Values:** `"disconnected"` | `"connecting"` | `"reconnecting"` | `"connected"`

**Example:**
```ts
console.log(db.status); // "connected"
```

### `isConnected` {#isconnected}

Returns whether the connection is currently established. This is equivalent to checking if `status === "connected"`.

**Type:** `boolean`

**Example:**
```ts
if (db.isConnected) {
    console.log('Database is connected');
}
```

### `ready` {#ready}

A promise that resolves when the connection is established and ready, or rejects if a connection error occurs.

**Type:** `Promise<void>`

**Example:**
```ts
await db.ready;
console.log('Connection is ready');
```

### Inherited properties

The `Surreal` class inherits all properties from [`SurrealSession`](/docs/reference/javascript/api/core/surreal-session.md), including:

- `namespace` - Current namespace
- `database` - Current database
- `accessToken` - Current access token
- `parameters` - Session parameters
- `session` - Session ID
- `isValid` - Session validity status

## Connection methods

### `.connect()` {#connect}

Connect to a local or remote SurrealDB instance.

> [!WARNING]
> Calling `connect()` will reset and dispose of any existing sessions created with `newSession()`.

```ts title="Method Syntax"
db.connect(url, opts?)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>url</code> <label label="required" /></td>
            <td><code>string | URL</code></td>
            <td>The endpoint URL to connect to (e.g., <code>"ws://localhost:8000"</code>, <code>"http://localhost:8000/rpc"</code>).</td>
        </tr>
        <tr>
            <td><code>opts</code> <label label="optional" /></td>
            <td><code><a href="/docs/reference/javascript/api/types/#connectoptions">ConnectOptions</a></code></td>
            <td>Connection-specific options such as namespace, database, and authentication.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Promise<void>` - Resolves when connection is successful

#### Examples

```ts title="WebSocket Connection"
await db.connect('ws://localhost:8000');
```

```ts title="HTTP Connection"
await db.connect('http://localhost:8000/rpc');
```

```ts title="With Namespace and Database"
await db.connect('ws://localhost:8000', {
    namespace: 'my_namespace',
    database: 'my_database'
});
```

```ts title="With Authentication"
await db.connect('ws://localhost:8000', {
    namespace: 'my_namespace',
    database: 'my_database',
    authentication: {
        username: 'root',
        password: 'secret'
    }
});
```

```ts title="With Custom Reconnect Options"
await db.connect('ws://localhost:8000', {
    reconnect: {
        enabled: true,
        attempts: 10,
        retryDelay: 1000,
        retryDelayMax: 10000,
        retryDelayMultiplier: 2
    }
});
```

### `.close()` {#close}

Disconnect from the active SurrealDB instance.

```ts title="Method Syntax"
db.close()
```

#### Returns
`Promise<void>` - Resolves when disconnection is successful

#### Example
```ts
await db.close();
console.log('Connection closed');
```

### `.health()` {#health}

Check the health status of the connected SurrealDB instance.

```ts title="Method Syntax"
db.health()
```

#### Returns
`Promise<void>` - Resolves if the instance is healthy, rejects otherwise

#### Example
```ts
try {
    await db.health();
    console.log('Database is healthy');
} catch (error) {
    console.error('Health check failed:', error);
}
```

### `.version()` {#version}

Retrieve version information from the connected SurrealDB instance.

```ts title="Method Syntax"
db.version()
```

#### Returns
[`Promise<VersionInfo>`](/docs/reference/javascript/api/types/#versioninfo) - An object containing version information

#### Example
```ts
const info = await db.version();
console.log(info.version); // "surrealdb-2.1.0"
```

### `.isFeatureSupported()` {#isfeatureSupported}

Check whether a specific feature is available in the current connection.

```ts title="Method Syntax"
db.isFeatureSupported(feature)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>feature</code> <label label="required" /></td>
            <td><code>Feature</code></td>
            <td>A feature from the <code>Features</code> object (e.g. <code>Features.LiveQueries</code>, <code>Features.Api</code>).</td>
        </tr>
    </tbody>
</table>

#### Returns
`boolean` - `true` if the feature is supported, `false` otherwise

#### Example
```ts
import { Surreal, Features } from 'surrealdb';

if (db.isFeatureSupported(Features.LiveQueries)) {
    console.log('Live queries are supported');
}
```

## Session management methods

### `.sessions()` {#sessions}

List all active sessions on the current connection.

```ts title="Method Syntax"
db.sessions()
```

#### Returns
`Promise<string[]>` - An array of session IDs

#### Example
```ts
const sessionIds = await db.sessions();
console.log('Active sessions:', sessionIds);
```

### `.newSession()` {#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.

```ts title="Method Syntax"
db.newSession()
```

#### Returns
`Promise<SurrealSession>` - A new [`SurrealSession`](/docs/reference/javascript/api/core/surreal-session.md) instance

#### Example
```ts
// 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()` {#closesession}

Close the primary session. This is equivalent to calling [`close()`](#close) on the connection.

```ts title="Method Syntax"
db.closeSession()
```

#### Returns
`Promise<void>` - Resolves when the session is closed

#### Example
```ts
await db.closeSession();
```

## Data management methods

### `.export()` {#export}

Export the database contents as a SQL string.

```ts title="Method Syntax"
db.export(options?)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>options</code> <label label="optional" /></td>
            <td><code>Partial&lt;<a href="/docs/reference/javascript/api/types/#sqlexportoptions">SqlExportOptions</a>&gt;</code></td>
            <td>Options to customise what gets exported.</td>
        </tr>
    </tbody>
</table>

#### 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

```ts title="Export Everything"
const sql = await db.export();
```

```ts title="Export Only Specific Tables"
const sql = await db.export({
    tables: ['users', 'posts'],
    records: true
});
```

```ts title="Export Schema Only (No Records)"
const sql = await db.export({
    records: false,
    tables: true,
    functions: true
});
```

```ts title="Export as Raw Response"
const response = await db.export().raw();
```

### `.import()` {#import}

Import database contents from a SQL string or a readable stream.

```ts title="Method Syntax"
db.import(input)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>input</code> <label label="required" /></td>
            <td><code>string | ReadableStream&lt;string&gt;</code></td>
            <td>The SQL string or readable stream to import into the database.</td>
        </tr>
    </tbody>
</table>

#### Returns
`Promise<void>` - Resolves when the import is complete

#### Example
```ts
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()` {#exportmodel}

Export a SurrealML model from the database.

```ts title="Method Syntax"
db.exportModel(name, version)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>name</code> <label label="required" /></td>
            <td><code>string</code></td>
            <td>The name of the SurrealML model to export.</td>
        </tr>
        <tr>
            <td><code>version</code> <label label="required" /></td>
            <td><code>string</code></td>
            <td>The version of the model to export.</td>
        </tr>
    </tbody>
</table>

#### Returns
`ExportModelPromise` - A promise that resolves to the exported model data. Has a `.raw()` method that returns the raw `Response` object.

#### Example
```ts
const modelData = await db.exportModel('my_model', '1.0.0');
```

```ts title="Export as Raw Response"
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()`](#subscribe) method.

### `connecting` {#event-connecting}

Emitted when the connection attempt starts.

**Payload:** None

**Example:**
```ts
const unsubscribe = db.subscribe('connecting', () => {
    console.log('Connecting to database...');
});
```

### `connected` {#event-connected}

Emitted when the connection is successfully established.

**Payload:** `[version: string]` - The SurrealDB version string

**Example:**
```ts
db.subscribe('connected', (version) => {
    console.log('Connected to SurrealDB version:', version);
});
```

### `reconnecting` {#event-reconnecting}

Emitted when the connection is attempting to reconnect after being disconnected.

**Payload:** None

**Example:**
```ts
db.subscribe('reconnecting', () => {
    console.log('Attempting to reconnect...');
});
```

### `disconnected` {#event-disconnected}

Emitted when the connection is closed.

**Payload:** None

**Example:**
```ts
db.subscribe('disconnected', () => {
    console.log('Disconnected from database');
});
```

### `error` {#event-error}

Emitted when a connection error occurs.

**Payload:** `[error: Error]` - The error object

**Example:**
```ts
db.subscribe('error', (error) => {
    console.error('Connection error:', error.message);
});
```

### Inherited events

The `Surreal` class also inherits and re-emits events from [`SurrealSession`](/docs/reference/javascript/api/core/surreal-session.md):

- `auth` - Emitted when authentication state changes
- `using` - Emitted when namespace/database changes

### `.subscribe()` {#subscribe}

Subscribe to connection and session events.

```ts title="Method Syntax"
db.subscribe(event, listener)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>event</code> <label label="required" /></td>
            <td><code>keyof <a href="/docs/reference/javascript/api/types/#surrealevents">SurrealEvents</a></code></td>
            <td>The event name to subscribe to.</td>
        </tr>
        <tr>
            <td><code>listener</code> <label label="required" /></td>
            <td><code>Function</code></td>
            <td>Callback function invoked when the event is emitted.</td>
        </tr>
    </tbody>
</table>

#### Returns
`() => void` - An unsubscribe function to remove the event listener

#### Example
```ts
const unsubscribe = db.subscribe('connected', (version) => {
    console.log('Connected:', version);
});

// Later, unsubscribe from the event
unsubscribe();
```

## Inherited methods

As `Surreal` extends [`SurrealSession`](/docs/reference/javascript/api/core/surreal-session.md), it inherits all authentication and query methods:

### Authentication methods
- [`signup()`](/docs/reference/javascript/api/core/surreal-session.md#signup) - Sign up a new user
- [`signin()`](/docs/reference/javascript/api/core/surreal-session.md#signin) - Sign in with credentials
- [`authenticate()`](/docs/reference/javascript/api/core/surreal-session.md#authenticate) - Authenticate with a token
- [`invalidate()`](/docs/reference/javascript/api/core/surreal-session.md#invalidate) - Invalidate the session

### Session configuration methods
- [`use()`](/docs/reference/javascript/api/core/surreal-session.md#use) - Set namespace and database
- [`set()`](/docs/reference/javascript/api/core/surreal-session.md#set) - Set a session parameter
- [`unset()`](/docs/reference/javascript/api/core/surreal-session.md#unset) - Remove a session parameter
- [`reset()`](/docs/reference/javascript/api/core/surreal-session.md#reset) - Reset the session

### Query methods

As `Surreal` extends [`SurrealQueryable`](/docs/reference/javascript/api/core/surreal-queryable.md) (via `SurrealSession`), it also inherits all query execution methods:

- [`query()`](/docs/reference/javascript/api/core/surreal-queryable.md#query) - Execute raw SurrealQL
- [`select()`](/docs/reference/javascript/api/core/surreal-queryable.md#select) - Select records
- [`create()`](/docs/reference/javascript/api/core/surreal-queryable.md#create) - Create records
- [`insert()`](/docs/reference/javascript/api/core/surreal-queryable.md#insert) - Insert records
- [`update()`](/docs/reference/javascript/api/core/surreal-queryable.md#update) - Update records
- [`upsert()`](/docs/reference/javascript/api/core/surreal-queryable.md#upsert) - Upsert records
- [`delete()`](/docs/reference/javascript/api/core/surreal-queryable.md#delete) - Delete records
- [`relate()`](/docs/reference/javascript/api/core/surreal-queryable.md#relate) - Create graph relationships
- [`live()`](/docs/reference/javascript/api/core/surreal-queryable.md#live) - Subscribe to live queries
- [`run()`](/docs/reference/javascript/api/core/surreal-queryable.md#run) - Execute functions

### Transaction method
- [`beginTransaction()`](/docs/reference/javascript/api/core/surreal-transaction.md) - Start a transaction

## Type parameters

This class does not use generic type parameters.

## Complete example

```ts
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: 'secret'
    }
});

// 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](/docs/reference/javascript/api/core/surreal-session.md) - Session management and authentication
- [SurrealQueryable](/docs/reference/javascript/api/core/surreal-queryable.md) - Query execution methods
- [SurrealTransaction](/docs/reference/javascript/api/core/surreal-transaction.md) - Transaction support
- [Node engine](/docs/reference/javascript/engines/node.md) and [WASM engine](/docs/reference/javascript/engines/wasm.md) - Engine-specific documentation
- [Data types](/docs/reference/javascript/api/values.md) - Working with data types
