Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

pocketbase

pocketbase79.5kMIT0.26.0TypeScript support: included

PocketBase JavaScript SDK

pocketbase, pocketbase-js, js-sdk, javascript-sdk, pocketbase-sdk

readme

PocketBase JavaScript SDK

Official JavaScript SDK (browser and node) for interacting with the PocketBase API.

Installation

Browser (manually via script tag)

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

OR if you are using ES modules:

<script type="module">
    import PocketBase from '/path/to/dist/pocketbase.es.mjs'

    const pb = new PocketBase("https://example.com")
    ...
</script>

Node.js (via npm)

npm install pocketbase --save
// Using ES modules (default)
import PocketBase from 'pocketbase'

// OR if you are using CommonJS modules
const PocketBase = require('pocketbase/cjs')

🔧 For Node < 17 you'll need to load a fetch() polyfill. I recommend lquixada/cross-fetch:

// npm install cross-fetch --save
import 'cross-fetch/polyfill';

🔧 Node doesn't have native EventSource implementation, so in order to use the realtime subscriptions you'll need to load a EventSource polyfill.

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

Usage

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"'
});

// and much more...

More detailed API docs and copy-paste examples could be found in the API documentation for each service.

Caveats

Binding filter parameters

The SDK comes with a helper pb.filter(expr, params) method to generate a filter string with placeholder parameters ({:paramName}) populated from an object.

This method is also recommended when using the SDK in Node/Deno/Bun server-side list queries and accepting untrusted user input as filter string arguments, because it will take care to properly escape the generated string expression, avoiding eventual string injection attacks (on the client-side this is not much of an issue).

const records = await pb.collection("example").getList(1, 20, {
  // the same as: "title ~ 'te\\'st' && (totalA = 123 || totalB = 123)"
  filter: pb.filter("title ~ {:title} && (totalA = {:num} || totalB = {:num})", { title: "te'st", num: 123 })
})

The supported placeholder parameter values are:

  • string (single quotes are autoescaped)
  • number
  • boolean
  • Date object (will be stringified into the format expected by PocketBase)
  • null
  • everything else is converted to a string using JSON.stringify()

File upload

PocketBase Web API supports file upload via multipart/form-data requests, which means that to upload a file it is enough to provide either a FormData instance OR plain object with File/Blob prop values.

  • Using plain object as body (this is the same as above and it will be converted to FormData behind the scenes):

      const data = {
        'title':    'lorem ipsum...',
        'document': new File(...),
      };
    
      await pb.collection('example').create(data);
  • Using FormData as body:

      // the standard way to create multipart/form-data body
      const data = new FormData();
      data.set('title', 'lorem ipsum...')
      data.set('document', new File(...))
    
      await pb.collection('example').create(data);

Error handling

All services return a standard Promise-based response, so the error handling is straightforward:

pb.collection('example').getList(1, 50).then((result) => {
  // success...
  console.log('Result:', result);
}).catch((error) => {
  // error...
  console.log('Error:', error);
});

// OR if you are using the async/await syntax:
try {
  const result = await pb.collection('example').getList(1, 50);
  console.log('Result:', result);
} catch (error) {
  console.log('Error:', error);
}

The response error is normalized and always returned as ClientResponseError object with the following public fields that you could use:

ClientResponseError {
    url:           string,     // requested url
    status:        number,     // response status code
    response:      { ... },    // the API JSON error response
    isAbort:       boolean,    // is abort/cancellation error
    originalError: Error|null, // the original non-normalized error
}

Auth store

The SDK keeps track of the authenticated token and auth model for you via the pb.authStore instance.

LocalAuthStore (default)

The default LocalAuthStore uses the browser's LocalStorage if available, otherwise - will fallback to runtime/memory (aka. on page refresh or service restart you'll have to authenticate again).

Conveniently, the default store also takes care to automatically sync the auth store state between multiple tabs.

NB! Deno also supports LocalStorage but keep in mind that, unlike in browsers where the client is the only user, by default Deno LocalStorage will be shared by all clients making requests to your server!

AsyncAuthStore

The SDK comes also with a helper AsyncAuthStore that you can use to integrate with any 3rd party async storage implementation (usually this is needed when working with React Native):

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)
Custom auth store

In some situations it could be easier to create your own custom auth store. For this you can extend BaseAuthStore and pass the new custom instance as constructor argument to the client:

import PocketBase, { BaseAuthStore } from 'pocketbase';

class CustomAuthStore extends BaseAuthStore {
    save(token, model) {
        super.save(token, model);

        // your custom business logic...
    }
}

const pb = new PocketBase('http://127.0.0.1:8090', new CustomAuthStore());
Common auth store fields and methods

The default pb.authStore extends BaseAuthStore and has the following public members that you can use:

BaseAuthStore {
    // base fields
    record:       RecordModel|null // the authenticated auth record
    token:        string  // the authenticated token
    isValid:      boolean // checks if the store has existing and unexpired token
    isSuperuser:  boolean // checks if the store state is for superuser

    // main methods
    clear()             // "logout" the authenticated record
    save(token, record) // update the store with the new auth data
    onChange(callback, fireImmediately = false) // register a callback that will be called on store change

    // cookie parse and serialize helpers
    loadFromCookie(cookieHeader, key = 'pb_auth')
    exportToCookie(options = {}, key = 'pb_auth')
}

To "logout" the authenticated record you can call pb.authStore.clear().

To "listen" for changes in the auth store, you can register a new listener via pb.authStore.onChange, eg:

// triggered everytime on store change
const removeListener1 = pb.authStore.onChange((token, record) => {
    console.log('New store data 1:', token, record)
});

// triggered once right after registration and everytime on store change
const removeListener2 = pb.authStore.onChange((token, record) => {
    console.log('New store data 2:', token, record)
}, true);

// (optional) removes the attached listeners
removeListener1();
removeListener2();

Auto cancellation

The SDK client will auto cancel duplicated pending requests for you. For example, if you have the following 3 duplicated endpoint calls, only the last one will be executed, while the first 2 will be cancelled with ClientResponseError error:

pb.collection('example').getList(1, 20) // cancelled
pb.collection('example').getList(2, 20) // cancelled
pb.collection('example').getList(3, 20) // executed

To change this behavior per request basis, you can adjust the requestKey: null|string special query parameter. Set it to null to unset the default request identifier and to disable auto cancellation for the specific request. Or set it to a unique string that will be used as request identifier and based on which pending requests will be matched (default to HTTP_METHOD + path, eg. "GET /api/users")

Example:

