Javascript


Javascript SDK for SurrealDB
The SurrealDB SDK for JavaScript enables simple and advanced querying of a remote database from a browser or 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.
import { Surreal } from 'surrealdb.js';
const db = new Surreal();
async function main() {
try {
// Connect to the database
await db.connect('http://127.0.0.1:8000/rpc', {
// Set the namespace and database for the connection
namespace: 'test',
database: 'test',
// Set the authentication details for the connection
auth: {
namespace: 'test',
database: 'test',
scope: 'user',
username: 'info@surrealdb.com',
password: 'my-secret-password',
},
});
// Create a new person with a random id
const created = await db.create('person', {
title: 'Founder & CEO',
name: {
first: 'Tobie',
last: 'Morgan Hitchcock',
},
marketing: true,
identifier: Math.random().toString(36).substr(2, 10),
});
// Update a person record with a specific id
const updated = await db.merge('person:jaime', {
marketing: true,
});
// Select all people records
const people = await db.select('person');
// Perform a custom advanced query
const 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(namespace,database) | 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) | 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.live<T>(tabel, 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<T,U>(thing,data) | Applies JSON Patch changes to all records in a table, or a specific record |
async db.delete<T,U>(thing,data) | Deletes all records, or a specific record |
.connect()
Connects to a local or remote database endpoint.
async db.connect(url, options)
Arguments
Arguments | Description | |
---|---|---|
url | The url of the database endpoint to connect to. | |
options | An 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');
// Specify a namespace and database pair to use
await db.connect('https://cloud.surrealdb.com/rpc', {
namespace: 'surrealdb',
database: '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: {
username: 'root',
password: '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({ namespace: 'surrealdb', database: '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
},
});
.wait()
Waits for the connection to the database to succeed.
async db.wait()
Example usage
await db.wait();
.close()
Closes the persistent connection to the database.
async db.close()
Example usage
await db.close();
.use()
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.
db.use({` { namespace, database } `})
Arguments
Arguments | Description | |
---|---|---|
namespace | Switches to a specific namespace. | |
database | Switches to a specific database. |
Example usage
await db.use({ namespace: 'surrealdb', database: 'docs' });
.info()
This method returns the record of an authenticated scope user.
async db.info<T>()
Example usage
const user = await db.info();
.signup()
Signs up to a specific authentication scope.
async db.signup({`{ namespace, database, scope, [...] }`})
Arguments
Arguments | Description | |
---|---|---|
namespace | The namespace to sign up to | |
database | The database to sign up to | |
scope | The scope to sign up to. Also pass any variables used in the scope |
Example usage
const token = await db.signup({
namespace: 'surrealdb',
database: 'docs',
scope: 'user',
// Also pass any properties required by the scope definition
email: 'info@surrealdb.com',
pass: '123456',
});
.signin()
Signs in to a root, namespace, database or scope user.
async db.signin({`{ ... }`})
Arguments
Properties | Description | |
---|---|---|
username | The username of the database user | |
password | The password of the database user | |
namespace | The namespace to sign in to | |
database | The database to sign in to | |
scope | The 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({
username: 'root',
password: 'surrealdb',
});
// Authenticate with a Namespace user
const token = await db.signin({
namespace: 'surrealdb',
username: 'tobie',
password: 'surrealdb',
});
// Authenticate with a Database user
const token = await db.signin({
namespace: 'surrealdb',
database: 'docs',
username: 'tobie',
password: 'surrealdb',
});
// Authenticate with a Scope user
const token = await db.signin({
namespace: 'surrealdb',
database: 'docs',
scope: 'user',
// Also pass any properties required by the scope definition
email: 'info@surrealdb.com',
pass: '123456',
});
.invalidate()
Invalidates the authentication for the current connection.
async db.invalidate()
Example usage
await db.invalidate();
.authenticate()
Authenticates the current connection with a JWT token.
async db.authenticate(token)
Arguments
Arguments | Description | |
---|---|---|
token | The JWT authentication token. |
Example usage
await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA');
.let()
Assigns a value as a parameter for this connection.
async db.let(key, val)
Arguments
Arguments | Description | |
---|---|---|
key | Specifies the name of the variable. | |
val | Assigns 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.
async db.unset(key)
Arguments
Arguments | Description | |
---|---|---|
key | Specifies the name of the variable. |
Example usage
// Remove the variable from the connection
await db.unset('name');
.live()
Initiates a live query.
async db.live<T>(table, callback, diff)
Arguments
Arguments | Description | |
---|---|---|
table | The table name to listen for changes for | |
callback | A callback function that processes live notifications | |
diff | If set to true, live notifications will include an array of JSON Patch objects, rather than the entire record for each notification. |
Example usage
// The uuid of the live query will be returned
const queryUuid = await db.live(
"person",
// The callback function takes an object with the 'action' and 'result' properties
({ action, result }) => {
// action can be: 'CREATE', 'UPDATE', 'DELETE' or 'CLOSE'
if (action === 'CLOSE') return;
// result contains either the entire record, or a set of JSON patches when diff mode is enabled
processSomeLiveQueryUpdate(result);
}
)
.listenLive()
Registers a callback function for a running live query.
async db.listenLive<T>(queryUuid, callback)
Arguments
Arguments | Description | |
---|---|---|
queryUuid | The UUID of a running live query | |
callback | A callback function that processes live notifications |
Example usage
await db.listenLive(
queryUuid,
// The callback function takes an object with the "action" and "result" properties
({ action, result }) => {
// action can be: "CREATE", "UPDATE", "DELETE" or "CLOSE"
if (action === 'CLOSE') return;
// result contains either the entire record, or a set of JSON patches when diff mode is enabled
processSomeLiveQueryUpdate(result);
}
)
.kill()
Kills a running live query by it's UUID
async db.kill(queryUuid)
Arguments
Arguments | Description | |
---|---|---|
queryUuid | The UUID of the live query you wish to kill |
Example usage
await db.kill(queryUuid)
.query()
Runs a set of SurrealQL statements against the database.
async db.query<T>(query, vars)
Arguments
Arguments | Description | |
---|---|---|
query | Specifies the SurrealQL statements. | |
vars | Assigns variables which can be used in the query. |
Example usage
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;
.select()
Selects all records in a table, or a specific record, from the database.
async db.select<T>(thing)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or a record ID to select. |
Example usage
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');
Translated query
This function will run the following query in the database.
SELECT * FROM $thing;
.create()
Creates a record in the database.
async db.create<T>(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or a record ID to create. | |
data | The document / record data to insert. |
Example usage
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',
});
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.
async db.insert<T>(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name to insert to. | |
data | Either a single document/record or an array of documents/records to insert |
Example usage
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' },
]);
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.
async db.update<T>(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to update. | |
data | The document / record data to insert. |
Example usage
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',
});
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.
async db.merge<T>(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to merge. | |
data | The document / record data to insert. |
Example usage
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',
});
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.
async db.patch(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to patch. | |
data | The 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.
async db.delete<T>(thing)
Arguments
Arguments | Description | |
---|---|---|
thing | The 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;