PocketBase JavaScript SDK
The PocketBase JavaScript SDK is the official client library for interacting with the PocketBase API, supporting both browser and Node.js environments. It provides comprehensive functionalities for data management, user authentication (including password and OAuth2 flows), and real-time subscriptions. The current stable version is 0.26.8, with the project maintaining a frequent release cadence to deliver bug fixes, performance improvements, and feature parity with the core PocketBase server. Key differentiators include its seamless integration with the PocketBase ecosystem, robust type definitions, flexible authentication store options (e.g., `LocalAuthStore` for web, `AsyncAuthStore` for React Native), and a crucial `pb.filter()` helper for securely binding filter parameters to prevent string injection attacks when handling untrusted server-side input.
Common errors
-
ReferenceError: fetch is not defined
cause Running PocketBase SDK in Node.js < 17 without a `fetch` polyfill.fixInstall `cross-fetch` (`npm install cross-fetch`) and add `import 'cross-fetch/polyfill';` to your application entry point. -
ReferenceError: EventSource is not defined
cause Attempting to use PocketBase real-time subscriptions in Node.js without an `EventSource` polyfill.fixInstall `eventsource` (`npm install eventsource`) and add `import { EventSource } from 'eventsource'; global.EventSource = EventSource;` (or `react-native-sse` for React Native) to your application entry point. -
const PocketBase = require('pocketbase'); // Error: `PocketBase is not a constructor` or similarcause Incorrect CommonJS import path for `pocketbase` package.fixFor CommonJS, use `const PocketBase = require('pocketbase/cjs');`. -
TypeError: Failed to parse JSON body from response
cause This error or `DOMException.SyntaxError` can occur in Safari (pre v0.26.5) when an aborted request causes `response.json()` to fail.fixUpdate the `pocketbase` SDK to version `0.26.5` or newer, which includes a fix for better abort error detection in Safari.
Warnings
- breaking The default batch size for `pb.collection('collectionName').getFullList()` was increased from 500 to 1000 for consistency with the Dart SDK and v0.23+ API limits. This may affect memory usage or pagination logic in applications that relied on the previous default.
- gotcha When using `pb.files.getURL()`, passing `null` or `undefined` as query parameter values will now cause those parameters to be skipped from the generated URL, matching the behavior of fetch methods.
- breaking When submitting an object with `Blob` or `File` fields, `undefined` properties are now ignored during `FormData` conversion, aligning with how `JSON.stringify` works. This change ensures consistency but might alter submitted data if `undefined` values were implicitly relied upon.
- gotcha Node.js versions older than 17 require a `fetch()` API polyfill (e.g., `cross-fetch`) to function correctly, as `fetch` is not natively available in those versions.
- gotcha Node.js environments require an `EventSource` polyfill (e.g., `eventsource` for server, `react-native-sse` for React Native) to use PocketBase's real-time subscriptions, as `EventSource` is not a native global object.
- breaking The `authWithOAuth2()` `Promise` was not properly rejecting when manually cancelled via `pb.cancelRequest()`, especially when waiting for a real-time subscription. This behavior is now corrected.
- gotcha When accepting untrusted user input as `filter` string arguments in Node.js or Deno server-side list queries, it is strongly recommended to use `pb.filter(expr, params)` to prevent string injection attacks. This helper automatically escapes placeholder parameters.
Install
-
npm install pocketbase -
yarn add pocketbase -
pnpm add pocketbase
Imports
- PocketBase
import { PocketBase } from 'pocketbase';import PocketBase from 'pocketbase';
- PocketBase
const PocketBase = require('pocketbase');const PocketBase = require('pocketbase/cjs'); - EventSource
new EventSource(...)
import { EventSource } from 'eventsource'; global.EventSource = EventSource;
Quickstart
import PocketBase from 'pocketbase';
import 'cross-fetch/polyfill'; // Only for Node < 17
const pb = new PocketBase('http://127.0.0.1:8090');
async function initializeApp() {
try {
// Example: Authenticate as an auth collection record
const userData = await pb.collection('users').authWithPassword('test@example.com', '123456');
console.log('User authenticated:', userData.record.email);
// Example: List and filter 'posts' collection records
const result = await pb.collection('posts').getList(1, 20, {
filter: pb.filter('status = true && created > {:date}', { date: new Date('2023-01-01T00:00:00Z') }),
sort: '-created'
});
console.log('Posts found:', result.items.length);
// Example: Create a new record
const newPost = await pb.collection('posts').create({
title: 'My new post',
content: 'This is some content.',
status: true,
author: userData.record.id
});
console.log('New post created:', newPost.id);
} catch (error) {
console.error('An error occurred:', error);
if (error.isAbort) {
console.error('Request was aborted.');
}
}
}
initializeApp();