PocketBase JavaScript SDK

repository·master·Indexed 25 days ago

https://github.com/pocketbase/js-sdk

The official client library for interacting with the PocketBase API in browser and Node.js environments. Version 0.27.0. Features include CRUD operations via RecordService, real-time subscriptions, authentication handlers (Password, OTP, OAuth2), batch requests, and a flexible authStore system for session management.

Tokens
8.2K
Snippets
14
Records
65
Agent score
83%

What's inside pocketbase-js-sdk

  1. Initialize and use the PocketBase client

    master

    To interact with your PocketBase instance, import the PocketBase class, instantiate it with your server URL, and use the collection API to perform operations like authentication and data retrieval.

    Import Styles

    ES Modules (Default):

    import PocketBase from 'pocketbase'

    CommonJS:

    const PocketBase = require('pocketbase/cjs')
    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');
    
    // list and filter "example" collection records
    const result = await pb.collection('example').getList(1, 20, {
        filter: 'status = true && created > "2022-08-01 10:00:00"'
    });
  2. Install the PocketBase JavaScript SDK

    master

    You can install the PocketBase SDK for Node.js environments using npm, or include it directly in the browser via script tags.

    Node.js (via npm)

    Install using:

    npm install pocketbase --save

    Browser (via script tag)

    For traditional script loading:

    <script src="/path/to/dist/pocketbase.umd.js"></script>
    <script type="text/javascript">
        const pb = new PocketBase("https://example.com")
        ...
    </script>

    Or using ES modules:

    <script type="module">
        import PocketBase from '/path/to/dist/pocketbase.es.mjs'
    
        const pb = new PocketBase("https://example.com")
        ...
    </script>
    npm install pocketbase --save
  3. Upload files using FormData or plain objects

    master

    PocketBase supports file uploads via multipart/form-data. You can upload files by providing either a standard FormData instance or a plain object containing File or Blob properties (the SDK will convert plain objects to FormData automatically).

    // Using plain object
    const data = {
      'title':    'lorem ipsum...',
      'document': new File(...),
    };
    await pb.collection('example').create(data);
    
    // Using FormData
    const data = new FormData();
    data.set('title', 'lorem ipsum...')
    data.set('document', new File(...))
    await pb.collection('example').create(data);
  4. Initialize a new PocketBase client

    master

    To interact with your PocketBase backend, create a new instance of the PocketBase class. You can specify a baseURL (defaults to /) and an authStore (e.g., LocalAuthStore for browser environments).

    Each instance method returns the PocketBase instance, allowing for method chaining.

    const pb = new PocketBase(baseURL = '/', authStore = LocalAuthStore);
  5. Configure Node.js environment for PocketBase

    master

    Because Node.js environments may lack certain web APIs used by the SDK, you may need to provide polyfills:

    Fetch Polyfill (Node < 17)

    If you are using a Node version older than 17, you must load a fetch() polyfill (e.g., cross-fetch):

    import 'cross-fetch/polyfill';

    EventSource Polyfill (Realtime Subscriptions)

    Node.js does not have a native EventSource implementation. To use realtime subscriptions, you must load an EventSource polyfill and assign it to global.EventSource.

    For Node.js servers:

    import { EventSource } from "eventsource";
    global.EventSource = EventSource;

    For React Native:

    import EventSource from "react-native-sse";
    global.EventSource = EventSource;
    // 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;
  6. Initialize the PocketBase Client

    master

    Create a new instance of the Client class to interact with your PocketBase backend. You can specify the baseURL, a custom authStore, and a preferred language code.

    By default, if no authStore is provided, the client uses LocalAuthStore (in browser environments) or a memory-based BaseAuthStore (in Deno).

  7. Run raw SQL queries with SQLService

    master

    If you have the necessary permissions, you can execute raw SQL queries directly against the database using the SQLService.

    // Runs the specified raw SQL query.
    🔐 pb.sql.run(query, options = {});
  8. Execute multiple requests in a single BatchService

    master

    Use BatchService to group multiple create, update, delete, or upsert requests into a single network request to improve efficiency.

    // create a new batch instance
    const batch = pb.createBatch();
    
    // register create/update/delete/upsert requests to the created batch
    batch.collection('example1').create({ ... });
    batch.collection('example2').update('RECORD_ID', { ... });
    batch.collection('example3').delete('RECORD_ID');
    batch.collection('example4').upsert({ ... });
    
    // send the batch request
    const result = await batch.send();
  9. Subscribe to real-time changes with RecordService

    master

    You can listen to real-time changes for a specific collection or a specific record using the subscribe and unsubscribe methods on the RecordService.

    • subscribe(topic, callback, options): Subscribe to a topic (use "*" for the whole collection or a recordId for a specific record). Returns an UnsubscribeFunc to remove that specific subscription.
    • unsubscribe([topic]): Removes all subscriptions for the specified topic. If no topic is provided, it removes all collection subscriptions.
  10. Handle errors with ClientResponseError

    master

    All services return Promise-based responses. Errors are normalized into a ClientResponseError object containing:

    • url: requested url
    • status: response status code
    • response: the API JSON error response
    • isAbort: boolean indicating if it was a cancellation error
    • originalError: the original non-normalized error
    try {
      const result = await pb.collection('example').getList(1, 50);
      console.log('Result:', result);
    } catch (error) {
      // error is a ClientResponseError
      console.log('Error:', error);
    }
  11. Manage real-time connections with RealtimeService

    master

    The RealtimeService is used for custom real-time actions outside of standard record subscriptions.

    • pb.realtime.subscribe(topic, callback, options): Initialize connection and register a listener. You can subscribe to PB_CONNECT to listen for connection/reconnection events.
    • pb.realtime.unsubscribe(topic?): Unsubscribe from a topic.
    • pb.realtime.unsubscribeByPrefix(topicPrefix): Unsubscribe using a prefix.
    • pb.realtime.unsubscribeByTopicAndListener(topic, callback): Unsubscribe a specific listener.
    • pb.realtime.isConnected: Boolean getter checking connection status.
    • pb.realtime.onDisconnect: An optional hook invoked when the client disconnects (e.g., server error or manual close).
  12. Specify TypeScript definitions for collections

    master

    You can provide type safety for your PocketBase collections using generics or global type assertions.

    Option 1: Generics Pass the interface to the collection method.

    Option 2: Global Type Assertion Extend the PocketBase type to map specific collection IDs to specific interfaces, allowing for cleaner code without repeating generics.