pb.collection('example').getList(1, 20);                        // cancelled
pb.collection('example').getList(1, 20);                        // executed
pb.collection('example').getList(1, 20, { requestKey: "test" }) // cancelled
pb.collection('example').getList(1, 20, { requestKey: "test" }) // executed
pb.collection('example').getList(1, 20, { requestKey: null })   // executed
pb.collection('example').getList(1, 20, { requestKey: null })   // executed

// globally disable auto cancellation
pb.autoCancellation(false);

pb.collection('example').getList(1, 20); // executed
pb.collection('example').getList(1, 20); // executed
pb.collection('example').getList(1, 20); // executed

If you want to globally disable the auto cancellation behavior, you could set pb.autoCancellation(false).

To manually cancel pending requests, you could use pb.cancelAllRequests() or pb.cancelRequest(requestKey).

Specify TypeScript definitions

You could specify custom TypeScript definitions for your Record models using generics:

interface Task {
  // type the collection fields you want to use...
  id:   string;
  name: string;
}

pb.collection('tasks').getList<Task>(1, 20) // -> results in Promise<ListResult<Task>>
pb.collection('tasks').getOne<Task>("RECORD_ID")  // -> results in Promise<Task>

Alternatively, if you don't want to type the generic argument every time you can define a global PocketBase type using type assertion:

interface Task {
  id:   string;
  name: string;
}

interface Post {
  id:     string;
  title:  string;
  active: boolean;
}

interface TypedPocketBase extends PocketBase {
  collection(idOrName: string): RecordService // default fallback for any other collection
  collection(idOrName: 'tasks'): RecordService<Task>
  collection(idOrName: 'posts'): RecordService<Post>
}

...

const pb = new PocketBase("http://127.0.0.1:8090") as TypedPocketBase;

pb.collection('tasks').getOne("RECORD_ID") // -> results in Promise<Task>
pb.collection('posts').getOne("RECORD_ID") // -> results in Promise<Post>

Custom request options

All API services accept an optional options argument (usually the last one and of type SendOptions), that can be used to provide:

  • custom headers for a single request
  • custom fetch options
  • or even your own fetch implementation

For example:

pb.collection('example').getList(1, 20, {
    expand:          'someRel',
    otherQueryParam: '123',

    // custom headers
    headers: {
        'X-Custom-Header': 'example',
    },

    // custom fetch options
    keepalive: false,
    cache:     'no-store',

    // or custom fetch implementation
    fetch: async (url, config) => { ... },
})

Note that for backward compatability and to minimize the verbosity, any "unknown" top-level field will be treated as query parameter.

Send hooks

Sometimes you may want to modify the request data globally or to customize the response.

To accomplish this, the SDK provides 2 function hooks:

  • beforeSend - triggered right before sending the fetch request, allowing you to inspect/modify the request config.

      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...
  • afterSend - triggered after successfully sending the fetch request, allowing you to inspect/modify the response object and its parsed data.

      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...

SSR integration

Unfortunately, there is no "one size fits all" solution because each framework handle SSR differently (and even in a single framework there is more than one way of doing things).

But in general, the idea is to use a cookie based flow:

  1. Create a new PocketBase instance for each server-side request
  2. "Load/Feed" your pb.authStore with data from the request cookie
  3. Perform your application server-side actions
  4. Before returning the response to the client, update the cookie with the latest pb.authStore state

All BaseAuthStore instances have 2 helper methods that should make working with cookies a little bit easier:

// update the store with the parsed data from the cookie string
pb.authStore.loadFromCookie('pb_auth=...');

// exports the store data as cookie, with option to extend the default SameSite, Secure, HttpOnly, Path and Expires attributes
pb.authStore.exportToCookie({ httpOnly: false }); // Output: 'pb_auth=...'

Below you could find several examples:

<summary>SvelteKit</summary>

One way to integrate with SvelteKit SSR could be to create the PocketBase client in a hook handle and pass it to the other server-side actions using the event.locals.

// 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;
}

And then, in some of your server-side actions, you could directly access the previously created event.locals.pb instance:

// 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...');
}

For proper locals.pb type detection, you can also add PocketBase in your your global types definition:

// src/app.d.ts
import PocketBase from 'pocketbase';

declare global {
    declare namespace App {
        interface Locals {
            pb: PocketBase
        }
    }
}
<summary>Astro</summary>

To integrate with Astro SSR, you could create the PocketBase client in the Middleware and pass it to the Astro components using the Astro.locals.

// src/middleware/index.ts
import PocketBase from 'pocketbase';

import { defineMiddleware } from 'astro/middleware';

export const onRequest = defineMiddleware(async ({ locals, request }: any, next: () => any) => {
    locals.pb = new PocketBase('http://127.0.0.1:8090');

    // load the store data from the request cookie string
    locals.pb.authStore.loadFromCookie(request.headers.get('cookie') || '');

    try {
        // get an up-to-date auth store state by verifying and refreshing the loaded auth record (if any)
        locals.pb.authStore.isValid && await locals.pb.collection('users').authRefresh();
    } catch (_) {
        // clear the auth store on failed refresh
        locals.pb.authStore.clear();
    }

    const response = await next();

    // send back the default 'pb_auth' cookie to the client with the latest store state
    response.headers.append('set-cookie', locals.pb.authStore.exportToCookie());

    return response;
});

And then, in your Astro file's component script, you could directly access the previously created locals.pb instance:

// src/pages/index.astro
---
const locals = Astro.locals;

const userAuth = async () => {
    const { token, record } = await locals.pb.collection('users').authWithPassword('test@example.com', '123456');

    return new Response('Success...');
};
---

Although middleware functionality is available in both SSG and SSR projects, you would likely want to handle any sensitive data on the server side. Update your output configuration to 'server':

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
    output: 'server'
});
<summary>Nuxt 3</summary>

One way to integrate with Nuxt 3 SSR could be to create the PocketBase client in a nuxt plugin and provide it as a helper to the nuxtApp instance:

// plugins/pocketbase.js
import PocketBase from 'pocketbase';

export default defineNuxtPlugin(async () => {
  const pb = new PocketBase('http://127.0.0.1:8090');

  const cookie = useCookie('pb_auth', {
    path:     '/',
    secure:   true,
    sameSite: 'strict',
    httpOnly: false, // change to "true" if you want only server-side access
    maxAge:   604800,
  })

  // load the store data from the cookie value
  pb.authStore.save(cookie.value?.token, cookie.value?.record);

  // send back the default 'pb_auth' cookie to the client with the latest store state
  pb.authStore.onChange(() => {
    cookie.value = {
      token: pb.authStore.token,
      record: pb.authStore.record,
    };
  });

  try {
      // get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any)
      pb.authStore.isValid && await pb.collection('users').authRefresh();
  } catch (_) {
      // clear the auth store on failed refresh
      pb.authStore.clear();
  }

  return {
    provide: { pb }
  }
});

