Skip to content

Concepts

Connecting to SurrealDB

The Go SDK supports connecting to SurrealDB over WebSocket or HTTP. The FromEndpointURLString factory function inspects the URL scheme and creates the appropriate connection automatically.

This page covers how to create, configure, and manage connections to a SurrealDB instance.

Function

Description

surrealdb.FromEndpointURLString(ctx, url)

Creates a connection from a URL string

surrealdb.FromConnection(ctx, conn)

Creates a client from a custom connection implementation

db.Close(ctx)

Closes the connection and releases resources

db.Use(ctx, ns, db)

Selects a namespace and database

db.Version(ctx)

Returns the version of the connected SurrealDB instance

Use FromEndpointURLString to create a new client and connect to a SurrealDB instance. The function accepts a context.Context for cancellation and a URL string that determines the connection type.

ctx := context.Background()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}
defer db.Close(ctx)

The context controls how long the connection attempt blocks. You can use context.WithTimeout to limit the connection time on unreliable networks:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")

The URL scheme determines the connection type and its capabilities.

SchemeConnection typeDescription
ws://WebSocketUnencrypted stateful connection
wss://WebSocketTLS-encrypted stateful connection
http://HTTPUnencrypted stateless connection
https://HTTPTLS-encrypted stateless connection
mem://MemoryIn-memory embedded instance

WebSocket connections are long-lived and stateful. They support all SDK features including live queries, sessions, and transactions.

HTTP connections are stateless. Each request is independent and requires its own authentication token. Live queries, sessions, and transactions are not available over HTTP.

If you need to configure the underlying connection (for example, custom TLS settings or a specific WebSocket implementation), you can create a connection manually and pass it to FromConnection:

import (
	"net/url"

	"github.com/surrealdb/surrealdb.go/pkg/connection"
	"github.com/surrealdb/surrealdb.go/pkg/connection/gorillaws"
)

endpoint, _ := url.Parse("ws://localhost:8000/rpc")
conf := connection.NewConfig(endpoint)
conn := gorillaws.New(conf)

db, err := surrealdb.FromConnection(ctx, conn)

FromConnection calls .Connect(ctx) on the connection for you, so you do not need to call it separately. For auto-reconnecting connections, see Reliable connections.

After connecting, use .Use() to select the namespace and database you want to work with. Most operations require a namespace and database to be selected first.

if err := db.Use(ctx, "my_namespace", "my_database"); err != nil {
	log.Fatal(err)
}

You can call .Use() multiple times to switch between namespaces and databases on the same connection.

WebSocket connections (ws://, wss://) are long-lived and stateful. After authentication, the session persists for the lifetime of the connection. The session duration defaults to NONE, meaning it never expires unless configured otherwise.

HTTP connections (http://, https://) are stateless. Each request requires its own authentication token. 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 in DEFINE ACCESS METHOD or DEFINE USER statements.

Note

Learn more about token and session duration in the security best practices documentation.

Call .Close() to release the underlying connection resources when you are done.

db.Close(ctx)

Use defer db.Close(ctx) immediately after creating the connection to ensure cleanup happens even when errors occur.

Was this page helpful?