Skip to content

Concepts

Connecting to SurrealDB

The first step towards interacting with SurrealDB is to create a new connection to a database instance. This involves initialising a new Surreal instance, connecting it to an endpoint, and selecting a namespace and database. The SDK supports remote connections over WebSocket and HTTP, as well as embedded in-process databases.

Method

Description

new Surreal()

Creates a new Surreal instance

db.connect(url)

Connects to a SurrealDB instance

db.close()

Closes the active connection

db.useNs(namespace)

Switches to a specific namespace

db.useDb(database)

Switches to a specific database

db.useDefaults()

Uses the default namespace and database

db.version()

Returns the server version

db.health()

Checks the server health

Create a new Surreal instance and call .connect() with a connection string pointing to your SurrealDB instance. The Surreal class implements AutoCloseable, so you can use it in a try-with-resources block to ensure the connection is closed automatically.

Surreal db = new Surreal();
db.connect("ws://localhost:8000");

The connection string determines the protocol and transport used to communicate with SurrealDB. For more on server configuration, see the start command documentation.

ProtocolDescription
ws://Plain WebSocket connection
wss://Secure WebSocket connection (TLS)
http://Plain HTTP connection
https://Secure HTTP connection (TLS)
memory://In-memory embedded database
surrealkv://Disk-based embedded database

The memory:// and surrealkv:// protocols run SurrealDB in-process using JNI, which eliminates network overhead. See Embedded databases for details on configuring embedded connections.

Not all features are available on every protocol. The table below summarizes what is supported for each connection type.

FeatureWebSocketHTTPEmbedded
AuthenticationYesYesYes
QueriesYesYesYes
CRUD operationsYesYesYes
Live queriesYesNoNo
TransactionsYesNoYes
Multiple sessionsYesNoYes
Export / ImportYesYesYes

After connecting, select a namespace and database using .useNs() and .useDb(). These methods return the Surreal instance, so they can be chained.

db.useNs("surrealdb").useDb("docs");

To reset the namespace and database to the server defaults, call .useDefaults().

db.useDefaults();

Since Surreal implements AutoCloseable, Java's try-with-resources statement ensures that .close() is called when the block exits, even if an exception is thrown. This is the recommended pattern for managing connections.

import com.surrealdb.Surreal;
import com.surrealdb.signin.RootCredential;

public class Example {

    public static void main(String[] args) {
        try (Surreal db = new Surreal()) {
            db.connect("ws://localhost:8000");
            db.useNs("surrealdb").useDb("docs");
            db.signin(new RootCredential("root", "root"));

            String version = db.version();
            System.out.println("Connected to SurrealDB " + version);
        }
    }

}

The connection protocol affects how authentication tokens and sessions behave.

  • WebSocket connections are stateful and long-lived. After the initial authentication, the session persists for the lifetime of the connection. The session duration defaults to NONE, meaning it never expires unless explicitly configured.

  • HTTP connections are stateless, so each request carries its own credentials and the server creates a short-lived session for that request. After a system user signs in, the SDK sends the username and password with every request, so the token duration does not apply. After a record user signs in, the SDK sends the token, so requests fail once the token expires. The token duration defaults to 1 hour.

The figure below shows which duration ends the session in each case, with the default durations.

A timeline over two hours shows which duration ends a session when the token duration is the default of one hour. A WebSocket connection that signed in with credentials keeps one session, and with the default session duration of NONE it keeps working after the token that signin returned has expired. A WebSocket connection that authenticated with a token has its session end when the token expires, and later queries fail with 'The session has expired'. Over HTTP, requests that send the token in an Authorization Bearer header succeed until the token expires and then fail with 401, while requests that send Basic credentials sign in again each time and keep succeeding. Over HTTP, the JavaScript, Python and Go SDKs send the token; the Rust, Java and .NET SDKs send a system user's username and password with every request, and a token for record users.A timeline over two hours shows which duration ends a session when the token duration is the default of one hour. A WebSocket connection that signed in with credentials keeps one session, and with the default session duration of NONE it keeps working after the token that signin returned has expired. A WebSocket connection that authenticated with a token has its session end when the token expires, and later queries fail with 'The session has expired'. Over HTTP, requests that send the token in an Authorization Bearer header succeed until the token expires and then fail with 401, while requests that send Basic credentials sign in again each time and keep succeeding. Over HTTP, the JavaScript, Python and Go SDKs send the token; the Rust, Java and .NET SDKs send a system user's username and password with every request, and a token for record users.

You can configure token and session durations using the DURATION clause on DEFINE ACCESS or DEFINE USER statements. See the security best practices documentation for guidance on choosing appropriate durations.

The .close() method releases all resources associated with the connection. If you are not using try-with-resources, call .close() explicitly when you are done with the connection.

db.close();

Was this page helpful?