When creating a new connection to a SurrealDB instance, you can choose to connect to a local or remote endpoint, specify a namespace and database pair to use, authenticate with an existing token, authenticate using a pair of credentials, or use advanced custom logic to prepare the connection to the database.
First, you need to initialize a new instance of the Surreal class and connect it to a database endpoint using the .connect() method. Then you can specify the connection details such as the URL, namespace, and database.
| Method | Description |
|---|---|
db.connect(url, options) | Connects to a local or remote database endpoint |
db.close() | Closes the persistent connection to the database |
db.ready | Waits for the connection to the database to succeed |
db.use(namespace, database) | Switch to a specific namespace and database |
Before you can execute any queries, you need to open a connection to a SurrealDB instance. This is done using the .connect() method. This method accepts a connection string and a set of options, including namespace, database, and authentication details.
The connection string represents a URI pointing to a SurrealDB instance. Supported connection protocols include:
ws://) for long lived connections (e.g. backend or frontend applications)http://) for short lived stateless connections (e.g. server-side rendering applications)// Over WebSocket await db.connect('ws://127.0.0.1:8000'); // Over HTTP await db.connect('http://127.0.0.1:8000');
// Over WebSocket await db.connect('wss://cloud.surrealdb.com'); // Over HTTP await db.connect('https://cloud.surrealdb.com');
// In-memory database await db.connect('mem://'); // IndexedDB database (browser) await db.connect('indxdb://localhost:8000'); // File-system database (backend) await db.connect('rocksdb://localhost:8000');
The optional connection options allow you to further configure the connection to the database, including namespace and database, reconnect logic, and authentication details.
You can directly specify the namespace and database to use using the namespace and database options. If you do not specify these options, the default namespace and database will be used. Once the connection is established, you can switch the active namespace and database with the .use() method.
When connecting as a system user or token, you can directly pass your credentials to the authentication option. While you can also use the dedicated .signin() method to authenticate, passing the authentication details to the .connect() method is the preferred way and allows for automatic reconnecting.
You can configure the reconnection behavior using the reconnect option. The SDK features a built-in reconnection mechanism for WebSocket connections that automatically reconnects to the database if the connection is lost. Additionally, you can configure the behavior with exponential backoff and jitter to prevent overwhelming the database with reconnection attempts.
| Option | Description |
|---|---|
enabled | Enable automatic reconnection |
attempts | Maximum reconnection attempts (-1 for unlimited) |
retryDelay | Initial delay before reconnecting (ms) |
retryDelayMax | Maximum delay between attempts (ms) |
retryDelayMultiplier | Multiply delay after each failed attempt |
retryDelayJitter | Random offset percentage for delays |
You can wait for the connection to the database to succeed by awaiting the .connect() method. If the connection fails for any reason, the promise will reject. If you want to await without opening a connection, you can make use of the .ready() method instead.
// Open a new connection and wait for it to succeed await db.connect('ws://127.0.0.1:8000'); // Wait for the connection to succeed without opening a new connection await db.ready();
The connection protocol you choose affects how authentication tokens and sessions work
NONE meaning that the session never expires unless otherwise specified.You can extend the session duration of a token or a session by setting the DURATION clause when creating a new access method with the DEFINE ACCESS METHOD statement, or when defining a new user with the DEFINE USER statement. Learn more about token and session duration in our security best practices documentation.
While an initial namespace and database can be specified directly in the .connect() method, you can also switch to a specific namespace and database using the .use() method. This is particularly useful if you want to switch to a different setup after connecting. You can also stay in the same namespace but switch to a different database.
await db.use({ namespace: 'surrealdb', database: 'docs' });
The SDK will emit a using event whenever the namespace or database is selected, including during the initial connection. This allows you to subscribe to namespace and database changes and react to them accordingly.
db.subscribe('using', ({ namespace, database }) => { console.log('Now using:', namespace, '/', database); });
The status of the connection is available through the .status property. This allows you to check the current connection state and react to changes in the connection status. The possible values are:
Additionally the SDK exposes events for each of these states, allowing you to subscribe to connection state changes.
db.subscribe('connected', () => { console.log('Connected to the database'); });
The .close() method closes the persistent connection to the database. You should always call this method when you are done with the connection to free up resources. Since this method is asynchronous, we highly recommend awaiting it to ensure that the connection is closed properly before proceeding.
await db.close();
The SDK provides a built in feature testing mechanism to check if a specific feature is supported by the current connection. This is particularly useful to check if a feature is supported before using it, and to avoid errors or unexpected behavior.
import { Features } from "surrealdb"; if (db.isFeatureSupported(Features.LiveQueries)) { // Execute a live query... }
A complete list of supported features can be found in the source code.