Connecting to SurrealDB
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.
API References
| 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 |
Opening a connection
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.
Connection string
The connection string represents a URI pointing to a SurrealDB instance. Supported connection protocols include:
WebSocket (
ws://) for long lived connections (e.g. backend or frontend applications)HTTP (
http://) for short lived stateless connections (e.g. server-side rendering applications)Embedded protocols using the WebAssembly engine or Node.js engine
Connection options
The optional connection options allow you to further configure the connection to the database, including namespace and database, reconnect logic, and authentication details.
Namespace and database
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.
Authentication details
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.
Reconnection behavior
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 |
Waiting for a connection
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.
Effect of connection protocol on token & session duration
The connection protocol you choose affects how authentication tokens and sessions work
Websocket connections open a single long-lived stateful connection where after the initial authentication, the session duration applies and if not specified, defaults to
NONEmeaning that the session never expires unless otherwise specified.HTTP connections are short-lived and stateless, requiring you to authenticate every request individually for which the token is used, creating a short lived session. Hence, the token duration which defaults to 1 hour applies.
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.
Selecting a namespace and database
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.
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.
Connection status
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:
disconnected when the SDK is waiting for a connection to be opened
connecting when a connection is currently being opened
connected when the SDK is ready to communicate with the database and execute queries
reconnecting when the connection dropped and the SDK is attempting to reconnect
Additionally the SDK exposes events for each of these states, allowing you to subscribe to connection state changes.
Closing a connection
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.
Testing for features
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.
A complete list of supported features can be found in the source code.
Learn more
Surreal API reference for the complete connection interface
ConnectOptions type reference for all connection options
Authentication for signing in and managing credentials
WebAssembly engine for embedded browser databases
Node.js engine for embedded server-side databases
Error handling for connection and reconnection errors
Security best practices for production deployments