pocketbase-better-auth
v1.0.16
Published
Better Auth PocketBase Adapter
Downloads
286
Maintainers
Readme
PocketBase Better Auth Adapter
A complete, production-ready adapter to use Better Auth with PocketBase as your authentication backend. This README is your single source for setup, usage, development, deployment, troubleshooting, and deep technical reference.
Table of Contents
- Features
- How It Works
- Installation
- PocketBase Schema Setup
- Usage
- API Reference
- Project Structure
- Development Guide
- Deployment
- Troubleshooting
- Security
- Resources & Links
Features
- 🔐 Full Better Auth support: Sessions, accounts, verifications, and more
- 🗄️ PocketBase-native: Uses PocketBase collections and admin API
- 🛠️ TypeScript-first: Fully typed, with type definitions included
- 🧩 Plug-and-play: Works with Next.js, Express, and any Node backend
- 📝 Customizable: Use singular or plural table names, debug logging, and more
- 🧪 Tested: 17+ unit tests, robust error handling
How It Works
This adapter implements the Better Auth adapter factory API using PocketBase as the backend. It translates Better Auth's CRUD operations into PocketBase collection queries, handling:
- Admin authentication (never expose admin credentials to the client!)
- Where clause translation: Converts Better Auth queries to PocketBase filter strings
- Pagination: Maps limit/offset to PocketBase's page/perPage
- Batch operations: Emulates
updateMany/deleteManyby fetching and looping - Type safety: All operations are fully typed
Installation
pnpm add pocketbase-better-auth better-auth pocketbase
# or
npm install pocketbase-better-auth better-auth pocketbase- 🔐 Full Better Auth support: Sessions, accounts, verifications, and more
- 🗄️ PocketBase-native: Uses PocketBase collections and admin API
- 🛠️ TypeScript-first: Fully typed, with type definitions included
- 🧩 Plug-and-play: Works with Next.js, Express, and any Node backend
- � Customizable: Use singular or plural table names, debug logging, and more
- � Tested: 17+ unit tests, robust error handling
pnpm add pocketbase-better-auth better-auth pocketbase
# or
npm install pocketbase-better-auth better-auth pocketbasePocketBase Schema Setup
You must create the required collections in PocketBase. The easiest way is to import the provided schema:
- Open PocketBase admin dashboard (
http://127.0.0.1:8090/_/) - Go to Settings > Import collections
- Copy the contents of
schema/pocketbase.collections.jsonfrom this repo - Paste into the import dialog
- switch "merge" on if you dont want to lost your existing collections
- Review the detected changes and click Confirm and import
Collections created:
user- Stores user information (name, email, emailVerified, image, timestamps)session- Stores active sessions (userId, token, expiresAt, IP, user agent, timestamps)account- Stores OAuth/social accounts (userId, provider info, tokens, timestamps)verification- Stores verification tokens (identifier, value, expiresAt, timestamps)
Note: The schema uses singular names by default. Set
usePlural: falsein the adapter config to match. Note2: Better-auth adapter will not use the default "users" collection witch is a different type (Auth collection)
Usage
1. Basic Setup
import { betterAuth } from "better-auth";
import { pocketBaseAdapter } from "pocketbase-better-auth";
import PocketBase from "pocketbase";
const pb = new PocketBase("http://127.0.0.1:8090");
await pb.admins.authWithPassword("[email protected]", "your-admin-password");
export const auth = betterAuth({
database: pocketBaseAdapter({
pb,
usePlural: false, // IMPORTANT: Use false to match the singular schema names (user, session, account, verification)
debugLogs: false, // set true for verbose logs
}),
emailAndPassword: { enabled: true },
});2. Using Environment Variables (Email/Password or JWT Token)
export const auth = betterAuth({
database: pocketBaseAdapter({
pb: {
url: process.env.POCKETBASE_URL || "http://127.0.0.1:8090",
// Option 1: Email/password (classic)
adminEmail: process.env.POCKETBASE_ADMIN_EMAIL,
adminPassword: process.env.POCKETBASE_ADMIN_PASSWORD,
// Option 2: JWT admin token (recommended for serverless/CI)
token: process.env.POCKETBASE_TOKEN,
},
usePlural: false, // Set to false to match the provided schema (singular names)
debugLogs: process.env.NODE_ENV === "development",
}),
emailAndPassword: { enabled: true },
});If both
tokenandadminEmail/adminPasswordare provided, the adapter will use the token.
3. API Route Example (Next.js App Router)
// app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
export const { GET, POST } = auth.handler;4. Client Usage Example
import { createAuthClient } from "better-auth/client";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL || "http://localhost:3000",
});
export const { useSession, signIn, signOut, signUp } = authClient;API Reference
pocketBaseAdapter(options)
| Option | Type | Default | Description |
|-------------|-------------------------------------------------------------|-----------|--------------------------------------------------|
| pb | PocketBase \| { url: string; adminEmail?: string; adminPassword?: string; token?: string } | (required) | PocketBase instance or config object |
| usePlural | boolean | true | Use plural collection names. Set to false for the provided schema which uses singular names (user, session, account, verification) |
| debugLogs | boolean | false | Enable debug logging |
Project Structure
├── src/
│ ├── index.ts # Main adapter implementation
│ └── adapter.test.ts # Unit tests
├── schema/
│ └── pocketbase.collections.json # Importable PocketBase schema (PocketBase v0.23+ format)
├── dist/ # Build output
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── vitest.config.tsSchema Format
The provided pocketbase.collections.json uses the new PocketBase v0.23+ format with:
fieldsarray instead ofschema- Flattened field properties (no nested
options) - Explicit
id,hidden,presentable,primaryKeyproperties for each field
If you're using an older version of PocketBase, you may need to manually create the collections through the admin UI.
Environment Variables
# PocketBase connection
POCKETBASE_URL=http://127.0.0.1:8090
# Option 1: Email/password
[email protected]
POCKETBASE_ADMIN_PASSWORD=your-admin-password
# Option 2: JWT admin token (recommended for CI/serverless)
POCKETBASE_TOKEN=your-pocketbase-admin-jwt-tokenDevelopment Guide
1. Install & Build
pnpm install
pnpm build2. Run Tests
pnpm test3. Lint
pnpm lint4. Adapter Structure
src/index.ts: ExportspocketBaseAdapter, implements all CRUD methods required by Better AuthparseWhere: Converts Better AuthWhereclauses to PocketBase filter strings- Handles admin authentication, error handling, and debug logging
5. How to Extend
- Add new fields to the schema and update
parseWhereif you need new query operators - Add custom logging or hooks as needed
Deployment
- Build the package:
pnpm build- Publish to npm (optional):
npm publish- Use in your app:
- Import and configure as shown above
Troubleshooting
"Invalid collections configuration"
- Make sure you're using PocketBase v0.23 or later (the schema uses the new
fieldsformat) - Verify the JSON is valid (you can use a JSON validator)
- Ensure you copied the entire file contents
"Collections created but no fields imported"
- This indicates an older PocketBase version that expects
schemainstead offields - Solution: Upgrade to PocketBase v0.23+, or manually create collections through the UI
"Cannot connect to PocketBase"
- Ensure PocketBase is running and the URL is correct
- Check your
POCKETBASE_URLenv variable
"Admin authentication failed"
- Verify admin email/password
- Ensure the admin account exists in PocketBase
"Collection not found"
- Import the schema file in PocketBase admin dashboard (Settings > Import collections)
- Ensure
usePluralmatches your collection names (usefalsefor the provided schema) - Verify collections exist: user, session, account, verification (singular) OR users, sessions, accounts, verifications (plural)
"Operation not permitted"
- Make sure you are using admin credentials (never expose these to the client!)
Security
- ⚠️ Never expose admin credentials to client-side code
- Always use environment variables for sensitive data
- Run the adapter server-side only
- Set PocketBase collection rules to restrict access as needed
Resources & Links
- Better Auth Documentation
- PocketBase Documentation
- GitHub Repository
- Reference: better-auth-instantdb
- Reference: remult-better-auth
License
MIT
