Back to top
Documentation Integrations SDKs Node.js

Node.js SDK for SurrealDB

The SurrealDB SDK for Node.js enables simple and advanced querying of a remote database from server-side code. All connections to SurrealDB are made over WebSockets, and automatically reconnect when the connection is terminated.

To contribute to this documentation, edit this file on GitHub.

To contribute to the SDK code, submit an Issue or Pull Request here.

Install the SDK

First, install the SurrealDB SDK using npm:

npm install --save surrealdb.js

Alternatively, you can use install the SurrealDB SDK using yarn, pnpm or similar:

yarn add surrealdb.js
pnpm install surrealdb.js

Connect to SurrealDB

Create a new app.js file and add the following code to try out some basic operations using the SurrealDB SDK.

const { default: Surreal } = require('surrealdb.js');

const db = new Surreal();

async function main() {

	try {
		// Connect to the database
		await db.connect('http://127.0.0.1:8000/rpc');

		// Signin as a namespace, database, or root user
		await db.signin({
			user: 'root',
			pass: 'root',
		});

		// Select a specific namespace / database
		await db.use({ns: 'test', db: 'test'});

		// Create a new person with a random id
		let created = await db.create("person", {
			title: 'Founder & CEO',
			name: {
				first: 'Tobie',
				last: 'Morgan Hitchcock',
			},
			marketing: true,
			identifier: Math.random().toString(36).slice(2, 12),
		});

		// Update a person record with a specific id
		let updated = await db.merge("person:jaime", {
			marketing: true,
		});

		// Select all people records
		let people = await db.select("person");

		// Perform a custom advanced query
		let groups = await db.query('SELECT marketing, count() FROM type::table($tb) GROUP BY marketing', {
			tb: 'person',
		});

	} catch (e) {

		console.error('ERROR', e);

	}

}

main();

Then run your app from the command line with:

node app.js

SDK methods

The JavaScript SDK comes with a number of built-in functions.

Function Description
async db.connect(url, options) Connects to a local or remote database endpoint
async db.wait() Waits for the connection to the database to succeed
async db.close() Closes the persistent connection to the database
async db.use({ ns, db }) Switch to a specific namespace and database
async db.info<T>() Returns the record of an authenticated scope user
async db.signup(vars) Signs this connection up to a specific authentication scope
async db.signin(vars) Signs this connection in to a specific authentication scope
async db.invalidate() Invalidates the authentication for the current connection
async db.authenticate(token) Authenticates the current connection with a JWT token
async db.let(key, val) Assigns a value as a parameter for this connection
async db.unset(key) Removes a parameter for this connection
async db.live<T>(table, callback, diff) Initiate a live query
async db.listenLive<T>(queryUuid, callback) Register a callback for a running live query
async db.kill(queryUuid) Kill a running live query
async db.query<T>(sql, vars) Runs a set of SurrealQL statements against the database
async db.select<T>(thing) Selects all records in a table, or a specific record
async db.create<T, U>(thing, data) Creates a record in the database
async db.insert<T, U>(thing, data) Inserts one or multiple records in the database
async db.update<T, U>(thing, data) Updates all records in a table, or a specific record
async db.merge<T, U>(thing, data) Modifies all records in a table, or a specific record
async db.patch(thing, data) Applies JSON Patch changes to all records in a table, or a specific record
async db.delete<T>(thing) Deletes all records, or a specific record

async db.connect(url, options)

Connects to a local or remote database endpoint.

Arguments Description
url The url of the database endpoint to connect to.
options An object with options to initiate the connection to SurrealDB.
// Connect to a local endpoint
await db.connect('http://127.0.0.1:8000/rpc');

// Connect to a remote endpoint
await db.connect('https://cloud.surrealdb.com/rpc');

// Specify a namespace and database pair to use
await db.connect('https://cloud.surrealdb.com/rpc', {
	ns: 'surrealdb',
	db: 'docs',
});

// Authenticate with an existing token
// The .authenticate() function is used under the hood.
await db.connect('https://cloud.surrealdb.com/rpc', {
	auth: '.....',
});

// Authenticate using a pair of credentials
await db.connect('https://cloud.surrealdb.com/rpc', {
	auth: {
		user: 'root',
		pass: 'surrealdb',
	},
});

// Use advanced custom logic to prepare the connection to the database
await db.connect('https://cloud.surrealdb.com/rpc', {
	prepare: async (db) => {
		await db.use({ ns: 'surrealdb', db: 'docs' });

		const token = await retrieveToken();
		if (token) await db.authenticate(token);

		// Any queries executed before the .prepare() function finishes will be forced to wait
		// Please note that this is also the case for queries executed within the prepare function
		// Doing so can cause the connection to stay in a initializing state
	},
});

