PocketBase Typegen

1.4.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

Generates PocketBase TypeScript types from a remote instance and demonstrates fully type-safe interaction with the PocketBase SDK for fetching, creating, and updating records, including advanced use cases like expanded relations and custom JSON field types.

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);

view raw JSON →