npm package: @imran3113/surreal-better-auth
Description: SurrealDB adapter for Better Auth
Author: cellograph
Latest version: 0.2.0

# @imran3113/surreal-better-auth

**SurrealDB v3 adapter for [Better Auth](https://better-auth.com)** — bringing the power of the multi-model database to your authentication system.

This adapter integrates SurrealDB's advanced querying capabilities with Better Auth's comprehensive authentication features. It targets **SurrealDB v3** with the **`surrealdb@2.0.0`** JS SDK.

> This package is a fork of [surreal-better-auth](https://github.com/oskar-gmerek/surreal-better-auth) by [Oskar Gmerek](https://github.com/oskar-gmerek), updated for SurrealDB v3 and `surrealdb@2.0.0` compatibility. Full credit to the original author for the foundational adapter design.

---

## Features

- **Full Better Auth compatibility** — Works with all Better Auth features and plugins
- **Optimized for SurrealDB v3** — Uses `BoundQuery`, direct record operations, and `type::record()`
- **Smart record links** — Automatic `record<table>` references instead of raw strings
- **Schema generation** — Works with Better Auth CLI for `.surql` schema output
- **Index generation** — Creates necessary database indexes out of the box
- **Flexible ID generation** — 8 strategies (ULID, UUID v4/v7, GUID, and more)
- **ESM and CommonJS** — Dual-format builds included
- **Zero extra dependencies** — Uses your existing `better-auth` and `surrealdb` packages

---

## Requirements

- **Node.js**: >= 20.0.0 or **Bun**: >= 1.2.0
- **better-auth**: ^1.3.7
- **surrealdb**: 2.0.0
- **SurrealDB server**: v3.x

---

## Installation

```bash
bun add @imran3113/surreal-better-auth surrealdb better-auth
```

```bash
# Other package managers
npm install @imran3113/surreal-better-auth surrealdb better-auth
pnpm add @imran3113/surreal-better-auth surrealdb better-auth
```

---

## Quick Start

### 1. Set up SurrealDB connection

```ts
// lib/db.ts
import { Surreal } from "surrealdb";

const db = new Surreal();
await db.connect("ws://localhost:8000");
await db.use({ namespace: "myapp", database: "production" });

export { db };
```

### 2. Configure Better Auth with the adapter

```ts
// lib/auth.ts
import { betterAuth } from "better-auth";
import { surrealdbAdapter } from "@imran3113/surreal-better-auth";
import { db } from "./db";

export const auth = betterAuth({
  database: surrealdbAdapter(db, {
    idGenerator: "surreal.ULID", // recommended for v3
  }),
  emailAndPassword: { enabled: true },
});
```

### 3. Generate and apply schema

```bash
bunx @better-auth/cli generate --output schema.surql
```

Apply the schema to SurrealDB via [Surrealist](https://surrealist.app/) or CLI import **before** running the application.

```bash
surreal import --conn ws://localhost:8000 --user root --pass root \
  --ns myapp --db production schema.surql
```

---

## Configuration

### Adapter Options

| Option | Type | Default | Description |
|---|---|---|---|
| `idGenerator` | `IdGenerator` | `undefined` | ID generation strategy (see below) |
| `usePlural` | `boolean` | `false` | Use plural table names (`users` vs `user`) |
| `allowPassingId` | `boolean` | `false` | Allow passing custom IDs when creating records |
| `debugLogs` | `boolean \| object` | `false` | Enable SurrealQL query logging |

### ID Generation Strategies

| Value | Generated By | Description |
|---|---|---|
| `"surreal.ULID"` | Database | ULID — sortable, recommended |
| `"surreal.UUIDv7"` | Database | UUID v7 — time-based, sortable |
| `"surreal.UUIDv4"` | Database | UUID v4 — random |
| `"surreal.UUID"` | Database | Default UUID |
| `"surreal.guid"` | Database | 20-char alphanumeric GUID |
| `"surreal"` | Database | SurrealDB default ID |
| `"sdk.UUIDv4"` | JS SDK | UUID v4 via `Uuid.v4()` |
| `"sdk.UUIDv7"` | JS SDK | UUID v7 via `Uuid.v7()` |
| `undefined` | Better Auth | Better Auth default or `generateId` |

### ID Generation Precedence

1. **`advanced.database.generateId()`** — Highest priority, overrides everything
2. **`idGenerator`** — Used if `generateId()` is not defined
3. **Custom ID from data** — Used if `allowPassingId: true` and ID is provided
4. **Better Auth default** — Used if `allowPassingId: true` and no ID in data
5. **Database default** — Fallback (same as `idGenerator: "surreal"`)

---

## Advanced Configuration

```ts
// lib/auth.ts
import { betterAuth } from "better-auth";
import { surrealdbAdapter } from "@imran3113/surreal-better-auth";
import { db } from "./db";

export const auth = betterAuth({
  database: surrealdbAdapter(db, {
    idGenerator: "surreal.ULID",
    usePlural: false,
    allowPassingId: true,
    debugLogs: true,
  }),
  emailAndPassword: { enabled: true },
  plugins: [
    // All Better Auth plugins are supported
  ],
});
```

### Granular Debug Logging

```ts
surrealdbAdapter(db, {
  debugLogs: {
    create: true,
    findOne: true,
    findMany: false,
    update: true,
    updateMany: false,
    delete: false,
    deleteMany: false,
    count: false,
  },
});
```

### Custom ID Generator

```ts
export const auth = betterAuth({
  database: surrealdbAdapter(db, {
    idGenerator: "surreal.ULID", // Ignored when generateId is provided
  }),
  advanced: {
    database: {
      generateId: () => "custom_" + Math.random().toString(36).substr(2, 9),
    },
  },
});
```

---

## SurrealDB v3 Notes

This adapter handles all SurrealDB v3 breaking changes automatically:

- **`DEFINE FIELD id` is invalid** — The `id` field is auto-managed; the schema generator omits it
- **`DEFINE INDEX ... COLUMNS id` is invalid** — Record IDs are inherently unique; no index needed
- **Non-existent tables throw errors** — Always apply schema before running the application
- **`type::thing()` renamed to `type::record()`** — The adapter uses `type::record()` internally
- **Hyphenated IDs are escaped** — `user:my-id` becomes `user:⟨my-id⟩`; prefer ULID/UUID generators

---

## SvelteKit Example

```ts
// src/hooks.server.ts
import { auth } from "$lib/auth";
import { svelteKitHandler } from "better-auth/svelte-kit";

export const handle = ({ event, resolve }) =>
  svelteKitHandler({ event, resolve, auth });
```

```ts
// src/lib/auth-client.ts
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient({
  baseURL: "http://localhost:5173",
});
```

---

## License

MIT