And then in your component you could access it like this:

<template>
  <div>
    Show: {{ data }}
  </div>
</template>

<script setup>
  const { data } = await useAsyncData(async (nuxtApp) => {
    // fetch and return all "example" records...
    const records = await nuxtApp.$pb.collection('example').getFullList();

    return structuredClone(records);
  })
</script>
<summary>Nuxt 2</summary>

One way to integrate with Nuxt 2 SSR could be to create the PocketBase client in a nuxt plugin and provide it as a helper to the $root context:

// plugins/pocketbase.js
import PocketBase from  'pocketbase';

export default async (ctx, inject) => {
  const pb = new PocketBase('http://127.0.0.1:8090');

  // load the store data from the request cookie string
  pb.authStore.loadFromCookie(ctx.req?.headers?.cookie || '');

  // send back the default 'pb_auth' cookie to the client with the latest store state
  pb.authStore.onChange(() => {
    ctx.res?.setHeader('set-cookie', pb.authStore.exportToCookie());
  });

  try {
      // get an up-to-date auth store state by verifying and refreshing the loaded auth record (if any)
      pb.authStore.isValid && await pb.collection('users').authRefresh();
  } catch (_) {
      // clear the auth store on failed refresh
      pb.authStore.clear();
  }

  inject('pocketbase', pb);
};

And then in your component you could access it like this:

<template>
  <div>
    Show: {{ items }}
  </div>
</template>

<script>
  export default {
    async asyncData({ $pocketbase }) {
      // fetch and return all "example" records...
      const items = await $pocketbase.collection('example').getFullList();

      return { items }
    }
  }
</script>
<summary>Next.js</summary>

Next.js doesn't seem to have a central place where you can read/modify the server request and response. There is support for middlewares, but they are very limited and, at the time of writing, you can't pass data from a middleware to the getServerSideProps functions (https://github.com/vercel/next.js/discussions/31792).

One way to integrate with Next.js SSR could be to create a custom PocketBase instance in each of your getServerSideProps:

import PocketBase from 'pocketbase';

// you can place this helper in a separate file so that it can be reused
async function initPocketBase(req, res) {
  const pb = new PocketBase('http://127.0.0.1:8090');

  // load the store data from the request cookie string
  pb.authStore.loadFromCookie(req?.headers?.cookie || '');

  // send back the default 'pb_auth' cookie to the client with the latest store state
  pb.authStore.onChange(() => {
    res?.setHeader('set-cookie', pb.authStore.exportToCookie());
  });

  try {
      // get an up-to-date auth store state by verifying and refreshing the loaded auth record (if any)
      pb.authStore.isValid && await pb.collection('users').authRefresh();
  } catch (_) {
      // clear the auth store on failed refresh
      pb.authStore.clear();
  }

  return pb
}

export async function getServerSideProps({ req, res }) {
  const pb = await initPocketBase(req, res)

  // fetch example records...
  const result = await pb.collection('example').getList(1, 30);

  return {
    props: {
      // ...
    },
  }
}

export default function Home() {
  return (
    <div>Hello world!</div>
  )
}

Security

The most common frontend related vulnerability is XSS (and CSRF when dealing with cookies). Fortunately, modern browsers can detect and mitigate most of this type of attacks if Content Security Policy (CSP) is provided.

To prevent a malicious user or 3rd party script to steal your PocketBase auth token, it is recommended to configure a basic CSP for your application (either as meta tag or HTTP header).

This is out of the scope of the SDK, but you could find more resources about CSP at:

Depending on how and where you use the JS SDK, it is also recommended to use the helper pb.filter(expr, params) when constructing filter strings with untrusted user input to avoid eventual string injection attacks (see Binding filter parameters).

Definitions

Creating new client instance

const pb = new PocketBase(baseURL = '/', authStore = LocalAuthStore);

Instance methods

Each instance method returns the PocketBase instance allowing chaining.

Method Description
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.

Services

Each service call returns a Promise object with the API response.

RecordService
Crud handlers
// Returns a paginated records list.
🔓 pb.collection(collectionIdOrName).getList(page = 1, perPage = 30, options = {});

// Returns a list with all records batch fetched at once
// (by default 200 items per request; to change it set the `batch` param).
🔓 pb.collection(collectionIdOrName).getFullList(options = {});

// Returns the first found record matching the specified filter.
🔓 pb.collection(collectionIdOrName).getFirstListItem(filter, options = {});

// Returns a single record by its id.
🔓 pb.collection(collectionIdOrName).getOne(recordId, options = {});

// Creates (aka. register) a new record.
🔓 pb.collection(collectionIdOrName).create(bodyParams = {}, options = {});

// Updates an existing record by its id.
🔓 pb.collection(collectionIdOrName).update(recordId, bodyParams = {}, options = {});

// Deletes a single record by its id.
🔓 pb.collection(collectionIdOrName).delete(recordId, options = {});
Realtime handlers
// Subscribe to realtime changes to the specified topic ("*" or recordId).
//
// It is safe to subscribe multiple times to the same topic.
//
// You can use the returned UnsubscribeFunc to remove a single registered subscription.
// If you want to remove all subscriptions related to the topic use unsubscribe(topic).
🔓 pb.collection(collectionIdOrName).subscribe(topic, callback, options = {});

// Unsubscribe from all registered subscriptions to the specified topic ("*" or recordId).
// If topic is not set, then it will remove all registered collection subscriptions.
🔓 pb.collection(collectionIdOrName).unsubscribe([topic]);
Auth handlers

Available only for "auth" type collections.

// Returns all available application auth methods.
🔓 pb.collection(collectionIdOrName).listAuthMethods(options = {});

// Authenticates a record with their username/email and password.
🔓 pb.collection(collectionIdOrName).authWithPassword(usernameOrEmail, password, options = {});

// Authenticates a record with an OTP.
🔓 pb.collection(collectionIdOrName).authWithOTP(otpId, password, options = {});

// Authenticates a record with OAuth2 provider without custom redirects, deeplinks or even page reload.
🔓 pb.collection(collectionIdOrName).authWithOAuth2(authConfig);

// Authenticates a record with OAuth2 code.
🔓 pb.collection(collectionIdOrName).authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData = {}, options = {});

// Refreshes the current authenticated record and auth token.
🔐 pb.collection(collectionIdOrName).authRefresh(options = {});

// Sends a record OTP email request.
🔓 pb.collection(collectionIdOrName).requestOTP(email, options = {});

