SurrealDB Docs Logo

Enter a search query

Create a new connection

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 SurrealDB and connect it to a database endpoint. Using the .connect() method, you can specify the connection details such as the URL, namespace, and database.

While the .connect() method is the primary method to connect to a SurrealDB instance, there are other methods that you can use while managing your connection.

MethodDescription
db.connect(url, options)Connects to a local or remote database endpoint
db.close()Closes the persistent connection to the database
db.readyWaits for the connection to the database to succeed
db.use(namespace,database)Switch to a specific namespace and database

.connect()

The .connect() method accepts a url and an options object. In the options object, you can specify the namespace and database to use, as well as the auth details which can be a token or a pair of credentials.

This means that the .use() method is not required if you specify the namespace and database in the options object. However, if you want to switch to a different namespace or database, you should use the .use() method. Depending on the use case, you can also specify advanced custom logic for the connection.

Connection options

You can specify your connection protocol either as http, https, ws, or wss. Since SurrealDB also supports RPC over WebSocket, by default, it is specified with a /rpc suffix.

// Connect to a local endpoint with http protocol await db.connect('http://127.0.0.1:8000/rpc'); // Connect to a local endpoint with ws protocol await db.connect('ws://127.0.0.1:8000/rpc');

Effect of connection protocol on token & session duration

The connection protocol you choose affects how authentication tokens and sessions work:

With websockets connections (ws://, wss://) you open a single long-lived stateful connection where after the initial authentication, the session duration applies and if not specified, defaults to NONE meaning that the session never expires unless otherwise specified.

When you connect with a HTTP connection (http://, https://), every request you make is 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.


.use()

Depending on the complexity of your use case, you can 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.

Learn more about the .use() method in the methods section.

Example usage

await db.use({ namespace: 'surrealdb', database: 'docs' });

.ready property

The .ready propery is used to wait for the connection to the database to succeed. This is particularly useful if you want to ensure that the connection is established before executing any queries.

Important

Use this property after .connect() to ensure that the connection is established before executing any queries.

await db.ready;

.close()

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.

await db.close();

Example

Here is an example of the .connect(), .use(), .ready, and .close() methods in action.

Example
import Surreal from "surrealdb"; // Define the database configuration interface interface DbConfig { url: string; namespace: string; database: string; } // Define the default database configuration const DEFAULT_CONFIG: DbConfig = { url: "http://127.0.0.1:8000/rpc", namespace: "test", database: "test", }; // Define the function to get the database instance export async function getDb(config: DbConfig = DEFAULT_CONFIG): Promise<Surreal> { const db = new Surreal(); try { await db.connect(config.url); await db.use({ namespace: config.namespace, database: config.database }); return db; } catch (err) { console.error("Failed to connect to SurrealDB:", err instanceof Error ? err.message : String(err)); await db.close(); throw err; } }
© SurrealDB GitHub Discord Community Cloud Features Releases Install