@rubixstudios/payload-surrealdb
v2.0.0
Published
SurrealDB adapter for Payload CMS
Readme
PayloadCMS + SurrealDB
A Payload CMS database adapter that integrates SurrealDB as a database backend. The adapter uses SurrealDB's PostgreSQL-compatible SQL interface with Payload's existing database functionality, including collections, relationships, transactions and migrations.
SurrealDB is an open-source, multi-model database designed to support structured and relational data through a unified database engine.
Learn more at SurrealDB.
Compatibility
The adapter supports Payload CMS v3 and v4, with SurrealDB v4 required for SQL compatibility.
| Component | Supported versions |
| ----------- | ------------------------------ |
| Payload CMS | ^3.94.2 or ^4.0.0-beta.12 |
| SurrealDB | v4, validated with 4.0.1 |
| Drizzle ORM | 0.45.2 |
| Node.js | >=24.22.3 <25 or >=26.13.1 |
Installation
pnpm add @rubixstudios/payload-surrealdb @payloadcms/db-postgres [email protected]Configure your SurrealDB connection using an environment variable.
DATABASE_URL=surrealdb+wss://user:[email protected]/app/payloadUse surrealdb+ws:// for local development without TLS. The namespace and database must already exist in SurrealDB.
// payload.config.ts
import { buildConfig } from 'payload'
import { surrealdbAdapter } from '@rubixstudios/payload-surrealdb'
export default buildConfig({
db: surrealdbAdapter({
pool: process.env.DATABASE_URL,
}),
})Additional options, including push, migrationDir, prodMigrations, beforeSchemaInit and afterSchemaInit, can be configured within surrealdbAdapter.
Schema and migrations
Generate versioned migrations using the standard Payload command.
pnpm exec payload migrate:createReview generated migrations before applying them, particularly when modifying existing database structures.
Run migrations at startup
Outside production, the adapter applies pending migration files from migrationDir when Payload starts. Payload records applied migrations and skips them on subsequent starts. The push option defaults to true. Set it to false to disable this behaviour.
db: surrealdbAdapter({
pool: process.env.DATABASE_URL,
push: false,
migrationDir: './src/migrations',
}),In production, configure prodMigrations with the generated migration list to apply pending migrations on startup.
Automatic startup migrations apply existing files. Changes to collections and globals still require payload migrate:create. To apply migrations manually, run pnpm exec payload migrate.
SurrealDB Cloud
When developing locally against a hosted SurrealDB Cloud database, you can explicitly use secure WebSocket transport with root authentication.
db: surrealdbAdapter({
pool: {
connectionString: process.env.DATABASE_URL!,
transport: 'ws',
auth: {
username: process.env.DATABASE_USERNAME!,
password: process.env.DATABASE_PASSWORD!,
},
},
push: false,
migrationDir: './src/migrations',
}),Configure the connection using environment variables.
DATABASE_URL=surrealdb+wss://xxxxx.surrealdb.earth/<namespace>/<database>
DATABASE_USERNAME=root
DATABASE_PASSWORD=replace-with-your-passwordThe surrealdb+wss:// scheme enables TLS, while transport: 'ws' explicitly selects WebSocket transport instead of automatic transport selection.
The namespace and database must already exist. With push: false, migrations must be applied manually or through an explicitly configured migration process.
Destructive migrations
Collection removals during rollback use the same WebSocket transaction as the migration and its history update. When adding foreign keys and indexes to new or existing tables, separate migrations may be required.
payload migrate:fresh validates the migration files before clearing the schema and reapplying them in order. Forward migrations run outside a transaction for SurrealDB schema compatibility, so earlier statements may remain committed if a migration fails.
Migration recovery
The adapter uses the internal payload_migration_guard table to detect incomplete forward migrations. A guard record is created before changes are applied and removed after successful completion. An active or incomplete guard blocks normal application startup and database-changing migration commands.
Run migrations from a single maintenance instance, pause application writes and back up the database. During migrate:fresh, the guard is recreated after the schema drop. An interruption during this transition may leave the database partially rebuilt or empty without a guard record.
If a migration fails, stop all application instances and inspect the schema, guard and payload_migrations history. Restore or repair the database before clearing the guard record:
SELECT * FROM "payload_migration_guard";
-- Only after confirming database consistency and that no migration is running:
DELETE FROM "payload_migration_guard" WHERE "id" = 1;Keep the guard table reserved for the adapter. It cannot detect incomplete migrations that occurred before this version.
Direct WebSocket migration queries default to a 60-second timeout. Override this with pool.timeout or the connection URL's timeout parameter in milliseconds. Set it to 0 to disable the deadline. A timeout does not confirm server-side cancellation.
Notes
- SurrealDB 4 is required. Not all PostgreSQL SQL statements and schema operations are supported.
- Existing PostgreSQL databases require a separate data migration when moving to SurrealDB.
- Certain schema modifications may require adjustments to generated migrations, including foreign key constraints, indexes and column renaming. SurrealDB 4.0.1 may report a successful column rename without applying it. Verify the resulting schema.
- Test migration rollbacks and destructive schema changes against a disposable database before using them in production.
Validation
Run pnpm test for the build and unit tests. Run pnpm test:integration for the migration and Payload smoke tests against a local SurrealDB 4.0.1 container.
To use an existing SurrealDB test server, set SURREAL_TEST_ENDPOINT and SURREAL_TEST_PASSWORD. The harness uses the root account to create and remove a unique namespace for each suite.
The smoke tests exercise authenticated REST requests, multipart uploads and downloads, document locks, relationship filters and joins, localized drafts, and version history. Transaction checks verify that a failed hook rolls back document updates, related writes, and version entries together. The job suite runs two workers against the same queue and verifies that a contested claim executes once and leaves scheduled jobs pending. The migration suite exercises migration generation, startup, rollback, and reapplication.
The GraphQL suite executes Payload's generated schema and checks authentication, access filters, mutations and relationship pagination. Trash tests cover default visibility, restore, permanent deletion and version cleanup. The plugin suite exercises Nested Docs breadcrumb updates, Redirects destination types and source uniqueness, and Search index synchronization.
SurrealDB can return SQLSTATE 40001 when two workers try to claim the same job. The worker can poll again after a claim transaction fails with that error.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support or inquiries:
- LinkedIn: rubixvi
- Website: Rubix Studios
Author
Rubix Studios
https://rubixstudios.com.au
