---
title: "Serverless, end to end | SurrealDB"
description: "Connect to SurrealDB from Cloudflare Workers, Vercel Edge, Deno, Node and Bun, with the JavaScript SDK, Surqlize, or the PostgreSQL and MySQL drivers."
url: https://surrealdb.com/connect/javascript
---

# Serverless, end to end.

Connect from anywhere, from the edge to the edge.

[Start free on Earth](https://studio.surrealdb.com/current/instances/deploy) [JavaScript SDK docs](https://surrealdb.com/docs/sdk/javascript)

CLI

MCP

`surreal cloud instance create my-agent --region earth`

Copy

**Runs serverless.** On Earth a database starts with its first query, in ~300ms from cold, and scales to zero instantly when idle.

**Connects serverless.** HTTP and WebSocket only, so a Worker, an edge function or a browser needs no TCP socket.

**Speaks your stack.** The SDK and Surqlize for SurrealQL, and SQL drivers for PostgreSQL, MySQL, Drizzle and Kysely.

1. ![Babcock](https://surrealdb.com/assets/static/babcock.lo4rnVg1.svg)
2. ![ING](https://surrealdb.com/assets/static/ing.X3I6S3_V.svg)
3. ![British Airways](https://surrealdb.com/assets/static/british-airways.KEsZiwV-.svg)
4. ![Nvidia](https://surrealdb.com/assets/static/nvidia.DaIEuMil.svg)
5. ![Apple](https://surrealdb.com/assets/static/apple.D5pq4flY.svg)
6. ![SpaceX](https://surrealdb.com/assets/static/spacex.CQJEk-IL.svg)
7. ![Samsung](https://surrealdb.com/assets/static/samsung.CH-vQgnb.svg)
8. ![adidas](https://surrealdb.com/assets/static/adidas.DdTC5qhk.svg)
9. ![Tencent](https://surrealdb.com/assets/static/tencent.paQmLxyy.svg)
10. ![Alibaba](https://surrealdb.com/assets/static/alibaba.B16idgfM.svg)
11. ![PolyAI](https://surrealdb.com/assets/static/poly-ai.c3w_fAg6.svg)
12. ![Later](https://surrealdb.com/assets/static/later.Ds736jFO.svg)
13. ![Verizon](https://surrealdb.com/assets/static/verizon.BI7CajdX.svg)
14. ![Liberty Mutual](https://surrealdb.com/assets/static/liberty-mutual.B7qOU1pd.svg)
15. ![Walmart](https://surrealdb.com/assets/static/walmart.BjDg_Sr8.svg)
16. ![Carrier](https://surrealdb.com/assets/static/carrier.D21gC6NX.svg)
17. ![Saks Fifth Avenue](https://surrealdb.com/assets/static/saks-fifth-avenue.COIDpLSb.svg)
18. ![San Francisco Compute Company](https://surrealdb.com/assets/static/sfcc.B7jlImq4.svg)
19. ![Shield AI](https://surrealdb.com/assets/static/shield-ai.pINZ0KJr.svg)
20. ![Wix](https://surrealdb.com/assets/static/wix.DvHhmoBi.svg)

01 |CHOOSE A CLIENT

## One database, three ways to connect

Serverless and edge runtimes cannot open raw TCP sockets, so every client here speaks HTTP and WebSocket. The same code runs in a Worker, a function or a browser.

SURREALDB

### [The JavaScript SDK, for SurrealQL](https://surrealdb.com/connect/javascript#sdk)

The surrealdb package speaks SurrealQL over HTTP or WebSocket, with the full data model: graph, vectors, live queries and record access.

Connect with the SDK

SURREALQL, TYPED

### [Surqlize, for a type-safe query builder](https://surrealdb.com/connect/javascript#surqlize)

Define tables once with t.* builders and get typed selects, writes, graph edges and live queries, with no code generation. It runs on the SDK.

Add Surqlize

POSTGRES AND MYSQL

### [SQL drivers, for SQL and your ORM](https://surrealdb.com/connect/javascript#sql-drivers)

@surrealdb/pg and @surrealdb/mysql send PostgreSQL and MySQL SQL over HTTP and WebSocket, so they run where TCP sockets do not, and Drizzle and Kysely run on top.

Connect with SQL

02 |SURREALDB

## The JavaScript SDK

The official client for SurrealQL. Connect over HTTPS from a Worker, one connection for each invocation, with a token in a secret.

Install

Copy

```
npm install surrealdb
```

Cloudflare Worker

Copy

```
1import { Surreal } from "surrealdb";23interface Env {4    SURREAL_URL: string; // https://abc123.surrealdb.earth5    SURREAL_TOKEN: string;6}78export default {9    async fetch(request: Request, env: Env): Promise<Response> {10        // A connection per invocation: nothing to keep alive.11        const db = new Surreal();1213        await db.connect(env.SURREAL_URL, {14            namespace: "prod",15            database: "app",16            authentication: env.SURREAL_TOKEN,17        });1819        try {20            const [people] = await db21                .query("SELECT name, age FROM person WHERE age > $min", { min: 18 })22                .collect<[{ name: string; age: number }[]]>();2324            return Response.json(people);25        } finally {26            await db.close();27        }28    },29};
```

Per-request identity

Copy

```
// The identity is whoever is asking, decided for every request.await db.connect("https://abc123.surrealdb.earth", {    namespace: "prod",    database: "app",    authentication: {        resolve: () => requestContext.getStore()?.token ?? null,        when: "request",    },});
```

WebSocket and records

Copy

```
import { RecordId, Surreal } from "surrealdb";// A WebSocket for sessions and live queries, in Node, Bun, Deno or a browser.const db = new Surreal();await db.connect("wss://abc123.surrealdb.earth", {    namespace: "prod",    database: "app",    authentication: { username: "root", password: "root" },});await db.create(new RecordId("person", "tobie")).content({ name: "Tobie", age: 30 });
```

03 |SURQLIZE

## Typed queries with Surqlize

A type-safe TypeScript ORM for SurrealDB. Tables are defined with t.* builders, and TypeScript infers every result type without code generation. It takes the same Surreal client.

Install

Copy

```
npm install surqlize surrealdb
```

Define, connect and query

Copy

```
1import { Surreal } from "surrealdb";2import { orm, t, table } from "surqlize";34const person = table("person", {5    name: t.string(),6    age: t.number(),7    created: t.date().default(() => new Date()),8});910const surreal = new Surreal();11await surreal.connect("https://abc123.surrealdb.earth", {12    namespace: "prod",13    database: "app",14    authentication: { token: process.env.SURREAL_TOKEN },15});1617const db = orm(surreal, person);1819await db.create("person").content({ name: "Ada", age: 36 });2021// The result type is inferred: { name: string; age: number }[]22const adults = await db23    .select("person")24    .where((p) => p.age.gte(18))25    .return((p) => ({ name: p.name, age: p.age }));
```

Surqlize targets SurrealDB 3 and later, and needs the surrealdb SDK 2.1 or later installed beside it, as one copy.

04 |SURREALDB POSTGRES AND MYSQL

## SQL drivers for the edge

@surrealdb/pg and @surrealdb/mysql run PostgreSQL and MySQL SQL against SurrealDB over HTTP and WebSocket. Values in a template are bound as typed parameters, never interpolated into the text.

PostgreSQL

Copy

```
npm install @surrealdb/pg
```

Copy

```
1import { connect } from "@surrealdb/pg";23const sql = connect("postgres://root:root@abc123.surrealdb.earth/app?namespace=prod");45const name = "Tobie";6const rows = await sql`SELECT name, age FROM person WHERE name = ${name}`;78// Several statements in one request, all or nothing.9const [created, count] = await sql.batch([10    sql`INSERT INTO person (id, name) VALUES (${"a"}, ${"A"})`,11    sql`SELECT count(*) FROM person`,12]);1314// SurrealQL on the same connection, with the same namespace, database and auth.15const graph = await sql.surql`SELECT ->authored->post.title AS posts FROM person`;
```

MySQL

Copy

```
npm install @surrealdb/mysql
```

Copy

```
1import { connect } from "@surrealdb/mysql";23const sql = connect("mysql://root:root@abc123.surrealdb.earth/app?namespace=prod");45const name = "Tobie";6const rows = await sql`SELECT name, age FROM person WHERE name = ${name}`;78// An interactive transaction runs over a WebSocket session.9await sql.begin(async (tx) => {10    await tx`UPDATE account SET balance = balance - ${10} WHERE id = ${"x"}`;11    await tx`UPDATE account SET balance = balance + ${10} WHERE id = ${"y"}`;12});
```

Bring your ORM

Copy

```
// Drizzle on PostgreSQLimport { Pool } from "@surrealdb/pg";import { drizzle } from "drizzle-orm/node-postgres";const pool = new Pool({ connectionString: env.SURREAL_PG_URL });const db = drizzle({ client: pool as never });
```

Copy

```
// Kysely on MySQLimport { createPool } from "@surrealdb/mysql/callback";import { Kysely, MysqlDialect } from "kysely";const db = new Kysely({    dialect: new MysqlDialect({ pool: createPool({ uri: env.SURREAL_MYSQL_URL }) as never }),});
```

Connection options

Copy

```
connect({    url: "surrealdb+wss://abc123.surrealdb.earth/prod/app",    auth: { username: "root", password: "..." }, // or { token } or () => token    transport: "auto", // "http" | "ws"    timeout: 15_000,});
```

05 |GOOD TO KNOW

## Runtimes, transports and credentials

RUNTIMES

### [Where each one runs](https://surrealdb.com/docs/sdk/javascript)

All three use fetch, WebSocket and AbortController, and no Node built-ins. They run on Cloudflare Workers, Vercel Edge, Deno Deploy, Bun, Node 20 and later, and in browsers. Node versions without a global WebSocket need one passed in, for example from ws.

Read the SDK docs

TRANSPORTS

### [HTTP for one call, WebSocket for a session](https://surrealdb.com/earth)

One-shot queries go over HTTP, with no handshake, which is the lowest latency from a cold isolate. Interactive transactions and live queries open a WebSocket. The SQL drivers choose for you with transport auto.

Run it on Earth

CREDENTIALS

### [Tokens, not passwords, in the client](https://surrealdb.com/surrealdb/auth)

Give each client a token, or a function that returns one. Never put root credentials in browser code. Record access and permissions decide what a token may read and write.

Explore auth

TRUSTED BY

## Enterprise teams building on SurrealDB

[See more case studies](https://surrealdb.com/casestudies)

### [Three data stores collapsed into one](https://surrealdb.com/customer/samsung)

![Samsung](https://surrealdb.com/assets/static/4c58b81e7b3c9466.C_Hv0eml.svg)

### [An AI assistant for 10,000 technicians](https://surrealdb.com/customer/verizon)

![Verizon](https://surrealdb.com/assets/static/18b99996c689000f.B5PQ-nI9.svg)

### [Nine backend tools consolidated into one](https://surrealdb.com/customer/tencent)

![Tencent](https://surrealdb.com/assets/static/401d8346058682c8.DqM87mst.svg)

### [Low-latency RAG, under the customer's control](https://surrealdb.com/customer/polyai)

![PolyAI](https://surrealdb.com/assets/static/c5fa07c66cd05131.BnC7wHcc.svg)

### [45 million recommendation queries a month](https://surrealdb.com/customer/saks)

![Saks Fifth Avenue](https://surrealdb.com/assets/static/saks-fifth-avenue-white.pDJ9HGmf.svg)

## JavaScript, answered

Which one should I use?

Use the JavaScript SDK for SurrealQL and the full data model. Add Surqlize if you want typed queries on top of it. Use the SQL drivers if you want to write PostgreSQL or MySQL SQL, or run Drizzle or Kysely, from a runtime without TCP sockets.

Can I use the standard pg or mysql2 packages on Cloudflare Workers?

Can I mix SurrealQL and SQL on one connection?

What are the limits of the SQL drivers today?

THE PLATFORM

## Everything an application and its agents know. Five surfaces, one engine.

Database

Document, graph, vector, time-series and relational in one engine.

![Five data models as dotted tiles: documents, graph, vector, time-series and relational](https://surrealdb.com/assets/static/platform-database.DUdumYDz.avif)

Read more

[Database](https://surrealdb.com/surrealdb)

Agent Memory

What an agent learns, with its source and its time, in the same engine.

![A timeline of remembered facts, each with its source](https://surrealdb.com/assets/static/platform-agent-memory.Cvv8D5Wl.avif)

Read more

[Agent Memory](https://surrealdb.com/agent-memory)

Cloud

Dedicated clusters by region, or serverless on SurrealDB Earth.

![Clusters in three regions on a world map, each running or scaling](https://surrealdb.com/assets/static/platform-cloud.--QZnaVi.avif)

Read more

[Cloud](https://surrealdb.com/cloud)

Studio

Query, explore and design the schema from the browser.

![A SurrealQL query in Studio and the schema graph under it](https://surrealdb.com/assets/static/platform-studio.7ykBFNLq.avif)

Read more

[Studio](https://surrealdb.com/studio)

MCP

Every model that speaks MCP reaches the database and the memory directly.

![Three models connected through MCP to the database and Agent Memory](https://surrealdb.com/assets/static/platform-mcp.D_oH0_wm.avif)

Read more

[MCP](https://surrealdb.com/mcp)

IN PRODUCTION

## Trusted at scale. Samsung, Nvidia, Verizon, Tencent, and Walmart run on SurrealDB.

14,000+

Developers building on SurrealDB Cloud

4M+

Developers building on SurrealDB worldwide

FROM THE TEAMS

> SurrealDB gives us a foundation where we can unify semantic search, knowledge graphs, and AI-driven decision making without stitching together multiple systems. Collapsing responsibility into SurrealDB has become our default engineering posture.

*Justin Foley*

VP of Engineering, Later

GET STARTED

## Connect in one request. Deploy a database on SurrealDB Earth and query it from your first Worker.

[Start free with SurrealDB](https://studio.surrealdb.com/current/instances/deploy) [JavaScript SDK docs](https://surrealdb.com/docs/sdk/javascript)

![ISO 27001](https://surrealdb.com/assets/static/iso.BzQy4FFy.svg)

![AICPA SOC 2 Type 2](https://surrealdb.com/assets/static/aicpa-soc.CE_YjqhK.svg)

![Cyber Essentials](https://surrealdb.com/assets/static/cyber-essentials.CtbmbYfL.svg)

![GDPR](https://surrealdb.com/assets/static/gdpr.IadR7loS.svg)

![Cyber Essentials Plus](https://surrealdb.com/assets/static/cyber-essentials-plus.Cl5P05xe.svg)

```json
{"@context":"https://schema.org","@type":"Organization","@id":"https://surrealdb.com/#organization","name":"SurrealDB","url":"https://surrealdb.com","logo":"https://surrealdb.com/assets/static/logo.BG7_TG2b.svg","description":"SurrealDB is a database for every agent. It starts on its first query, scales to zero when idle, speaks Postgres and MySQL, and remembers in one query.","foundingDate":"2022","legalName":"SurrealDB Ltd","identifier":{"@type":"PropertyValue","propertyID":"GB-COH","value":"13615201"},"address":{"@type":"PostalAddress","streetAddress":"3rd Floor, 1 Ashley Road","addressLocality":"Altrincham","addressRegion":"Cheshire","postalCode":"WA14 2DT","addressCountry":"GB"},"contactPoint":[{"@type":"ContactPoint","contactType":"customer support","email":"support@surrealdb.com","url":"https://surrealdb.com/contact","availableLanguage":"English"},{"@type":"ContactPoint","contactType":"sales","email":"info@surrealdb.com","url":"https://surrealdb.com/contact","availableLanguage":"English"},{"@type":"ContactPoint","contactType":"security","email":"security@surrealdb.com","url":"https://surrealdb.com/.well-known/security.txt","availableLanguage":"English"},{"@type":"ContactPoint","contactType":"legal","email":"legal@surrealdb.com","url":"https://surrealdb.com/legal","availableLanguage":"English"}],"hasCertification":[{"@type":"Certification","name":"SOC 2 Type 2"},{"@type":"Certification","name":"GDPR"},{"@type":"Certification","name":"Cyber Essentials Plus"},{"@type":"Certification","name":"ISO 27001"}],"owns":[{"@type":"SoftwareApplication","name":"SurrealDB","url":"https://surrealdb.com/surrealdb"},{"@type":"SoftwareApplication","name":"Agent Memory","url":"https://surrealdb.com/agent-memory"}],"knowsAbout":["multi-model databases","document databases","graph databases","vector search","time-series databases","SurrealQL","Agent Memory","real-time databases","embedded databases","AI agent database","graph ontology","distributed database","knowledge graphs","distributed transaction protocols","highly-scalable databases"],"sameAs":["https://www.wikidata.org/wiki/Q124316308","https://github.com/surrealdb/surrealdb","https://twitter.com/surrealdb","https://www.youtube.com/@surrealdb","https://www.linkedin.com/company/surrealdb","https://discord.gg/surrealdb","https://www.reddit.com/r/surrealdb","https://www.instagram.com/surrealdb","https://medium.com/surrealdb","https://dev.to/surrealdb"]}
```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://surrealdb.com"},{"@type":"ListItem","position":2,"name":"Javascript","item":"https://surrealdb.com/connect/javascript"}]}
```

```json
{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Which one should I use?","acceptedAnswer":{"@type":"Answer","text":"Use the JavaScript SDK for SurrealQL and the full data model. Add Surqlize if you want typed queries on top of it. Use the SQL drivers if you want to write PostgreSQL or MySQL SQL, or run Drizzle or Kysely, from a runtime without TCP sockets."}},{"@type":"Question","name":"Can I use the standard pg or mysql2 packages on Cloudflare Workers?","acceptedAnswer":{"@type":"Answer","text":"They need TCP sockets, which most serverless runtimes do not offer. Where TCP is available, pg, mysql2 and other native drivers connect to the PostgreSQL and MySQL wire protocols of SurrealDB directly. Where it is not, use @surrealdb/pg and @surrealdb/mysql, which use HTTP and WebSocket."}},{"@type":"Question","name":"Can I mix SurrealQL and SQL on one connection?","acceptedAnswer":{"@type":"Answer","text":"Yes. Both SQL drivers have a surql tagged template that runs SurrealQL on the same connection, with the same namespace, database and authentication."}},{"@type":"Question","name":"What are the limits of the SQL drivers today?","acceptedAnswer":{"@type":"Answer","text":"The drivers are at version 0.1.0 and need an instance that serves the pgsql and mysql RPC methods. Cursors, COPY, LISTEN and NOTIFY, and Drizzle neon-serverless and planetscale-serverless adapters are not provided. The compatibility notes list the rest."}}]}
```
