PocketBase Typegen
PocketBase Typegen is a utility that generates TypeScript definitions directly from your PocketBase database schema. It supports various input sources including a live PocketBase instance URL, a local SQLite database file, or an exported JSON schema. The current stable version is `1.4.1`, with releases occurring regularly to maintain compatibility with new PocketBase versions and introduce new features. Key differentiators include the automatic generation of a `TypedPocketBase` type, which allows for fully type-safe usage of the PocketBase JavaScript SDK, as well as distinct types for individual collections, expand relations, and `Create`/`Update` operations, significantly enhancing developer experience and reducing runtime errors in TypeScript projects.
Common errors
-
TypeError: require is not a function
cause Attempting to use `pocketbase-typegen` in a CommonJS (`require()`) environment when it is primarily an ESM package or your generated types are imported in an ESM context.fixEnsure your project is configured for ESM (e.g., `"type": "module"` in `package.json`) or that you are importing the generated types using `import` statements in `.js` or `.ts` files. -
TS2339: Property 'expand' does not exist on type '...' or Property 'user' does not exist on type '...'
cause This typically occurs when trying to access an expanded relation (`result.expand.user`) without providing the correct `Expand` generic type to the response, or without actually requesting the expansion from PocketBase via the `{ expand: 'field' }` option in `getOne`/`getList`.fixEnsure you are passing the `Expand` generic to your response type (e.g., `CommentsResponse<Metadata, Expand>`) and that your PocketBase query includes the `{ expand: 'relationFieldName' }` option. -
Error: Node.js v18.0.0 or higher is required.
cause You are attempting to run `pocketbase-typegen` with a Node.js version older than 18.fixUpdate your Node.js installation to version 18 or newer. You can use a tool like `nvm` (Node Version Manager) to easily manage multiple Node.js versions. -
Error: Must specify --url, --db, or --json.
cause The `pocketbase-typegen` CLI tool was invoked without specifying a source for the PocketBase schema (either a remote URL, local database file, or JSON schema export).fixProvide one of the required schema source options: `--url <your-pocketbase-url>`, `--db <path-to-db.db>`, or `--json <path-to-schema.json>`.
Warnings
- breaking Version `1.4.1` and newer explicitly require Node.js v18 or higher. Running with older Node.js versions will result in execution errors.
- breaking Starting with version `1.4.0`, `pocketbase-typegen` now emits `as const` objects with a companion union type instead of TypeScript `enum`s. This change improves compatibility with `--erasableSyntaxOnly` and related TypeScript compiler options.
- breaking Version `1.3.0` introduced breaking changes to support PocketBase `v0.23.x`. Ensure your PocketBase backend is updated to a compatible version if you are using `pocketbase-typegen v1.3.0` or newer.
- gotcha The `TypedPocketBase` type, which provides full SDK-wide type assertion, requires PocketBase JavaScript SDK `v0.18.3+`. If you are using an older SDK version with `pocketbase-typegen v1.2.0` or newer, you must pass the `--no-sdk` option during type generation to avoid compatibility issues.
- gotcha When generating types from a remote PocketBase instance using the `--url` option, you must provide authentication credentials via `--email` and `--password`, or an `--token`. Failing to do so will prevent the tool from accessing your schema.
Install
-
npm install pocketbase-typegen -
yarn add pocketbase-typegen -
pnpm add pocketbase-typegen
Imports
- TypedPocketBase
import TypedPocketBase from './pocketbase-types'
import { TypedPocketBase } from './pocketbase-types' - Collections
import Collections from './pocketbase-types'
import { Collections } from './pocketbase-types' - MyCollectionResponse
import MyCollectionResponse from './pocketbase-types'
import { MyCollectionResponse } from './pocketbase-types' - Create, Update
const Create = require('./pocketbase-types')import { Create, Update } from './pocketbase-types'
Quickstart
import PocketBase from 'pocketbase';
import { TypedPocketBase } from './pocketbase-types';
import { Collections, Create, Update, TasksResponse, CommentsResponse, UsersResponse } from './pocketbase-types';
// First, generate your types. Run this command in your terminal:
// npx pocketbase-typegen --url https://myproject.pockethost.io --email admin@myproject.com --password 'secr3tp@ssword!'
const pb = new PocketBase('http://127.0.0.1:8090') as TypedPocketBase;
async function exampleUsage() {
// Fetch a single task with full type safety
const task = await pb.collection(Collections.Tasks).getOne('RECORD_ID');
console.log('Fetched task:', task.title);
// Example with expanded relations and JSON field types
type Metadata = { likes: number };
type Expand = { user: UsersResponse };
const commentResult = await pb.collection(Collections.Comments).getOne<CommentsResponse<Metadata, Expand>>('COMMENT_RECORD_ID', { expand: 'user' });
console.log('Comment metadata likes:', commentResult.metadata?.likes);
console.log('Comment user username:', commentResult.expand.user.username);
// Create a new user record
const newUser: Create<Collections.Users> = {
name: 'Jane Doe',
username: 'janedoe',
password: 'password123',
passwordConfirm: 'password123',
email: 'jane@example.com',
emailVisibility: true,
verified: false,
};
await pb.collection(Collections.Users).create(newUser);
console.log('User created successfully.');
// Update an existing user record
const updatedUser: Update<Collections.Users> = {
name: 'Jane Smith',
};
await pb.collection(Collections.Users).update('USER_RECORD_ID', updatedUser);
console.log('User updated successfully.');
}
exampleUsage().catch(console.error);