async db.wait()

Waits for the connection to the database to succeed.

await db.wait();

async db.close()

Closes the persistent connection to the database.

await db.close();

db.use({ ns, db })

Switch to a specific namespace and database. If only the ns or db property is specified, the current connection details will be used to fill the other property.

Properties Description
ns Initially required Switches to a specific namespace.
db Initially required Switches to a specific database.
await db.use({ ns: 'surrealdb', db: 'docs' });

async db.info<T>()

This method returns the record of an authenticated scope user.

const user = await db.info();

async db.signup({ NS, DB, SC, [...] })

Signs up to a specific authentication scope.

Properties Description
NS Required The namespace to sign up to
DB Required The database to sign up to
SC Required The scope to sign up to. Also pass any variables used in the scope
const token = await db.signup({
	NS: 'surrealdb',
	DB: 'docs',
	SC: 'user',

	// Also pass any properties required by the scope definition
	email: 'info@surrealdb.com',
	pass: '123456',
});

async db.signin({ ... })

Signs in to a root, namespace, database or scope user.

Properties Description
user Required for root, NS & DB The username of the database user
pass Required for root, NS & DB The password of the database user
NS Required for DB & SC The namespace to sign in to
DB Required for SC The database to sign in to
SC The scope to sign in to. Also pass any variables used in the scope
// Authenticate with a root user
const token = await db.signin({
	user: 'root',
	pass: 'surrealdb',
});

// Authenticate with a Namespace user
const token = await db.signin({
	NS: 'surrealdb',
	user: 'tobie',
	pass: 'surrealdb',
});

// Authenticate with a Database user
const token = await db.signin({
	NS: 'surrealdb',
	DB: 'docs',
	user: 'tobie',
	pass: 'surrealdb',
});

// Authenticate with a Scope user
const token = await db.signin({
	NS: 'surrealdb',
	DB: 'docs',
	SC: 'user',

	// Also pass any properties required by the scope definition
	email: 'info@surrealdb.com',
	pass: '123456',
});

async db.invalidate()

Invalidates the authentication for the current connection.

await db.invalidate();

async db.authenticate(token)

Authenticates the current connection with a JWT token.

Arguments Description
token Required The JWT authentication token.
await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA');

async db.let(key, val)

Assigns a value as a parameter for this connection.

Arguments Description
key Required Specifies the name of the variable.
val Required Assigns the value to the variable name.
// Assign the variable on the connection
await db.let('name', {
	first: 'Tobie',
	last: 'Morgan Hitchcock',
});

// Use the variable in a subsequent query
await db.query('CREATE person SET name = $name');

// Use the variable in a subsequent query
await db.query('SELECT * FROM person WHERE name.first = $name.first');

async db.unset(key)

Removes a parameter for this connection.

Arguments Description
key Required Specifies the name of the variable.
// Remove the variable from the connection
await db.unset('name');

async db.live<T>(table, callback, diff)

Initiates a live query.

Arguments Description
table Required The table name to listen for changes for
callback Optional A callback function that processes live notifications
diff Optional If set to true, live notifications will include an array of JSON Patch objects, rather than the entire record for each notification.
await db.kill(queryUuid)

async db.listenLive<T>(queryUuid, callback)

Registers a callback function for a running live query.

Arguments Description
queryUuid Required The UUID of a running live query
callback Required A callback function that processes live notifications
await db.kill(queryUuid)

async db.kill(queryUuid)

Kills a running live query by it's UUID

Arguments Description
queryUuid Required The UUID of the live query you wish to kill
await db.kill(queryUuid)

async db.query<T>(query, vars)

Runs a set of SurrealQL statements against the database.

Arguments Description
query Required Specifies the SurrealQL statements.
vars Optional Assigns variables which can be used in the query.
type Person = {
	id: string;
	name: string;
};

// Assign the variable on the connection
const result = await db.query<[Person[], Person[]]>(
	'CREATE person SET name = "John"; SELECT * FROM type::table($tb);',
	{ tb: 'person' }
);

// Get the first result from the first query
const created = result[0].result[0];

// Get all of the results from the second query
const people = result[1].result;

async db.select<T>(thing)

Selects all records in a table, or a specific record, from the database.

Arguments Description
thing Required The table name or a record ID to select.
type Person = {
	id: string;
	name: string;
};

// Select all records from a table
const people = await db.select<Person>('person');

// Select a specific record from a table
const [person] = await db.select<Person>('person:h5wxrf2ewk8xjxosxtyc');

This function will run the following query in the database:

SELECT * FROM $thing;

