Skip to content

Languages

JavaScript quickstart

There are three ways to use SurrealDB from JavaScript and TypeScript. This page compares them, gives a prompt for each that you can paste into a coding agent, and walks through a first connection with the JavaScript SDK, which Surqlize is built on.

ClientUse it whenPackages
SurqlizeYou write TypeScript and want typed queries from a schema defined in codesurqlize and surrealdb
JavaScript SDKYou want to write SurrealQL, with the full data model, live queries and record accesssurrealdb
SQL driversYou want to write PostgreSQL or MySQL SQL, or run Drizzle, Kysely or Prisma@surrealdb/pg or @surrealdb/mysql

All three connect over HTTP or WebSocket, so they also run in browsers and in edge runtimes such as Cloudflare Workers, which cannot open a TCP socket.

Surqlize describes your tables in TypeScript with t.* builders, and TypeScript infers the type of every query result from them, with no code generation step. It takes the Surreal client from the JavaScript SDK to connect.

Add Surqlize to this TypeScript project and use it for its SurrealDB queries. Read https://surrealdb.com/docs/libraries/surqlize-typescript.md first, then follow the installation and schema pages it links to.
npm install surqlize surrealdb
Define a table and query it
import { Surreal } from "surrealdb";
import { orm, table, t } from "surqlize";

const user = table("user", {
	name: t.string(),
	email: t.string(),
	age: t.number(),
	created: t.date(),
});

const surreal = new Surreal();
await surreal.connect("ws://localhost:8000", {
	namespace: "main",
	database: "main",
	authentication: { username: "root", password: "secret" },
});

const db = orm(surreal, user);

await db.create("user").content({
	name: "Ada",
	email: "ada@example.com",
	age: 36,
	created: new Date(),
});

// adults: { name: string; email: string }[]
const adults = await db
	.select("user")
	.where((user) => user.age.gte(18))
	.return((user) => ({ name: user.name, email: user.email }));

Surqlize for TypeScript covers schemas, graph edges, live queries and transactions.

The SDK sends SurrealQL to SurrealDB and covers the whole data model. The steps below install it, connect, create records, read them back and close the connection.

Connect this project to SurrealDB with the JavaScript SDK. Read https://surrealdb.com/docs/languages/javascript.md and follow the steps for the JavaScript SDK.

Follow the installation guide to install the SDK as a dependency in your project. Once installed, you can import and instantiate the SDK to start using it.

import { Surreal } from 'surrealdb';

// Create a new Surreal instance
const db = new Surreal();

The Surreal class can be instantiated multiple times to connect to multiple SurrealDB instances at once.

You can use the .connect() method to connect to a local or remote SurrealDB instance. This method accepts a connection string and a set of options, including namespace, database, and authentication details. Supported connection protocols include:

  • WebSocket (ws://, wss://) for long-lived connections (e.g. backend or frontend applications)

  • HTTP (http://, https://) for short-lived stateless connections (e.g. server-side rendering applications)

  • Embedded engines using the WebAssembly engine or Node.js engine

The figure below shows how the three kinds of connection differ.

Three panels compare the ways to connect. Over WebSocket, the app opens one socket and keeps it open: it signs in once, sends many queries over the same socket, and the server pushes live query notifications to it without a request. Over HTTP, each request is separate and carries its own credentials or token, and a LIVE SELECT is refused because there is no socket to send notifications to. In an embedded database, the SurrealDB engine runs inside the application process as a library and keeps data in memory or in SurrealKV files, with no network and no server to run.Three panels compare the ways to connect. Over WebSocket, the app opens one socket and keeps it open: it signs in once, sends many queries over the same socket, and the server pushes live query notifications to it without a request. Over HTTP, each request is separate and carries its own credentials or token, and a LIVE SELECT is refused because there is no socket to send notifications to. In an embedded database, the SurrealDB engine runs inside the application process as a library and keeps data in memory or in SurrealKV files, with no network and no server to run.

This approach is suitable for connecting to a SurrealDB instance as a system user, for example when connecting from a server-side application. A new server creates the namespace main and the database main, which the example below uses.

const db = new Surreal();

// Connect as system user using the WebSocket protocol
await db.connect('ws://localhost:8000', {
	namespace: "main",
	database: "main",
	authentication: {
		username: 'root',
		password: 'secret'
	}
});

Alternatively, you can use the .signin() method to authenticate. However, passing the authentication details to the .connect() method is the preferred way, and allows for automatic reconnecting.

Once connected, you can use the .create() method to execute a CREATE query. This method accepts either a Table or a RecordId as the first argument. Use the .content() chain to specify the record data.

import { Table, RecordId } from 'surrealdb';

const users = new Table('user');
const products = new Table('product');

// Create a record with a random id
const user = await db.create(users).content({
	name: 'John',
	email: 'john@example.com',
	age: 32
});

console.log(user);
// { id: user:w6xb3izpgvz4n0gow6q7, name: 'John', email: 'john@example.com', age: 32 }

// Create a record with a specific ID
const appleId = new RecordId(products, 'apple');
const product = await db.create(appleId).content({
	name: 'Apple',
	price: 1.50,
	category: 'fruit'
});

console.log(product);
// { id: product:apple, name: 'Apple', price: 1.50, category: 'fruit' }

The .select() method retrieves all records from a table, or a single record by its RecordId. You can chain methods like .fields(), .where(), and .limit() to refine your query.

import { Table, RecordId, eq } from 'surrealdb';

const users = new Table('user');
const products = new Table('product');

// Select all users
const allUsers = await db.select(users);

// Select a specific record by ID
const apple = await db.select(new RecordId(products, 'apple'));

// Select specific fields with filtering
const results = await db.select(products)
	.fields('name', 'price')
	.where(eq("category", "fruit"))
	.limit(10);

In addition to the .eq() function in the above example, the SDK provides a full set of expression utilities for building type-safe SurrealQL conditions.

For more advanced use cases, you can use the .query() method to run SurrealQL statements directly. Use parameters to safely pass dynamic values.

const [cheapProducts] = await db.query<[{ name: string; price: number }[]]>(
	'SELECT name, price FROM product WHERE price < $max_price ORDER BY price',
	{ max_price: 5.00 }
);

console.log(cheapProducts);
// [{ name: 'Apple', price: 1.50 }]

Once you are done, close the connection to free up resources.

await db.close();

The SQL drivers send PostgreSQL or MySQL SQL to SurrealDB over HTTP and WebSocket, and each has a compatibility layer, so node-postgres, mysql2, Drizzle, Kysely and Prisma code runs on top of them. Every connection can also run SurrealQL with the surql template.

Connect this project to SurrealDB with the SurrealDB SQL drivers. Read https://surrealdb.com/docs/libraries/sql-drivers.md first, and use @surrealdb/pg or @surrealdb/mysql to match the SQL the project already uses.
npm install @surrealdb/pg
import { connect } from "@surrealdb/pg";

const sql = connect("postgres://root:secret@abc123.surrealdb.earth/app?namespace=prod");

const name = "Tobie";
const rows = await sql`SELECT name, age FROM person WHERE name = ${name}`;

SQL drivers for JavaScript covers the MySQL driver, transactions and the layers for each ORM.

There is a lot more you can do with the SDK, including updating and deleting records, authentication, live queries, and transactions.

Note

This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the JavaScript SDK reference.

Was this page helpful?