Skip to main content
Version: 1.1.0

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.

NOTE: This SDK is compatible with V1.0.0

Install the SDK

First, install the SurrealDB SDK using npm:

npm install --save surrealdb.node

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

yarn add surrealdb.node
pnpm install surrealdb.node

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.node');

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.

FunctionDescription
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()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)Assigns a value as a parameter for this connection
async db.let(key,val)Runs a set of SurrealQL statements against the database
async db.unset(key)Removes a parameter for this connection
async db.query(sql,vars)Runs a set of SurrealQL statements against the database
async db.select(thing)Selects all records in a table, or a specific record
async db.create(thing,data)Creates a record in the database
async db.insert(thing,data)Inserts one or multiple records in the database
async db.update(thing,data)Updates all records in a table, or a specific record
async db.merge(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(thing,data)Deletes all records, or a specific record

.connect()

Connects to a local or remote database endpoint.

Method Syntax
async db.connect(url, options)

Arguments

ArgumentsDescription
urlThe url of the database endpoint to connect to.
optionsAn object with options to initiate the connection to SurrealDB.

Example usage

// 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');

.close()

Closes the persistent connection to the database.

Method Syntax
async db.close()

Example usage

await db.close();

.use()

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

Method Syntax
db.use({ ns, db })

Arguments

ArgumentsDescription
nsINITIALLY REQUIREDSwitches to a specific namespace.
dbINITIALLY REQUIREDSwitches to a specific database.

Example usage

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

.info()

This method returns the record of an authenticated scope user.

Method Syntax
async db.info()

Example usage

const user = await db.info();

.signup()

Signs up to a specific authentication scope.

Method Syntax
async db.signup({ ns, db, sc, ... })

Arguments

PropertiesDescription
nsREQUIREDThe namespace to sign up to
dbREQUIREDThe database to sign up to
scREQUIREDThe scope to sign up to. Also pass any variables used in the scope

Example usage

const token = await db.signup({
ns: 'surrealdb',
db: 'docs',
sc: 'user',

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

.signin()

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

Method Syntax
async db.signin({ ... })

Arguments

PropertiesDescription
userREQUIREDThe username of the database user
passREQUIREDThe password of the database user
nsREQUIREDThe namespace to sign in to
dbREQUIREDThe database to sign in to
scREQUIREDThe scope to sign in to. Also pass any variables used in the scope

Example usage

// 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',
password: '123456',
});

.invalidate()

Authenticates the current connection with a JWT token.

Method Syntax
async db.invalidate()

Example usage

await db.invalidate();

.authenticate()

Authenticates the current connection with a JWT token.

Method Syntax
async db.authenticate()

Example usage

await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA');

.let()

Assigns a value as a parameter for this connection.

Method Syntax
async db.let(key, val)

Arguments

ArgumentsDescription
keyREQUIREDSpecifies the name of the variable.
valREQUIREDAssigns the value to the variable name.

Example usage

// 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');

.unset()

Removes a parameter for this connection.

Method Syntax
async db.unset(key)

Arguments

ArgumentsDescription
keyREQUIREDSpecifies the name of the variable.

Example usage

// Remove the variable from the connection
await db.unset('name');

.query()

Runs a set of SurrealQL statements against the database.

Method Syntax
async db.query(query, vars)

Arguments

ArgumentsDescription
queryREQUIREDSpecifies the name of the variable.
varsOPTIONALSpecifies the name of the variable.

Example usage

// Assign the variable on the connection
const result = await db.query(
'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;

.select()

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

Method Syntax
async db.select(thing)

Arguments

ArgumentsDescription
thingREQUIREDThe table name or a record ID to select.

Example usage

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

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

Translated query

This function will run the following query in the database:

SELECT * FROM $thing;

.create()

Creates a record in the database.

Method Syntax
async db.create(thing, data)

Arguments

ArgumentsDescription
thingREQUIREDThe table name or the specific record ID to create.
dataOPTIONALThe document / record data to insert.

Example usage

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

// Create a record with a specific ID
const [record] = await db.create('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:tobie', {
name: 'Tobie',
});

Translated query

This function will run the following query in the database:

CREATE $thing CONTENT $data;

.insert()

Inserts one or multiple records in the database.

Method Syntax
async db.insert(thing, data)

Arguments

ArgumentsDescription
thingREQUIREDThe table name to insert to.
dataOPTIONALEither a single document/record or an array of documents/records to insert

Example usage

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

// Insert multiple records
const people = await db.insert('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', [
{ name: 'Tobie' },
{ name: 'Jaime' },
]);

Translated query

This function will run the following query in the database:

INSERT INTO $thing $data;

.update()

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

Method Syntax
async db.update(thing, data)
NOTE: This function replaces the current document / record data with the specified data.

Arguments

ArgumentsDescription
thingREQUIREDThe table name or the specific record ID to update.
dataOPTIONALThe document / record data to insert.

Example usage

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

// Update a record with a specific ID
const [person] = await db.update('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:tobie', {
name: 'Tobie',
});

Translated query

This function will run the following query in the database:

UPDATE $thing CONTENT $data;

.merge()

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

Method Syntax
async db.merge(thing, data)
NOTE: This function merges the current document / record data with the specified data.

Arguments

ArgumentsDescription
thingREQUIREDThe table name or the specific record ID to merge.
dataOPTIONALThe document / record data to insert.

Example usage

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

// Update a record with a specific ID
const [person] = await db.merge('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:tobie', {
name: 'Tobie',
});

Translated query

This function will run the following query in the database:

UPDATE $thing MERGE $data;

.patch()

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

Method Syntax
async db.patch(thing, data)
NOTE: This function patches the current document / record data with the specified JSON Patch data.

Arguments

ArgumentsDescription
thingREQUIREDThe table name or the specific record ID to patch.
dataOPTIONALThe JSON Patch data with which to patch the records.

Example usage

// 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' },
]);

Translated query

This function will run the following query in the database:

UPDATE $thing PATCH $data;

.delete()

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

Method Syntax
async db.delete(thing)

Arguments

ArgumentsDescription
thingREQUIREDThe table name or a record ID to delete.

Example usage

// Delete all records from a table
await db.delete('person');

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

Translated query

This function will run the following query in the database:

DELETE * FROM $thing;