// Sends a record password reset email.
🔓 pb.collection(collectionIdOrName).requestPasswordReset(email, options = {});

// Confirms a record password reset request.
🔓 pb.collection(collectionIdOrName).confirmPasswordReset(resetToken, newPassword, newPasswordConfirm, options = {});

// Sends a record verification email request.
🔓 pb.collection(collectionIdOrName).requestVerification(email, options = {});

// Confirms a record email verification request.
🔓 pb.collection(collectionIdOrName).confirmVerification(verificationToken, options = {});

// Sends a record email change request to the provider email.
🔐 pb.collection(collectionIdOrName).requestEmailChange(newEmail, options = {});

// Confirms record new email address.
🔓 pb.collection(collectionIdOrName).confirmEmailChange(emailChangeToken, userPassword, options = {});

// Lists all linked external auth providers for the specified record.
🔐 pb.collection(collectionIdOrName).listExternalAuths(recordId, options = {});

// Unlinks a single external auth provider relation from the specified record.
🔐 pb.collection(collectionIdOrName).unlinkExternalAuth(recordId, provider, options = {});

// Impersonate authenticates with the specified recordId and returns a new client with the received auth token in a memory store.
🔐 pb.collection(collectionIdOrName).impersonate(recordId, duration, options = {});

BatchService

// 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()

FileService
// Builds and returns an absolute record file url for the provided filename.
🔓 pb.files.getURL(record, filename, options = {});

// Requests a new private file access token for the current authenticated record.
🔐 pb.files.getToken(options = {});

CollectionService
// Returns a paginated collections list.
🔐 pb.collections.getList(page = 1, perPage = 30, options = {});

// Returns a list with all collections batch fetched at once
// (by default 200 items per request; to change it set the `batch` query param).
🔐 pb.collections.getFullList(options = {});

// Returns the first found collection matching the specified filter.
🔐 pb.collections.getFirstListItem(filter, options = {});

// Returns a single collection by its id or name.
🔐 pb.collections.getOne(idOrName, options = {});

// Creates (aka. register) a new collection.
🔐 pb.collections.create(bodyParams = {}, options = {});

// Updates an existing collection by its id or name.
🔐 pb.collections.update(idOrName, bodyParams = {}, options = {});

// Deletes a single collection by its id or name.
🔐 pb.collections.delete(idOrName, options = {});

// Deletes all records associated with the specified collection.
🔐 pb.collections.truncate(idOrName, options = {});

// Imports the provided collections.
🔐 pb.collections.import(collections, deleteMissing = false, options = {});

// Returns type indexed map with scaffolded collection models populated with their default field values.
🔐 pb.collections.getScaffolds(options = {});

LogService
// Returns a paginated logs list.
🔐 pb.logs.getList(page = 1, perPage = 30, options = {});

// Returns a single log by its id.
🔐 pb.logs.getOne(id, options = {});

// Returns logs statistics.
🔐 pb.logs.getStats(options = {});

SettingsService
// Returns a map with all available app settings.
🔐 pb.settings.getAll(options = {});

// Bulk updates app settings.
🔐 pb.settings.update(bodyParams = {}, options = {});

// Performs a S3 storage connection test.
🔐 pb.settings.testS3(filesystem = "storage", options = {});

// Sends a test email (verification, password-reset, email-change).
🔐 pb.settings.testEmail(collectionIdOrName, toEmail, template, options = {});

// Generates a new Apple OAuth2 client secret.
🔐 pb.settings.generateAppleClientSecret(clientId, teamId, keyId, privateKey, duration, options = {});

RealtimeService

This service is usually used with custom realtime actions. For records realtime subscriptions you can use the subscribe/unsubscribe methods available in the pb.collection() RecordService.

// Initialize the realtime connection (if not already) and register the subscription listener.
//
// You can subscribe to the `PB_CONNECT` event if you want to listen to the realtime connection connect/reconnect events.
🔓 pb.realtime.subscribe(topic, callback, options = {});

// Unsubscribe from all subscription listeners with the specified topic.
🔓 pb.realtime.unsubscribe(topic?);

// Unsubscribe from all subscription listeners starting with the specified topic prefix.
🔓 pb.realtime.unsubscribeByPrefix(topicPrefix);

// Unsubscribe from all subscriptions matching the specified topic and listener function.
🔓 pb.realtime.unsubscribeByTopicAndListener(topic, callback);

// Getter that checks whether the realtime connection has been established.
pb.realtime.isConnected

// An optional hook that is invoked when the realtime client disconnects
// either when unsubscribing from all subscriptions or when the connection
// was interrupted or closed by the server.
//
// Note that the realtime client autoreconnect on its own and this hook is
// useful only for the cases where you want to apply a special behavior on
// server error or after closing the realtime connection.
pb.realtime.onDisconnect = function(activeSubscriptions)

BackupService
// Returns list with all available backup files.
🔐 pb.backups.getFullList(options = {});

// Initializes a new backup.
🔐 pb.backups.create(basename = "", options = {});

// Upload an existing app data backup.
🔐 pb.backups.upload({ file: File/Blob }, options = {});

// Deletes a single backup by its name.
🔐 pb.backups.delete(key, options = {});

// Initializes an app data restore from an existing backup.
🔐 pb.backups.restore(key, options = {});

// Builds a download url for a single existing backup using a
// superuser file token and the backup file key.
🔐 pb.backups.getDownloadURL(token, key);
CronService
// Returns list with all available cron jobs.
🔐 pb.crons.getFullList(options = {});

// Runs the specified cron job.
🔐 pb.crons.run(jobId, options = {});

HealthService
// Checks the health status of the api.
🔓 pb.health.check(options = {});

Development

# run unit tests
npm test

# run prettier
npm run format

# build and minify for production
npm run build

changelog

