### Usage Examples Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Offers complete usage examples demonstrating various SDK features, including authentication flows, CRUD operations, realtime subscriptions, pagination, file handling, error patterns, SSR integration, and TypeScript setup. ```APIDOC ## Usage Examples ### Description This section provides practical, end-to-end examples of how to use the PocketBase JavaScript SDK for common use cases. ### Example Categories - **Authentication**: Implementing login, registration, and logout flows. - **CRUD Operations**: Demonstrating fetching, creating, updating, and deleting records. - **Realtime Subscriptions**: Setting up listeners for real-time data changes. - **Pagination**: Handling paginated data retrieval. - **File Handling**: Uploading, downloading, and managing files. - **Error Handling Patterns**: Strategies for gracefully handling API errors. - **SSR Integration**: Examples for using the SDK in server-side rendering environments. - **TypeScript Setup**: Guidance on configuring TypeScript for optimal SDK usage. - **Advanced Filtering**: Complex filtering and sorting examples. ``` -------------------------------- ### Install PocketBase SDK Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Install the PocketBase SDK using npm. This is the first step to using the SDK in your JavaScript project. ```bash npm install pocketbase ``` -------------------------------- ### CollectionService Examples Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Demonstrates common operations with the CollectionService, including fetching all collections, getting a specific one, creating a new collection, and importing collections. ```typescript // Get all collections const collections = await pb.collections.getFullList(); ``` ```typescript // Get specific collection const users = await pb.collections.getOne('users'); ``` ```typescript // Create a new collection const newCollection = await pb.collections.create({ name: 'posts', type: 'base', fields: [ { name: 'title', type: 'text' }, { name: 'content', type: 'editor' }, ], }); ``` ```typescript // Import collections await pb.collections.import(collectionsArray, true); ``` -------------------------------- ### SvelteKit SSR Integration: Handle Hook Setup Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Example of setting up a PocketBase client instance in SvelteKit's `handle` hook for SSR. It loads auth state from cookies and refreshes the auth token. ```javascript // src/hooks.server.js import PocketBase from 'pocketbase'; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { event.locals.pb = new PocketBase('http://127.0.0.1:8090'); // load the store data from the request cookie string event.locals.pb.authStore.loadFromCookie(event.request.headers.get('cookie') || ''); try { // get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any) event.locals.pb.authStore.isValid && await event.locals.pb.collection('users').authRefresh(); } catch (_) { // clear the auth store on failed refresh event.locals.pb.authStore.clear(); } const response = await resolve(event); // send back the default 'pb_auth' cookie to the client with the latest store state response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie()); return response; } ``` -------------------------------- ### BackupService Example Usage Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Demonstrates common operations with the BackupService, including creating, listing, restoring, and deleting backups. ```typescript // Create backup const backup = await pb.backups.create('backup_' + new Date().toISOString()); // List backups const backups = await pb.backups.getFullList(); // Restore await pb.backups.restore(backups[0].key); // Delete await pb.backups.delete(backups[0].key); ``` -------------------------------- ### Install PocketBase SDK for Node.js Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Install the PocketBase SDK using npm for Node.js projects. ```sh npm install pocketbase --save ``` -------------------------------- ### AsyncAuthStore Example with AsyncStorage Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Example of initializing PocketBase with AsyncAuthStore using React Native's AsyncStorage for persistence. It defines custom save and initial state retrieval functions. ```typescript import AsyncStorage from '@react-native-async-storage/async-storage'; const store = new AsyncAuthStore({ save: async (serialized) => { await AsyncStorage.setItem('pb_auth', serialized); }, initial: await AsyncStorage.getItem('pb_auth'), }); const pb = new Client('http://127.0.0.1:8090', store); ``` -------------------------------- ### LocalAuthStore Example Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Demonstrates initializing PocketBase with LocalAuthStore and performing authentication. Auth state persists across page reloads and is restored automatically. ```typescript const pb = new Client('http://127.0.0.1:8090', new LocalAuthStore()); // Auth state persists across page reloads const authData = await pb.collection('users').authWithPassword('user@example.com', 'password'); // After page reload, auth state is restored console.log(pb.authStore.token); // Still valid console.log(pb.authStore.record); // User data restored ``` -------------------------------- ### CronService Example Usage Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Demonstrates how to list all cron jobs and manually run a specific job using the CronService. ```typescript // List jobs const jobs = await pb.crons.getFullList(); // Run job await pb.crons.run('cleanup_expired_tokens'); ``` -------------------------------- ### Authentication Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Examples for authenticating users with email and password, checking authentication status, and logging out. ```APIDOC ## Authentication This section covers user authentication, including logging in, checking the authentication state, and logging out. ### Authenticate with Password ```typescript const authData = await pb.collection('users').authWithPassword('user@example.com', 'password'); console.log(authData.record.id); console.log(pb.authStore.token); ``` ### Check Authentication Status ```typescript if (pb.authStore.isValid) { console.log('User is authenticated'); } ``` ### Logout ```typescript pb.authStore.clear(); ``` ``` -------------------------------- ### Get and Update Application Settings Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Demonstrates how to retrieve all application settings and then update specific metadata like the application name and URL. ```typescript // Get all settings const settings = await pb.settings.getAll(); console.log(settings.meta?.appName); // Update settings await pb.settings.update({ meta: { appName: 'My App', appUrl: 'https://example.com', }, }); ``` -------------------------------- ### Configuration and Options Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Explains various configuration options for the SDK, including client constructor options, query parameters, file upload settings, hook setup, auth store configuration, performance tuning, and SSR/Node.js integration. ```APIDOC ## Configuration and Options ### Description This section details the various configuration options available for customizing the PocketBase JavaScript SDK's behavior. ### Client Constructor Options - `baseUrl` (string): Required. The base URL of your PocketBase instance. - `collectionCache` (Map): Optional. A cache for collection schemas. - `realtime` (boolean): Optional. Enables or disables realtime subscriptions (defaults to true). - `autoCancellation` (boolean): Optional. Enables or disables auto-cancellation of requests (defaults to true). ### Query Parameters - Options for filtering, sorting, and pagination in list requests. ### File Upload Configuration - Options related to uploading files, such as `filename` and `mimeType`. ### Hook Setup - Configuring `beforeSend` and `afterSend` request hooks. ### Auth Store Configuration - Specifying the type of `AuthStore` to use (e.g., `LocalAuthStore`, `AsyncAuthStore`). ### Performance Tuning - Options that can affect performance, such as caching and request batching. ### SSR/Node.js Setup - Specific configurations for running the SDK in server-side rendering or Node.js environments. ``` -------------------------------- ### Create Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Examples for creating new records in a collection. Supports creating with basic fields and with file uploads. ```APIDOC ## Create Records ### Create Post This function creates a new post record with title, content, status, author, and creation timestamp. ```typescript async function createPost(title: string, content: string) { const post = await pb.collection('posts').create({ title, content, status: 'draft', author: pb.authStore.record?.id, created: new Date().toISOString(), }); return post; } ``` ### Create Post with Image This function creates a new post record and uploads an associated image file. ```typescript async function createPostWithImage(title: string, imageFile: File) { const formData = new FormData(); formData.set('title', title); formData.set('image', imageFile); formData.set('status', 'draft'); const post = await pb.collection('posts').create(formData); return post; } ``` ``` -------------------------------- ### Realtime Subscriptions with PocketBase SDK Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Shows how to subscribe to record changes using Server-Sent Events. This example subscribes to all changes in the 'posts' collection and logs the action and record data. ```typescript await pb.collection('posts').subscribe('*', (data) => { console.log(`Record ${data.action}:`, data.record); }); ``` -------------------------------- ### Execute Batch Requests Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example of using the BatchService to queue create and update operations on different collections and then sending them all at once. ```typescript const batch = pb.createBatch(); batch.collection('users').create({ name: 'John' }); batch.collection('posts').update('record_id', { title: 'New Title' }); const results = await batch.send(); ``` -------------------------------- ### Read Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Examples for retrieving single records, lists of records with pagination, all records, and searching records. ```APIDOC ## Read Records ### Get Single Post Retrieves a single post record by its ID, with options to expand related records. ```typescript async function getPost(id: string) { const post = await pb.collection('posts').getOne(id, { expand: 'author,category', }); return post; } ``` ### List Posts Retrieves a paginated list of posts, filtered by status and sorted by creation date. ```typescript async function listPosts(page: number = 1) { const result = await pb.collection('posts').getList(page, 20, { filter: 'status = "published"', sort: '-created', expand: 'author', }); return result; } ``` ### Get All Posts Retrieves all published posts, with options for filtering, sorting, and batching. ```typescript async function getAllPosts() { const posts = await pb.collection('posts').getFullList({ filter: 'status = "published"', sort: '-created', batch: 500, }); return posts; } ``` ### Search Posts Searches for posts based on a query string that matches the title or content, returning published posts. ```typescript async function searchPosts(query: string) { const posts = await pb.collection('posts').getList(1, 20, { filter: pb.filter( '(title ~ {:q} || content ~ {:q}) && status = "published"', { q: query } ), sort: '-created', }); return posts.items; } ``` ``` -------------------------------- ### Initialize PocketBase Client and Authenticate User Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Initialize the PocketBase client with your API endpoint and authenticate a user using their email and password. This is a common starting point for most SDK operations. ```javascript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); ... // authenticate as auth collection record const userData = await pb.collection('users').authWithPassword('test@example.com', '123456'); ``` -------------------------------- ### Generate API Record URL Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example of using `buildURL` to create a full URL for accessing API records. ```typescript const url = pb.buildURL('/api/records'); // http://127.0.0.1:8090/api/records ``` -------------------------------- ### API Route to Fetch Published Posts in SvelteKit Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md An example of a SvelteKit API route (`+server.js`) that uses the PocketBase instance available via `locals.pb` to fetch a list of published posts. It demonstrates basic data fetching for an API endpoint. ```typescript // src/routes/api/posts/+server.js export async function GET({ locals }) { const posts = await locals.pb.collection('posts').getList(1, 20, { filter: 'status = "published"', }); return new Response(JSON.stringify(posts)); } ``` -------------------------------- ### SvelteKit SSR Integration: Server-Side Endpoint Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Example of accessing the PocketBase instance from `event.locals` in a SvelteKit server-side endpoint to perform authenticated actions like login. ```javascript // src/routes/login/+server.js /** * Creates a `POST /login` server-side endpoint * * @type {import('./$types').RequestHandler} */ export async function POST({ request, locals }) { const { email, password } = await request.json(); const { token, record } = await locals.pb.collection('users').authWithPassword(email, password); return new Response('Success...'); } ``` -------------------------------- ### Add EventSource Polyfill for Realtime Subscriptions in Node.js Source: https://github.com/pocketbase/js-sdk/blob/master/README.md To use realtime subscriptions in Node.js, install and import the 'eventsource' package as a polyfill for EventSource. ```js // for server: npm install eventsource --save import { EventSource } from "eventsource"; // for React Native: npm install react-native-sse --save import EventSource from "react-native-sse"; global.EventSource = EventSource; ``` -------------------------------- ### Batch Operations in PocketBase SDK Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Demonstrates how to perform multiple transactional requests in a single call using the batch API. This example creates two posts in a single batch operation. ```typescript const batch = pb.createBatch(); batch.collection('posts').create({ title: 'Post 1' }); batch.collection('posts').create({ title: 'Post 2' }); const results = await batch.send(); ``` -------------------------------- ### Download File Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Initiates a file download for a given record and filename. This function generates a downloadable URL and programmatically clicks a link to start the download in the browser. ```typescript // Download file async function downloadFile(record: any, filename: string) { const url = pb.files.getURL(record, filename, { download: true, }); // Open download const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); } ``` -------------------------------- ### SDK Documentation Files Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/MANIFEST.txt This lists the generated markdown files that constitute the PocketBase JavaScript SDK's technical reference. Each file covers specific aspects of the SDK, from core client functionality to advanced usage patterns and examples. ```APIDOC ## SDK Documentation Files This document provides a manifest of the generated technical reference files for the PocketBase JavaScript SDK. Each file covers specific aspects of the SDK, from core client functionality to advanced usage patterns and examples. ### Files Generated 1. **README.md** (317 lines) * Overview and navigation guide * Quick start guide * Key concepts * Common patterns reference * Version and resource information 2. **01-client.md** (301 lines) * Client class documentation * Constructor parameters * Properties and methods * Request hooks (beforeSend, afterSend) * URL building and auto-cancellation * Filter expression construction * Integration examples 3. **02-record-service.md** (660 lines) * RecordService for collection records * CRUD operations (getList, getOne, create, update, delete) * Realtime subscriptions * Authentication methods (password, OAuth2, OTP) * Email verification and password reset * External auth provider management * Impersonation 4. **03-auth-store.md** (362 lines) * BaseAuthStore (memory storage) * LocalAuthStore (browser localStorage) * AsyncAuthStore (custom async storage) * Cookie management * Change listeners * Custom auth store implementation * SSR integration examples 5. **04-services.md** (778 lines) * CollectionService (collection definitions) * FileService (file URLs and access tokens) * LogService (application logs) * HealthService (API health checks) * SettingsService (app settings, email, S3, OAuth) * RealtimeService (SSE subscriptions) * BackupService (database backups) * CronService (scheduled jobs) * SQLService (raw SQL queries) * BatchService (transactional batch requests) 6. **05-types.md** (615 lines) * Response types (ListResult, RecordAuthResponse) * Record types (BaseModel, RecordModel, LogModel) * Collection types (BaseCollectionModel, ViewCollectionModel, AuthCollectionModel) * Configuration types (TokenConfig, OAuth2Config, EmailTemplate) * Authentication types (AuthMethodsList, AuthProviderInfo) * Request options (SendOptions, ListOptions, etc.) * Error types * Batch and utility types 7. **06-errors.md** (401 lines) * ClientResponseError class * HTTP status codes and meanings * Network error handling * Validation error structure * Common error scenarios * Error handling patterns * Best practices for error management 8. **07-configuration.md** (583 lines) * Client constructor options * Query parameters (page, sort, filter, expand) * File upload configuration * Hook configuration and examples * Auth store setup * Realtime configuration * Auto-cancellation settings * TypeScript configuration * SSR/Node.js setup * Performance tuning 9. **08-crud-service.md** (449 lines) * Base CRUD class documentation * Method signatures and behavior * getFullList() with batching * Pagination patterns * Search and filtering * Infinite scroll implementation * Type safety with generics * Response validation 10. **09-utilities.md** (461 lines) * filter() - safe SQL-like filter building * JWT functions (isTokenExpired, getTokenPayload) * Cookie functions (cookieParse, cookieSerialize) * Form data helpers * Query parameter serialization * URL building * File operations * Common utility patterns 11. **10-examples.md** (641 lines) * Setup and initialization * Authentication flows (password, OAuth2, OTP, registration) * CRUD operations with real examples * Batch operations * Realtime subscriptions * Pagination implementation * File upload and download * Error handling patterns * SSR integration * TypeScript setup * Advanced filtering ``` -------------------------------- ### BackupService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Manages database backups. Provides methods to create, list, upload, delete, restore, and get download URLs for backup files. ```APIDOC ## BackupService Manages database backups. ### Methods #### getFullList() Returns all backup files. ```typescript async getFullList(options?: CommonOptions): Promise> ``` #### create() Creates a new backup. ```typescript async create(basename?: string, options?: CommonOptions): Promise<{ [key: string]: any }> ``` #### upload() Uploads an existing backup file. ```typescript async upload(body: { file: File | Blob }, options?: CommonOptions): Promise<{ [key: string]: any }> ``` #### delete() Deletes a backup file. ```typescript async delete(key: string, options?: CommonOptions): Promise ``` #### restore() Restores the app from a backup. ```typescript async restore(key: string, options?: CommonOptions): Promise ``` #### getDownloadURL() Builds a download URL for a backup file. ```typescript getDownloadURL(token: string, key: string): string ``` ``` -------------------------------- ### Demonstrate Auto Cancellation Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example showing how disabling auto-cancellation allows duplicate requests to execute. If auto-cancellation were enabled, the second `getList` call would be cancelled. ```typescript pb.autoCancellation(false); // Disable auto-cancellation const list1 = await pb.collection('posts').getList(1, 20); const list2 = await pb.collection('posts').getList(1, 20); // Will execute ``` -------------------------------- ### Basic Usage of PocketBase SDK Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Demonstrates basic operations including initializing the client, logging in, fetching records, creating a new record, and logging out. Ensure the PocketBase server is running at the specified URL. ```typescript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); // Login const authData = await pb.collection('users').authWithPassword('user@example.com', 'password'); // Fetch records const posts = await pb.collection('posts').getList(1, 20); // Create record const newPost = await pb.collection('posts').create({ title: 'My Post', content: 'Lorem ipsum', }); // Logout pb.authStore.clear(); ``` -------------------------------- ### Creating a new client instance Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Instantiate a new PocketBase client with optional base URL and authentication store. ```APIDOC ## Creating new client instance ```js const pb = new PocketBase(baseURL = '/', authStore = LocalAuthStore); ``` ``` -------------------------------- ### Delete Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Example for deleting a record by its ID. ```APIDOC ## Delete Records ### Delete Post Deletes a post record by its ID and logs a success message. ```typescript async function deletePost(id: string) { const success = await pb.collection('posts').delete(id); if (success) { console.log('Post deleted'); } return success; } ``` ``` -------------------------------- ### Initialize PocketBase SDK in Browser (Script Tag) Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Include the SDK via a script tag for manual integration in browsers. Instantiate PocketBase with your API endpoint. ```html ``` -------------------------------- ### Client Constructor Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Instantiate the PocketBase Client with optional parameters. ```APIDOC ## Constructor ```typescript new Client(baseURL?: string, authStore?: BaseAuthStore | null, lang?: string) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | baseURL | string | "/" | The base PocketBase backend URL (e.g., 'http://127.0.0.1:8090') | | authStore | BaseAuthStore \| null | LocalAuthStore | Custom auth store instance. Defaults to LocalAuthStore in browsers, BaseAuthStore in Deno environments | | lang | string | "en-US" | Language code sent with requests as Accept-Language header | ``` -------------------------------- ### Unsubscribe by Topic Prefix Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Unsubscribes from all topics that start with the specified prefix. ```typescript async unsubscribeByPrefix(topicPrefix: string): Promise ``` -------------------------------- ### getFullList() Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/02-record-service.md Retrieves all records from a collection by fetching them in batches. Useful for getting all data without manual pagination. ```APIDOC ## getFullList() ### Description Returns all records by batch fetching (default 1000 per request). ### Method `async getFullList(options?: RecordFullListOptions): Promise>` OR `async getFullList(batch?: number, options?: RecordListOptions): Promise>` ### Parameters #### Query Parameters - **batch** (number) - Optional - Records per batch request, defaults to 1000. - **options** (RecordFullListOptions/RecordListOptions) - Optional - Query options. ### Response #### Success Response (200) - **Array** - An array containing all matching records. ### Request Example ```typescript // Get all records with defaults const allRecords = await pb.collection('posts').getFullList(); // With batch size and options const filtered = await pb.collection('posts').getFullList(500, { filter: 'status = "draft"', batch: 100, }); ``` ``` -------------------------------- ### Importing the Client Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md How to import the Client class into your project. ```APIDOC ## Import ```typescript import Client from 'pocketbase'; // or import { Client } from 'pocketbase'; ``` ``` -------------------------------- ### Create New PocketBase Client Instance Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Instantiate a new PocketBase client. Requires the base URL and an authentication store. ```javascript const pb = new PocketBase(baseURL = '/', authStore = LocalAuthStore); ``` -------------------------------- ### Update Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Examples for updating existing records, including updating basic fields and replacing associated files. ```APIDOC ## Update Records ### Update Post Updates an existing post record with provided fields and a timestamp for the last update. ```typescript async function updatePost(id: string, updates: { title?: string; content?: string }) { const updated = await pb.collection('posts').update(id, { ...updates, updated: new Date().toISOString(), }); return updated; } ``` ### Update Post Image Replaces the existing image file associated with a post record. ```typescript async function updatePostImage(id: string, newImage: File) { const updated = await pb.collection('posts').update(id, { image: newImage, }); return updated; } ``` ``` -------------------------------- ### Initialize PocketBase SDK in Browser (ES Modules) Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Import the SDK as an ES module for modern browser development. Initialize PocketBase with your API endpoint. ```html ``` -------------------------------- ### Instance methods Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Available methods on a PocketBase client instance, all of which return the client instance for chaining. ```APIDOC ## Instance methods > Each instance method returns the `PocketBase` instance allowing chaining. ### `pb.send(path, sendOptions = {})` Sends an api http request. ### `pb.autoCancellation(enable)` Globally enable or disable auto cancellation for pending duplicated requests. ### `pb.cancelAllRequests()` Cancels all pending requests. ### `pb.cancelRequest(cancelKey)` Cancels single request by its cancellation token key. ### `pb.buildURL(path)` Builds a full client url by safely concatenating the provided path. ``` -------------------------------- ### Custom Headers per Request Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Shows how to include custom headers in your requests, for example, when fetching a list of records. ```APIDOC ## Custom Headers per Request This example demonstrates how to send custom HTTP headers with your SDK requests. ### Fetching Records with Custom Headers ```typescript const records = await pb.collection('posts').getList(1, 20, { headers: { 'X-Custom-Header': 'value' }, fields: 'id,title', }); ``` ``` -------------------------------- ### Run Unit Tests Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Execute the unit tests for the SDK using npm. ```sh npm test ``` -------------------------------- ### Build for Production Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Build and minify the SDK for production deployment using npm. ```sh npm run build ``` -------------------------------- ### Make Custom API Call Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example of sending a POST request to a custom API endpoint with a JSON body and custom headers. ```typescript const result = await pb.send('/api/custom-endpoint', { method: 'POST', body: { data: 'value' }, headers: { 'X-Custom': 'header' } }); ``` -------------------------------- ### Initialize Client with Base URL Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/07-configuration.md Configure the base URL for the PocketBase server. Supports production, development, and relative paths in browsers. ```typescript const pb = new Client('https://api.example.com'); ``` ```typescript const pb = new Client('http://127.0.0.1:8090'); ``` ```typescript const pb = new Client('/api'); ``` -------------------------------- ### Initialize Client with Language Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/07-configuration.md Set the Accept-Language header for requests to specify the preferred language for responses. ```typescript const pb = new Client('http://localhost:8090', undefined, 'de-DE'); ``` ```typescript const pb = new Client('http://localhost:8090', undefined, 'fr-FR'); ``` ```typescript const pb = new Client('http://localhost:8090', undefined, 'en-US'); ``` -------------------------------- ### Access Collection Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example of how to retrieve records from a collection using the RecordService. Demonstrates fetching all records and fetching typed records with an interface. ```typescript const pb = new Client('http://127.0.0.1:8090'); // Get all records const records = await pb.collection('posts').getList(1, 20); // Get typed records interface Post { id: string; title: string; content: string; } const typedRecords = await pb.collection('posts').getList(1, 20); ``` -------------------------------- ### Initialize Client with Auth Store Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/07-configuration.md Configure a custom authentication store instance for the client. Supports LocalAuthStore, BaseAuthStore, or a custom store. ```typescript const pb = new Client('http://localhost:8090', new LocalAuthStore()); ``` ```typescript const pb = new Client('http://localhost:8090', new BaseAuthStore()); ``` ```typescript const pb = new Client('http://localhost:8090', customAuthStore); ``` ```typescript const pb = new Client('http://localhost:8090'); ``` -------------------------------- ### Instantiate PocketBase Client Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Create a new instance of the PocketBase Client. Optional parameters include the base URL of the backend, a custom authentication store, and the language code for requests. ```typescript new Client(baseURL?: string, authStore?: BaseAuthStore | null, lang?: string) ``` -------------------------------- ### Initialize AsyncAuthStore with AsyncStorage Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Use AsyncAuthStore to integrate with third-party async storage, commonly needed for React Native applications. Ensure you have '@react-native-async-storage/async-storage' installed. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import PocketBase, { AsyncAuthStore } from 'pocketbase'; const store = new AsyncAuthStore({ save: async (serialized) => AsyncStorage.setItem('pb_auth', serialized), initial: AsyncStorage.getItem('pb_auth'), }); const pb = new PocketBase('http://127.0.0.1:8090', store) ``` -------------------------------- ### Get RecordService Instance Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Obtain a RecordService instance for a specific collection to perform CRUD and authentication operations. Supports generic typing for collection models. ```typescript collection(idOrName: string): RecordService ``` -------------------------------- ### Initialize PocketBase SDK Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Instantiate the PocketBase client with the API endpoint. Custom configurations can be provided for the auth store and language. ```typescript import PocketBase from 'pocketbase'; const pb = new PocketBase('http://127.0.0.1:8090'); // OR with custom configuration const pb = new PocketBase( 'https://api.example.com', // baseURL new LocalAuthStore(), // auth store 'en-US' // language ); ``` -------------------------------- ### Core Client Class Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md The main Client class is the entry point for the SDK. It handles constructor options, request hooks, auto-cancellation, and filter expression building. ```APIDOC ## Client Class ### Description The `Client` class is the primary entry point for interacting with the PocketBase API using the JavaScript SDK. It manages the connection, handles request hooks, and provides configuration for auto-cancellation and filter expressions. ### Constructor - `new Client(baseUrl, options)` - `baseUrl` (string): The base URL of your PocketBase instance. - `options` (object): Optional configuration settings. ### Properties - `options` (object): The configuration options for the client. - `hooks` (object): An object containing request hooks like `beforeSend` and `afterSend`. ### Methods - `autoCancel(enabled)`: Configures auto-cancellation of requests. - `filter(expression)`: Builds a filter expression string. ### Request Hooks - `beforeSend`: A function that is called before each request is sent. - `afterSend`: A function that is called after each request is received. ``` -------------------------------- ### Get Single Record by ID Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/02-record-service.md Retrieve a single record by its unique ID. Use this when you know the specific record you need. It can also expand related data. ```typescript const post = await pb.collection('posts').getOne('record_id', { expand: 'author,comments', }); ``` -------------------------------- ### Listen for Realtime Connection Lifecycle Events Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/07-configuration.md Handle realtime connection events by subscribing to PB_CONNECT for connection establishment and by defining the onDisconnect callback for disconnections. ```typescript // Listen for connection established await pb.realtime.subscribe('PB_CONNECT', () => { console.log('Realtime connected'); }); // Handle disconnection pb.realtime.onDisconnect = (activeSubscriptions) => { if (activeSubscriptions.length > 0) { console.log('Connection lost, still have active subscriptions'); // Handle reconnection logic } else { console.log('All subscriptions closed'); } }; ``` -------------------------------- ### Import AsyncAuthStore Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Import the AsyncAuthStore class from the pocketbase SDK for use with asynchronous storage solutions. ```typescript import { AsyncAuthStore } from 'pocketbase'; ``` -------------------------------- ### Modify Request Headers with beforeSend Hook Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Use the `beforeSend` hook to intercept and modify outgoing fetch requests globally. This example adds a custom header to all requests. ```javascript const pb = new PocketBase('http://127.0.0.1:8090'); pb.beforeSend = function (url, options) { // For list of the possible request options properties check // https://developer.mozilla.org/en-US/docs/Web/API/fetch#options options.headers = Object.assign({}, options.headers, { 'X-Custom-Header': 'example', }); return { url, options }; }; // use the created client as usual... ``` -------------------------------- ### Use Filter with Placeholders Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Example demonstrating how to use the `filter` method to build a query filter with string and date parameters, including escaping special characters in strings. ```typescript const records = await pb.collection('posts').getList(1, 20, { filter: pb.filter('title ~ {:title} && created > {:date}', { title: "test's filter", date: new Date('2024-01-01') }) }); // Results in: title ~ 'test\'s filter' && created > '2024-01-01 00:00:00' ``` -------------------------------- ### Get Private File Access URL Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Generates a URL for accessing a private file. It includes an access token in the URL query parameters to grant temporary access. ```typescript // Get private file access async function getPrivateFileUrl(record: any, filename: string) { // Get access token const token = await pb.files.getToken(); // Build URL with token const url = pb.files.getURL(record, filename); return url + '?token=' + encodeURIComponent(token); } ``` -------------------------------- ### Get Full List of Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/08-crud-service.md Fetches all records in batches. Useful for retrieving all data without manual pagination. Supports custom batch sizes and query options. ```typescript // Get all records in default 1000-record batches const allRecords = await pb.collection('posts').getFullList(); // With options const published = await pb.collection('posts').getFullList({ filter: 'status = "published"', sort: '-created', batch: 500, }); // Legacy syntax with explicit batch const all = await pb.collection('posts').getFullList(500); ``` -------------------------------- ### Import PocketBase Client Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/01-client.md Import the Client class from the pocketbase SDK. Two common import syntaxes are shown. ```typescript import Client from 'pocketbase'; // or import { Client } from 'pocketbase'; ``` -------------------------------- ### Import SQLService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Import the SQLService from the pocketbase SDK. ```typescript import { SQLService } from 'pocketbase'; ``` -------------------------------- ### Accessing SDK Services Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/README.md Illustrates how to access different services provided by the SDK, such as RecordService, CollectionService, and FileService. Each service is accessed as a property of the initialized PocketBase client. ```typescript pb.collection('name') // RecordService - CRUD and auth pb.collections // CollectionService - collection definitions pb.files // FileService - file URLs and tokens pb.realtime // RealtimeService - SSE subscriptions pb.settings // SettingsService - app configuration pb.logs // LogService - application logs pb.health // HealthService - health checks pb.backups // BackupService - database backups pb.crons // CronService - scheduled jobs pb.sql // SQLService - raw SQL queries ``` -------------------------------- ### Retrieve Logs with LogService Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Use LogService to fetch paginated lists of logs, retrieve a single log by its ID, or get statistics about the logs. Options can be provided for pagination and filtering. ```javascript // Returns a paginated logs list. 🔐 pb.logs.getList(page = 1, perPage = 30, options = {}); ``` ```javascript // Returns a single log by its id. 🔐 pb.logs.getOne(id, options = {}); ``` ```javascript // Returns logs statistics. 🔐 pb.logs.getStats(options = {}); ``` -------------------------------- ### Instantiate AsyncAuthStore Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Create a new instance of AsyncAuthStore, providing options for saving and initializing the auth state. This is suitable for environments like React Native. ```typescript new AsyncAuthStore({ save: async (serialized) => { await AsyncStorage.setItem('pb_auth', serialized); }, initial: await AsyncStorage.getItem('pb_auth'), }) ``` -------------------------------- ### Import SettingsService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Import the SettingsService from the pocketbase SDK. ```typescript import { SettingsService } from 'pocketbase'; ``` -------------------------------- ### Get Full Records List Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/02-record-service.md Fetch all records from a collection by making batch requests. Useful for retrieving all data without manual pagination. You can specify a batch size for requests. ```typescript // Get all records with defaults const allRecords = await pb.collection('posts').getFullList(); // With batch size and options const filtered = await pb.collection('posts').getFullList(500, { filter: 'status = "draft"', batch: 100, }); ``` -------------------------------- ### Import BackupService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Import the BackupService class from the PocketBase SDK. ```typescript import { BackupService } from 'pocketbase'; ``` -------------------------------- ### Extend Response Data with afterSend Hook Source: https://github.com/pocketbase/js-sdk/blob/master/README.md The `afterSend` hook allows you to inspect and modify the response data after a fetch request. This example adds an additional field to the parsed response data. ```javascript const pb = new PocketBase('http://127.0.0.1:8090'); pb.afterSend = function (response, data) { // do something with the response state console.log(response.status); return Object.assign(data, { // extend the data... "additionalField": 123, }); }; // use the created client as usual... ``` -------------------------------- ### Manage Backups with BackupService Source: https://github.com/pocketbase/js-sdk/blob/master/README.md Use BackupService to retrieve a list of all backups, create new backups, upload existing backup files, delete backups by name, restore from a backup, and generate download URLs for backups. ```javascript // Returns list with all available backup files. 🔐 pb.backups.getFullList(options = {}); ``` ```javascript // Initializes a new backup. 🔐 pb.backups.create(basename = "", options = {}); ``` ```javascript // Upload an existing app data backup. 🔐 pb.backups.upload({ file: File/Blob }, options = {}); ``` ```javascript // Deletes a single backup by its name. 🔐 pb.backups.delete(key, options = {}); ``` ```javascript // Initializes an app data restore from an existing backup. 🔐 pb.backups.restore(key, options = {}); ``` ```javascript // Builds a download url for a single existing backup using a // superuser file token and the backup file key. 🔐 pb.backups.getDownloadURL(token, key); ``` -------------------------------- ### LogService.getList Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Returns paginated application logs. ```APIDOC ## LogService.getList ### Description Returns paginated logs. ### Method getList ### Parameters #### Path Parameters - **page** (number) - Optional - The page number to retrieve. - **perPage** (number) - Optional - The number of logs per page. - **options** (ListOptions) - Optional - Additional options for filtering and sorting. ### Returns Paginated list of logs. ### Example ```typescript const logs = await pb.logs.getList(1, 50, { sort: '-created', }); ``` ``` -------------------------------- ### Get First List Item by Filter Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/02-record-service.md Find and return the first record that matches a given filter expression. Ideal for scenarios where you expect only one result or need the earliest match. ```typescript const post = await pb.collection('posts').getFirstListItem( 'slug = "my-post"', { expand: 'author' } ); ``` -------------------------------- ### Get Paginated List of Records Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/08-crud-service.md Retrieves a paginated list of records. Ideal for displaying data in tables or lists where only a subset is needed at a time. Returns items along with pagination details. ```typescript const result = await pb.collection('posts').getList(1, 20, { filter: 'status = "published"', sort: '-created', skipTotal: false, }); console.log(result.items); // Page items console.log(result.totalItems); // Total matching console.log(result.totalPages); // Total pages console.log(result.page); // Current page console.log(result.perPage); // Per page ``` -------------------------------- ### Get Current Authenticated User Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Retrieve the currently logged-in user's record from the `record` property of the auth store. Log the user's ID and email if a record exists. ```typescript const user = pb.authStore.record; if (user) { console.log(user.id, user.email); } ``` -------------------------------- ### Get User Avatar URL Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/10-examples.md Retrieves the URL for a user's avatar. It fetches the user record and constructs the file URL, optionally generating a thumbnail. Returns null if the user has no avatar. ```typescript // Get file URL async function getUserAvatarUrl(userId: string) { const user = await pb.collection('users').getOne(userId); if (user.avatar) { const url = pb.files.getURL(user, user.avatar, { thumb: '200x200c', // Thumbnail size }); return url; } return null; } ``` -------------------------------- ### Create New Instance Per Request (SSR/Node.js) Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/07-configuration.md Instantiate a new PocketBase client for each server request to manage authentication state and perform server-side operations. Load auth from cookies and refresh tokens as needed. ```typescript export async function handle({ req, res }) { const pb = new Client('http://127.0.0.1:8090'); // Load auth from cookie pb.authStore.loadFromCookie(req.headers.cookie); try { // Refresh token if (pb.authStore.isValid) { await pb.collection( pb.authStore.record.collectionName ).authRefresh(); } } catch (_) { pb.authStore.clear(); } // Use pb for server-side requests const data = await pb.collection('posts').getList(); // Export cookie res.setHeader('Set-Cookie', pb.authStore.exportToCookie()); return { props: { data } }; } ``` -------------------------------- ### Get Single Record by ID Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/08-crud-service.md Retrieves a single record by its unique ID. Use this when you know the exact ID of the item you need. Supports expanding related data and selecting specific fields. ```typescript const post = await pb.collection('posts').getOne('record_id'); // With expand const post = await pb.collection('posts').getOne('record_id', { expand: 'author,comments', }); // With field selection const post = await pb.collection('posts').getOne('record_id', { fields: 'id,title,created', }); ``` -------------------------------- ### Get Paginated Records List Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/02-record-service.md Retrieve a paginated list of records from a collection. Supports filtering, sorting, and expanding related data. Use when you need to display records in chunks or apply complex queries. ```typescript const result = await pb.collection('posts').getList(1, 20, { filter: 'status = "published"', sort: '-created', expand: 'author', }); console.log(result.items); console.log(result.totalPages); ``` -------------------------------- ### Import FileService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Import the FileService class from the pocketbase SDK. ```typescript import { FileService } from 'pocketbase'; ``` -------------------------------- ### Import RealtimeService Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Import the RealtimeService class from the pocketbase SDK. ```typescript import { RealtimeService } from 'pocketbase'; ``` -------------------------------- ### Auto-Refresh Token on Route Change (SPA) Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/03-auth-store.md Implement automatic token refreshing in a Single Page Application by listening for auth changes. This example checks if the token is expiring soon and attempts to refresh it to ensure a valid session. ```typescript // Automatically refresh token when needed pb.authStore.onChange(async (token, record) => { if (!record) return; // No user // Check if token is expiring soon (within 5 minutes) try { if (pb.authStore.isValid) { // Optional: refresh to ensure fresh token await pb.collection(record.collectionName).authRefresh(); } } catch (e) { pb.authStore.clear(); } }); ``` -------------------------------- ### Get First List Item Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/08-crud-service.md Fetches the first record that matches a given filter. Useful for retrieving a single specific item without needing to fetch a full list. Throws a 404 error if no match is found. ```typescript const post = await pb.collection('posts').getFirstListItem( 'slug = "my-post"' ); // With options const post = await pb.collection('posts').getFirstListItem( 'status = "published"', { expand: 'author' } ); // Safe parameter binding const post = await pb.collection('posts').getFirstListItem( pb.filter('slug = {:slug}', { slug: 'my-post' }) ); ``` -------------------------------- ### Subscribe to Realtime Topics Source: https://github.com/pocketbase/js-sdk/blob/master/_autodocs/04-services.md Subscribe to realtime events. Use 'PB_CONNECT' for connection events or collection-specific topics like 'collection/record_id' for record changes. The callback function receives data for each event. ```typescript await pb.realtime.subscribe('PB_CONNECT', () => { console.log('Realtime connected'); }); ``` ```typescript await pb.realtime.subscribe('posts/record_id', (data) => { console.log('Record changed:', data); }); ```