async db.create<T, U>(thing, data)

Creates a record in the database.

Arguments Description
thing Required The table name or the specific record ID to create.
data Optional The document / record data to insert.
type Person = {
	id: string;
	name: string;
	settings: {
		active: boolean;
		marketing: boolean;
	};
};

// Create a record with a random ID
const [person] = await db.create<Person>('person');

// Create a record with a specific ID
const [record] = await db.create<Person>('person:tobie', {
	name: 'Tobie',
	settings: {
		active: true,
		marketing: true,
	},
});

// The content you are creating the record with might differ from the return type
const [record] = await db.create<
	Person,
	Pick<Person, 'name'>
>('person:tobie', {
	name: 'Tobie',
});

This function will run the following query in the database:

CREATE $thing CONTENT $data;

async db.insert<T, U>(thing, data)

Insers one or multiple records in the database.

Arguments Description
thing Required The table name to insert to.
data Optional Either a single document/record or an array of documents/records to insert
type Person = {
	id: string;
	name: string;
	settings: {
		active: boolean;
		marketing: boolean;
	};
};

// Insert a single record
const [person] = await db.insert<Person>('person', {
	name: 'Tobie',
	settings: {
		active: true,
		marketing: true,
	},
});

// Insert multiple records
const people = await db.insert<Person>('person', [
	{
		name: 'Tobie',
		settings: {
			active: true,
			marketing: true,
		},
	},
	{
		name: 'Jaime',
		settings: {
			active: true,
			marketing: true,
		},
	},
]);

// The content you are creating the record with might differ from the return type
const people = await db.insert<
	Person,
	Pick<Person, 'name'>
>('person', [
	{ name: 'Tobie' },
	{ name: 'Jaime' },
]);

This function will run the following query in the database:

INSERT INTO $thing $data;

async db.update<T, U>(thing, data)

Updates all records in a table, or a specific record, in the database.

This function replaces the current document / record data with the specified data.
Arguments Description
thing Required The table name or the specific record ID to update.
data Optional The document / record data to insert.
type Person = {
	id: string;
	name: string;
	settings: {
		active: boolean;
		marketing: boolean;
	};
};

// Update all records in a table
const people = await db.update<Person>('person');

// Update a record with a specific ID
const [person] = await db.update<Person>('person:tobie', {
	name: 'Tobie',
	settings: {
		active: true,
		marketing: true,
	},
});

// The content you are updating the record with might differ from the return type
const [record] = await db.update<
	Person,
	Pick<Person, 'name'>
>('person:tobie', {
	name: 'Tobie',
});

This function will run the following query in the database:

UPDATE $thing CONTENT $data;

async db.merge<T, U>(thing, data)

Modifies all records in a table, or a specific record, in the database.

This function merges the current document / record data with the specified data.
Arguments Description
thing Required The table name or the specific record ID to merge
data Optional The document / record data to insert.
type Person = {
	id: string;
	name: string;
	updated_at: Date;
	settings: {
		active: boolean;
		marketing: boolean;
	};
};

// Update all records in a table
const people = await db.merge<Person>('person', {
	updated_at: new Date(),
});

// Update a record with a specific ID
const [person] = await db.merge<Person>('person:tobie', {
	updated_at: new Date(),
	settings: {
		active: true,
	},
});

// The content you are merging the record with might differ from the return type
const [record] = await db.merge<
	Person,
	Pick<Person, 'name'>
>('person:tobie', {
	name: 'Tobie',
});

This function will run the following query in the database:

UPDATE $thing MERGE $data;

async db.patch(thing, data)

Applies JSON Patch changes to all records, or a specific record, in the database.

This function patches the current document / record data with the specified JSON Patch data.
Arguments Description
thing Required The table name or the specific record ID to patch.
data Optional The JSON Patch data with which to patch the records.
// Update all records in a table
const people = await db.patch('person', [
	{ op: 'replace', path: '/created_at', value: new Date() },
]);

// Update a record with a specific ID
const [person] = await db.patch('person:tobie', [
	{ op: 'replace', path: '/settings/active', value: false },
	{ op: 'add', path: '/tags', value: ['developer', 'engineer'] },
	{ op: 'remove', path: '/temp' },
]);

This function will run the following query in the database:

UPDATE $thing PATCH $data;

async db.delete<T>(thing)

Deletes all records in a table, or a specific record, from the database.

Arguments Description
thing Required The table name or a record ID to delete.
// Delete all records from a table
await db.delete('person');

// Delete a specific record from a table
await db.delete('person:h5wxrf2ewk8xjxosxtyc');

This function will run the following query in the database:

DELETE * FROM $thing;