0.26.0

  • Ignore undefined properties when submitting an object that has Blob/File fields (which is under the hood converted to FormData) for consistency with how JSON.stringify works (see pocketbase#6731).

0.25.2

  • Removed unnecessary checks in serializeQueryParams and added automated tests.

0.25.1

  • Ignore query parameters with undefined value (#330).

0.25.0

  • Added pb.crons service to interact with the cron Web APIs.

0.24.0

  • Added support for assigning FormData as body to individual batch requests (pocketbase#6145).

0.23.0

  • Added optional pb.realtime.onDisconnect hook function. Note that the realtime client autoreconnect on its own and this hook is useful only for the cases where you want to apply a special behavior on server error or after closing the realtime connection.

0.22.1

  • Fixed old pb.authStore.isAdmin/pb.authStore.isAuthRecord and marked them as deprecated in favour of pb.authStore.isSuperuser (#323). Note that with PocketBase v0.23.0 superusers are converted to a system auth collection so you can always simply check the value of pb.authStore.record?.collectionName.

0.22.0

⚠️ This release introduces some breaking changes and works only with PocketBase v0.23.0+.

  • Added support for sending batch/transactional create/updated/delete/upsert requests with the new batch Web APIs.

      const batch = pb.createBatch();
    
      batch.collection("example1").create({ ... });
      batch.collection("example2").update("RECORD_ID", { ... });
      batch.collection("example3").delete("RECORD_ID");
      batch.collection("example4").upsert({ ... });
    
      const result = await batch.send();
  • Added support for authenticating with OTP (email code):

      const result = await pb.collection("users").requestOTP("test@example.com");
    
      // ... show a modal for users to check their email and to enter the received code ...
    
      await pb.collection("users").authWithOTP(result.otpId, "EMAIL_CODE");

    Note that PocketBase v0.23.0 comes also with Multi-factor authentication (MFA) support. When enabled from the dashboard, the first auth attempt will result in 401 response and a mfaId response, that will have to be submitted with the second auth request. For example:

      try {
        await pb.collection("users").authWithPassword("test@example.com", "1234567890");
      } catch (err) {
        const mfaId = err.response?.mfaId;
        if (!mfaId) {
          throw err; // not mfa -> rethrow
        }
    
        // the user needs to authenticate again with another auth method, for example OTP
        const result = await pb.collection("users").requestOTP("test@example.com");
        // ... show a modal for users to check their email and to enter the received code ...
        await pb.collection("users").authWithOTP(result.otpId, "EMAIL_CODE", { "mfaId": mfaId });
      }
  • Added new pb.collection("users").impersonate("RECORD_ID") method for superusers. It authenticates with the specified record id and returns a new client with the impersonated auth state loaded in a memory store.

      // authenticate as superusers (with v0.23.0 admins is converted to a special system auth collection "_superusers"):
      await pb.collection("_superusers").authWithPassword("test@example.com", "1234567890");
    
      // impersonate
      const impersonateClient = pb.collection("users").impersonate("USER_RECORD_ID", 3600 /* optional token duration in seconds */)
    
      // log the impersonate token and user data
      console.log(impersonateClient.authStore.token);
      console.log(impersonateClient.authStore.record);
    
      // send requests as the impersonated user
      impersonateClient.collection("example").getFullList();
  • Added new pb.collections.getScaffolds() method to retrieve a type indexed map with the collection models (base, auth, view) loaded with their defaults.

  • Added new pb.collections.truncate(idOrName) to delete all records associated with the specified collection.

  • Added the submitted fetch options as 3rd last argument in the pb.afterSend hook.

  • Instead of replacing the entire pb.authStore.record, on auth record update we now only replace the available returned response record data (pocketbase#5638).

  • ⚠️ Admins are converted to _superusers auth collection and there is no longer AdminService and AdminModel types. pb.admins is soft-deprecated and aliased to pb.collection("_superusers").

      // before   ->  after
      pb.admins.* ->  pb.collection("_superusers").*
  • ⚠️ pb.authStore.model is soft-deprecated and superseded by pb.authStore.record.

  • ⚠️ Soft-deprecated the OAuth2 success auth meta.avatarUrl response field in favour of meta.avatarURL for consistency with the Go conventions.

  • ⚠️ Changed AuthMethodsList inerface fields to accomodate the new auth methods and listAuthMethods() response.

      {
        "mfa": {
          "duration": 100,
          "enabled": true
        },
        "otp": {
          "duration": 0,
          "enabled": false
        },
        "password": {
          "enabled": true,
          "identityFields": ["email", "username"]
        },
        "oauth2": {
          "enabled": true,
          "providers": [{"name": "gitlab", ...}, {"name": "google", ...}]
        }
      }
  • ⚠️ Require specifying collection id or name when sending test email because the email templates can be changed per collection.

      // old
      pb.settings.testEmail(email, "verification")
    
      // new
      pb.settings.testEmail("users", email, "verification")
  • ⚠️ Soft-deprecated and aliased *Url() -> *URL() methods for consistency with other similar native JS APIs and the accepted Go conventions. The old methods still works but you may get a console warning to replace them because they will be removed in the future.

      pb.baseUrl                  -> pb.baseURL
      pb.buildUrl()               -> pb.buildURL()
      pb.files.getUrl()           -> pb.files.getURL()
      pb.backups.getDownloadUrl() -> pb.backups.getDownloadURL()
  • ⚠️ Renamed CollectionModel.schema to CollectionModel.fields.

  • ⚠️ Renamed type SchemaField to CollectionField.

0.21.5

  • Shallow copy the realtime subscribe options argument for consistency with the other methods (#308).

0.21.4

  • Fixed the requestKey handling in authWithOAuth2({...}) to allow manually cancelling the entire OAuth2 pending request flow using pb.cancelRequest(requestKey). Due to the window.close caveats note that the OAuth2 popup window may still remain open depending on which stage of the OAuth2 flow the cancellation has been invoked.

0.21.3

0.21.2

  • Exported HealthService types (#289).

0.21.1

  • Manually update the verified state of the current matching AuthStore model on successful "confirm-verification" call.

  • Manually clear the current matching AuthStore on "confirm-email-change" call because previous tokens are always invalidated.

  • Updated the fetch mock tests to check also the sent body params.

  • Formatted the source and tests with prettier.

0.21.0

⚠️ This release works only with PocketBase v0.21.0+ due to changes of how the multipart/form-data body is handled.

  • Properly sent json body with multipart/form-data requests. This should fix the edge cases mentioned in the v0.20.3 release.

  • Gracefully handle OAuth2 redirect error with the authWithOAuth2() call.

0.20.3

  • Partial and temporary workaround for the auto application/json -> multipart/form-data request serialization of a json field when a Blob/File is found in the request body (#274).

    The "fix" is partial because there are still 2 edge cases that are not handled - when a json field value is empty array (eg. []) or array of strings (eg. ["a","b"]). The reason for this is because the SDK doesn't have information about the field types and doesn't know which field is a json or an arrayable select, file or relation, so it can't serialize it properly on its own as FormData string value.

    If you are having troubles with persisting json values as part of a multipart/form-data request the easiest fix for now is to manually stringify the json field value:

      await pb.collection("example").create({
        // having a Blob/File as object value will convert the request to multipart/form-data
        "someFileField": new Blob([123]),
        "someJsonField": JSON.stringify(["a","b","c"]),
      })

    A proper fix for this will be implemented with PocketBase v0.21.0 where we'll have support for a special @jsonPayload multipart body key, which will allow us to submit mixed multipart/form-data content (kindof similar to the multipart/mixed MIME).

0.20.2

  • Throw 404 error for getOne("") when invoked with empty id (#271).

  • Added @throw {ClientResponseError} jsdoc annotation to the regular request methods (#262).

0.20.1

  • Propagate the PB_CONNECT event to allow listening to the realtime connect/reconnect events.
      pb.realtime.subscribe("PB_CONNECT", (e) => {
        console.log(e.clientId);
      })

0.20.0

  • Added expand, filter, fields, custom query and headers parameters support for the realtime subscriptions.

      pb.collection("example").subscribe("*", (e) => {
        ...
      }, { filter: "someField > 10" });

    This works only with PocketBase v0.20.0+.

  • Changes to the logs service methods in relation to the logs generalization in PocketBase v0.20.0+:

      pb.logs.getRequestsList(...)  -> pb.logs.getList(...)
      pb.logs.getRequest(...)       -> pb.logs.getOne(...)
      pb.logs.getRequestsStats(...) -> pb.logs.getStats(...)
  • Added missing SchemaField.presentable field.

  • Added new AuthProviderInfo.displayName string field.

  • Added new AuthMethodsList.onlyVerified bool field.

0.19.0

  • Added pb.filter(rawExpr, params?) helper to construct a filter string with placeholder parameters populated from an object.

      const record = await pb.collection("example").getList(1, 20, {
        // the same as: "title ~ 'te\\'st' && (totalA = 123 || totalB = 123)"
        filter: pb.filter("title ~ {:title} && (totalA = {:num} || totalB = {:num})", { title: "te'st", num: 123 })
      })

    The supported placeholder parameter values are:

    • string (single quotes will be autoescaped)
    • number
    • boolean
    • Date object (will be stringified into the format expected by PocketBase)
    • null
    • anything else is converted to a string using JSON.stringify()

0.18.3

  • Added optional generic support for the RecordService (#251). This should allow specifying a single TypeScript definition for the client, eg. using type assertion:

      interface Task {
        id:   string;
        name: string;
      }
    
      interface Post {
        id:     string;
        title:  string;
        active: boolean;
      }
    
      interface TypedPocketBase extends PocketBase {
        collection(idOrName: string): RecordService // default fallback for any other collection
        collection(idOrName: 'tasks'): RecordService<Task>
        collection(idOrName: 'posts'): RecordService<Post>
      }
    
      ...
    
      const pb = new PocketBase("http://127.0.0.1:8090") as TypedPocketBase;
    
      // the same as pb.collection('tasks').getOne<Task>("RECORD_ID")
      await pb.collection('tasks').getOne("RECORD_ID") // -> results in Task
    
      // the same as pb.collection('posts').getOne<Post>("RECORD_ID")
      await pb.collection('posts').getOne("RECORD_ID") // -> results in Post

0.18.2

  • Added support for assigning a Promise as AsyncAuthStore initial value (#249).

0.18.1

  • Fixed realtime subscriptions auto cancellation to use the proper requestKey param.

0.18.0

  • Added pb.backups.upload(data) action (available with PocketBase v0.18.0).

  • Added experimental autoRefreshThreshold option to auto refresh (or reauthenticate) the AuthStore when authenticated as admin. This could be used as an alternative to fixed Admin API keys.

      await pb.admins.authWithPassword("test@example.com", "1234567890", {
        // This will trigger auto refresh or auto reauthentication in case
        // the token has expired or is going to expire in the next 30 minutes.
        autoRefreshThreshold: 30 * 60
      })

0.17.3

  • Loosen the type check when calling pb.files.getUrl(user, filename) to allow passing the pb.authStore.model without type assertion.

0.17.2

  • Fixed mulitple File/Blob array values not transformed properly to their FormData equivalent when an object syntax is used.

0.17.1

  • Fixed typo in the deprecation console.warn messages (#235; thanks @heloineto).

0.17.0

  • To simplify file uploads, we now allow sending the multipart/form-data request body also as plain object if at least one of the object props has File or Blob value.

      // the standard way to create multipart/form-data body
      const data = new FormData();
      data.set("title", "lorem ipsum...")
      data.set("document", new File(...))
    
      // this is the same as above
      // (it will be converted behind the scenes to FormData)
      const data = {
        "title":    "lorem ipsum...",
        "document": new File(...),
      };
    
      await pb.collection("example").create(data);
  • Added new pb.authStore.isAdmin and pb.authStore.isAuthRecord helpers to check the type of the current auth state.

  • The default LocalAuthStore now listen to the browser storage event, so that we can sync automatically the pb.authStore state between multiple tabs.

  • Added new helper AsyncAuthStore class that can be used to integrate with any 3rd party async storage implementation (usually this is needed when working with React Native):

      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("https://example.com", store)
  • pb.files.getUrl() now returns empty string in case an empty filename is passed.

  • ⚠️ All API actions now return plain object (POJO) as response, aka. the custom class wrapping was removed and you no longer need to manually call structuredClone(response) when using with SSR frameworks.

    This could be a breaking change if you use the below classes (and respectively their helper methods like $isNew, $load(), etc.) since they were replaced with plain TS interfaces:

      class BaseModel    -> interface BaseModel
      class Admin        -> interface AdminModel
      class Record       -> interface RecordModel
      class LogRequest   -> interface LogRequestModel
      class ExternalAuth -> interface ExternalAuthModel
      class Collection   -> interface CollectionModel
      class SchemaField  -> interface SchemaField
      class ListResult   -> interface ListResult

    Side-note: If you use somewhere in your code the Record and Admin classes to determine the type of your pb.authStore.model, you can safely replace it with the new pb.authStore.isAdmin and pb.authStore.isAuthRecord getters.

  • ⚠️ Added support for per-request fetch options, including also specifying completely custom fetch implementation.

    In addition to the default fetch options, the following configurable fields are supported:

      interface SendOptions extends RequestInit {
          // any other custom key will be merged with the query parameters
          // for backward compatibility and to minimize the verbosity
          [key: string]: any;
    
          // optional custom fetch function to use for sending the request
          fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
    
          // custom headers to send with the requests
          headers?: { [key: string]: string };
    
          // the body of the request (serialized automatically for json requests)
          body?: any;
    
          // query params that will be appended to the request url
          query?: { [key: string]: any };
    
          // the request identifier that can be used to cancel pending requests
          requestKey?:  string|null;
    
          // @deprecated use `requestKey:string` instead
          $cancelKey?:  string;
    
          // @deprecated use `requestKey:null` instead
          $autoCancel?: boolean;
      }

    For most users the above will not be a breaking change since there are available function overloads (when possible) to preserve the old behavior, but you can get a warning message in the console to update to the new format. For example:

      // OLD (should still work but with a warning in the console)
      await pb.collection("example").authRefresh({}, {
        "expand": "someRelField",
      })
    
      // NEW
      await pb.collection("example").authRefresh({
        "expand": "someRelField",
        // send some additional header
        "headers": {
          "X-Custom-Header": "123",
        },
        "cache": "no-store" // also usually used by frameworks like Next.js
      })
  • Eagerly open the default OAuth2 signin popup in case no custom urlCallback is provided as a workaround for Safari.

  • Internal refactoring (updated dev dependencies, refactored the tests to use Vitest instead of Mocha, etc.).

0.16.0

  • Added skipTotal=1 query parameter by default for the getFirstListItem() and getFullList() requests. Note that this have performance boost only with PocketBase v0.17+.

  • Added optional download=1 query parameter to force file urls with Content-Disposition: attachment (supported with PocketBase v0.17+).

0.15.3

  • Automatically resolve pending realtime connect Promises in case unsubscribe is called before subscribe is being able to complete (pocketbase#2897).

0.15.2

  • Replaced new URL(...) with manual url parsing as it is not fully supported in React Native (pocketbase#2484).

  • Fixed nested ClientResponseError.originalError wrapping and added ClientResponseError constructor tests.

0.15.1

  • Cancel any pending subscriptions submit requests on realtime disconnect (#204).

0.15.0

  • Added fields to the optional query parameters for limiting the returned API fields (available with PocketBase v0.16.0).

  • Added pb.backups service for the new PocketBase backup and restore APIs (available with PocketBase v0.16.0).

  • Updated pb.settings.testS3(filesystem) to allow specifying a filesystem to test - storage or backups (available with PocketBase v0.16.0).

0.14.4

  • Removed the legacy aliased BaseModel.isNew getter since it conflicts with similarly named record fields (pocketbase#2385). This helper is mainly used in the Admin UI, but if you are also using it in your code you can replace it with the $ prefixed version, aka. BaseModel.$isNew.

0.14.3

  • Added OAuth2AuthConfig.query prop to send optional query parameters with the authWithOAuth2(config) call.

0.14.2

  • Use location.origin + location.pathname instead of full location.href when constructing the browser absolute url to ignore any extra hash or query parameter passed to the base url. This is a small addition to the earlier change from v0.14.1.

0.14.1

  • Use an absolute url when the SDK is initialized with a relative base path in a browser env to ensure that the generated OAuth2 redirect and file urls are absolute.

0.14.0

  • Added simplified authWithOAuth2() version without having to implement custom redirect, deeplink or even page reload:

      const authData = await pb.collection('users').authWithOAuth2({
        provider: 'google'
      })

    Works with PocketBase v0.15.0+.

    This method initializes a one-off realtime subscription and will open a popup window with the OAuth2 vendor page to authenticate. Once the external OAuth2 sign-in/sign-up flow is completed, the popup window will be automatically closed and the OAuth2 data sent back to the user through the previously established realtime connection.

    Site-note: when creating the OAuth2 app in the provider dashboard you have to configure https://yourdomain.com/api/oauth2-redirect as redirect URL.

    The "manual" code exchange flow is still supported as authWithOAuth2Code(provider, code, codeVerifier, redirectUrl).

    For backward compatibility it is also available as soft-deprecated function overload of authWithOAuth2(provider, code, codeVerifier, redirectUrl).

  • Added new pb.files service:

      // Builds and returns an absolute record file url for the provided filename.
      🔓 pb.files.getUrl(record, filename, queryParams = {});
    
      // Requests a new private file access token for the current auth model (admin or record).
      🔐 pb.files.getToken(queryParams = {});

    pb.getFileUrl() is soft-deprecated and acts as alias calling pb.files.getUrl() under the hood.

    Works with PocketBase v0.15.0+.

0.13.1

  • Added option to specify a generic send() return type and defined SendOptions type (#171; thanks @iamelevich).

  • Deprecated SchemaField.unique prop since its function is replaced by Collection.indexes in the upcoming PocketBase v0.14.0 release.

0.13.0

  • Aliased all BaseModel helpers with $ equivalent to avoid conflicts with the dynamic record props (#169).

    isNew      -> $isNew
    load(data) -> $load(data)
    clone()    -> $clone()
    export()   -> $export()
    // ...

    For backward compatibility, the old helpers will still continue to work if the record doesn't have a conflicting field name.

  • Updated pb.beforeSend and pb.afterSend signatures to allow returning and awaiting an optional Promise (#166; thanks @Bobby-McBobface).

  • Added Collection.indexes field for the new collection indexes support in the upcoming PocketBase v0.14.0.

  • Added pb.settings.generateAppleClientSecret() for sending a request to generate Apple OAuth2 client secret in the upcoming PocketBase v0.14.0.

0.12.1

  • Fixed request multipart/form-data body check to allow the React Native Android and iOS custom FormData implementation as valid fetch body (#2002).

0.12.0

  • Changed the return type of pb.beforeSend hook to allow modifying the request url (#1930).

    // old
    pb.beforeSend = function (url, options) {
      ...
      return options;
    }
    
    // new
    pb.beforeSend = function (url, options) {
      ...
      return { url, options };
    }

    The old return format is soft-deprecated and will still work, but you'll get a console.warn message to replace it.

0.11.1

  • Exported the services class definitions to allow being used as argument types (#153).
    CrudService
    AdminService
    CollectionService
    LogService
    RealtimeService
    RecordService
    SettingsService

0.11.0

  • Aliased/soft-deprecated ClientResponseError.data in favor of ClientResponseError.response to avoid the stuttering when accessing the inner error response data key (aka. err.data.data now is err.response.data). The ClientResponseError.data will still work but it is recommend for new code to use the response key.

  • Added getFullList(queryParams = {}) overload since the default batch size in most cases doesn't need to change (it can be defined as query parameter). The old form getFullList(batch = 200, queryParams = {}) will still work, but it is recommend for new code to use the shorter form.

0.10.2

  • Updated getFileUrl() to accept custom types as record argument.

0.10.1

  • Added check for the collection name before auto updating the pb.authStore state on auth record update/delete.

0.10.0

  • Added more helpful message for the ECONNREFUSED ::1 localhost error (related to #21).

  • Preserved the "original" function and class names in the minified output for those who rely on *.prototype.name.

  • Allowed sending the existing valid auth token with the authWithPassword() calls.

  • Updated the Nuxt3 SSR examples to use the built-in useCookie() helper.

0.9.1

  • Normalized nested expand items to Record|Array<Record> instances.

0.9.0

  • Added pb.health.check() that checks the health status of the API service (available in PocketBase v0.10.0)

0.8.4

  • Added type declarations for the action query parameters (#102; thanks @sewera).
    BaseQueryParams
    ListQueryParams
    RecordQueryParams
    RecordListQueryParams
    LogStatsQueryParams
    FileQueryParams

0.8.3

  • Renamed the declaration file extension from .d.ts to .d.mts to prevent type resolution issues (#92).

0.8.2

  • Allowed catching the initial realtime connect error as part of the subscribe() Promise resolution.

  • Reimplemented the default EventSource retry mechanism for better control and more consistent behavior across different browsers.

0.8.1

This release contains only documentation fixes:

  • Fixed code comment typos.

  • Added note about loadFromCookie that you may need to call authRefresh to validate the loaded cookie state server-side.

  • Updated the SSR examples to show the authRefresh call. For the examples the authRefresh call is not required but it is there to remind users that it needs to be called if you want to do permission checks in a node env (eg. SSR) and rely on the pb.authStore.isValid.

0.8.0

⚠️ Please note that this release works only with the new PocketBase v0.8+ API!

See the breaking changes below for what has changed since v0.7.x.

Non breaking changes

  • Added support for optional custom Record types using TypeScript generics, eg. pb.collection('example').getList<Tasks>().

  • Added new pb.autoCancellation(bool) method to globally enable or disable auto cancellation (true by default).

  • Added new crud method getFirstListItem(filter) to fetch a single item by a list filter.

  • You can now set additional account createData when authenticating with OAuth2.

  • Added AuthMethodsList.usernamePassword return field (we now support combined username/email authentication; see below authWithPassword).

Breaking changes

  • Changed the contstructor from PocketBase(url, lang?, store?) to PocketBase(url, store?, lang?) (aka. the lang option is now last).

  • For easier and more conventional parsing, all DateTime strings now have Z as suffix, so that you can do directly new Date('2022-01-01 01:02:03.456Z').

  • Moved pb.records.getFileUrl() to pb.getFileUrl().

  • Moved all pb.records.* handlers under pb.collection().*:

    pb.records.getFullList('example');                => pb.collection('example').getFullList();
    pb.records.getList('example');                    => pb.collection('example').getList();
    pb.records.getOne('example', 'RECORD_ID');        => pb.collection('example').getOne('RECORD_ID');
    (no old equivalent)                               => pb.collection('example').getFirstListItem(filter);
    pb.records.create('example', {...});              => pb.collection('example').create({...});
    pb.records.update('example', 'RECORD_ID', {...}); => pb.collection('example').update('RECORD_ID', {...});
    pb.records.delete('example', 'RECORD_ID');        => pb.collection('example').delete('RECORD_ID');
  • The pb.realtime service has now a more general callback form so that it can be used with custom realtime handlers. Dedicated records specific subscribtions could be found under pb.collection().*:

    pb.realtime.subscribe('example', callback)           => pb.collection('example').subscribe("*", callback)
    pb.realtime.subscribe('example/RECORD_ID', callback) => pb.collection('example').subscribe('RECORD_ID', callback)
    pb.realtime.unsubscribe('example')                   => pb.collection('example').unsubscribe("*")
    pb.realtime.unsubscribe('example/RECORD_ID')         => pb.collection('example').unsubscribe('RECORD_ID')
    (no old equivalent)                                  => pb.collection('example').unsubscribe()

    Additionally, subscribe() now return UnsubscribeFunc that could be used to unsubscribe only from a single subscription listener.

  • Moved all pb.users.* handlers under pb.collection().*:

    pb.users.listAuthMethods()                                                 => pb.collection('users').listAuthMethods()
    pb.users.authViaEmail(email, password)                                     => pb.collection('users').authWithPassword(usernameOrEmail, password)
    pb.users.authViaOAuth2(provider, code, codeVerifier, redirectUrl)          => pb.collection('users').authWithOAuth2(provider, code, codeVerifier, redirectUrl, createData = {})
    pb.users.refresh()                                                         => pb.collection('users').authRefresh()
    pb.users.requestPasswordReset(email)                                       => pb.collection('users').requestPasswordReset(email)
    pb.users.confirmPasswordReset(resetToken, newPassword, newPasswordConfirm) => pb.collection('users').confirmPasswordReset(resetToken, newPassword, newPasswordConfirm)
    pb.users.requestVerification(email)                                        => pb.collection('users').requestVerification(email)
    pb.users.confirmVerification(verificationToken)                            => pb.collection('users').confirmVerification(verificationToken)
    pb.users.requestEmailChange(newEmail)                                      => pb.collection('users').requestEmailChange(newEmail)
    pb.users.confirmEmailChange(emailChangeToken, password)                    => pb.collection('users').confirmEmailChange(emailChangeToken, password)
    pb.users.listExternalAuths(recordId)                                       => pb.collection('users').listExternalAuths(recordId)
    pb.users.unlinkExternalAuth(recordId, provider)                            => pb.collection('users').unlinkExternalAuth(recordId, provider)
  • Changes in pb.admins for consistency with the new auth handlers in pb.collection().*:

    pb.admins.authViaEmail(email, password); => pb.admins.authWithPassword(email, password);
    pb.admins.refresh();                     => pb.admins.authRefresh();
  • To prevent confusion with the auth method responses, the following methods now returns 204 with empty body (previously 200 with token and auth model):

    pb.admins.confirmPasswordReset(...): Promise<bool>
    pb.collection("users").confirmPasswordReset(...): Promise<bool>
    pb.collection("users").confirmVerification(...): Promise<bool>
    pb.collection("users").confirmEmailChange(...): Promise<bool>
  • Removed the User model because users are now regular records (aka. Record). The old user fields lastResetSentAt, lastVerificationSentAt and profile are no longer available (the profile fields are available under the Record.* property like any other fields).

  • Renamed the special Record props:

    @collectionId   => collectionId
    @collectionName => collectionName
    @expand         => expand
  • Since there is no longer User model, pb.authStore.model can now be of type Record, Admin or null.

  • Removed lastResetSentAt from the Admin model.

  • Replaced ExternalAuth.userId with 2 new recordId and collectionId props.

  • Removed the deprecated uppercase service aliases:

    client.Users       => client.collection(*)
    client.Records     => client.collection(*)
    client.AuthStore   => client.authStore
    client.Realtime    => client.realtime
    client.Admins      => client.admins
    client.Collections => client.collections
    client.Logs        => client.logs
    client.Settings    => client.settings