- Notifications
You must be signed in to change notification settings - Fork171
pocketbase/js-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Official JavaScript SDK (browser and node) for interacting with thePocketBase API.
<scriptsrc="/path/to/dist/pocketbase.umd.js"></script><scripttype="text/javascript">constpb=newPocketBase("https://example.com")...</script>
OR if you are using ES modules:
<scripttype="module">importPocketBasefrom'/path/to/dist/pocketbase.es.mjs'constpb=newPocketBase("https://example.com")...</script>
npm install pocketbase --save
// Using ES modules (default)importPocketBasefrom'pocketbase'// OR if you are using CommonJS modulesconstPocketBase=require('pocketbase/cjs')
🔧 ForNode < 17 you'll need to load a
fetch()polyfill.I recommendlquixada/cross-fetch:// npm install cross-fetch --saveimport'cross-fetch/polyfill';
🔧 Node doesn't have native
EventSourceimplementation, so in order to use the realtime subscriptions you'll need to load aEventSourcepolyfill.// for server: npm install eventsource --saveimport{EventSource}from"eventsource";// for React Native: npm install react-native-sse --saveimportEventSourcefrom"react-native-sse";global.EventSource=EventSource;
importPocketBasefrom'pocketbase';constpb=newPocketBase('http://127.0.0.1:8090');...// authenticate as auth collection recordconstuserData=awaitpb.collection('users').authWithPassword('test@example.com','123456');// list and filter "example" collection recordsconstresult=awaitpb.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 theAPI documentation for each service.
The SDK comes with a helperpb.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 asfilter 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).
constrecords=awaitpb.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)numberbooleanDateobject (will be stringified into the format expected by PocketBase)null- everything else is converted to a string using
JSON.stringify()
PocketBase Web API supports file upload viamultipart/form-data requests,which means that to upload a file it is enough to provide either aFormData instance OR plain object withFile/Blob prop values.
Using plain object as body(this is the same as above and it will be converted to
FormDatabehind the scenes):constdata={'title':'lorem ipsum...','document':newFile(...),};awaitpb.collection('example').create(data);
Using
FormDataas body:// the standard way to create multipart/form-data bodyconstdata=newFormData();data.set('title','lorem ipsum...')data.set('document',newFile(...))awaitpb.collection('example').create(data);
All services return a standardPromise-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{constresult=awaitpb.collection('example').getList(1,50);console.log('Result:',result);}catch(error){console.log('Error:',error);}
The response error is normalized and always returned asClientResponseError object with the following public fields that you could use:
ClientResponseError{url:string,// requested urlstatus:number,// response status coderesponse:{ ...},// the API JSON error responseisAbort:boolean,// is abort/cancellation errororiginalError:Error|null,// the original non-normalized error}
The SDK keeps track of the authenticated token and auth model for you via thepb.authStore instance.
The defaultLocalAuthStore uses the browser'sLocalStorage 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
LocalStoragebut keep in mind that, unlike in browsers where the client is the only user, by default DenoLocalStoragewill be shared by all clients making requests to your server!
The SDK comes also with a helperAsyncAuthStore that you can use to integrate with any 3rd party async storage implementation (usually this is needed when working with React Native):
importAsyncStoragefrom'@react-native-async-storage/async-storage';importPocketBase,{AsyncAuthStore}from'pocketbase';conststore=newAsyncAuthStore({save:async(serialized)=>AsyncStorage.setItem('pb_auth',serialized),initial:AsyncStorage.getItem('pb_auth'),});constpb=newPocketBase('http://127.0.0.1:8090',store)
In some situations it could be easier to create your own custom auth store. For this you can extendBaseAuthStore and pass the new custom instance as constructor argument to the client:
importPocketBase,{BaseAuthStore}from'pocketbase';classCustomAuthStoreextendsBaseAuthStore{save(token,model){super.save(token,model);// your custom business logic...}}constpb=newPocketBase('http://127.0.0.1:8090',newCustomAuthStore());
The defaultpb.authStore extendsBaseAuthStore 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 methodsclear()// "logout" the authenticated recordsave(token,record)// update the store with the new auth dataonChange(callback,fireImmediately=false)// register a callback that will be called on store change// cookie parse and serialize helpersloadFromCookie(cookieHeader,key='pb_auth')exportToCookie(options={},key='pb_auth')}
To"logout" the authenticated record you can callpb.authStore.clear().
To"listen" for changes in the auth store, you can register a new listener viapb.authStore.onChange, eg:
// triggered everytime on store changeconstremoveListener1=pb.authStore.onChange((token,record)=>{console.log('New store data 1:',token,record)});// triggered once right after registration and everytime on store changeconstremoveListener2=pb.authStore.onChange((token,record)=>{console.log('New store data 2:',token,record)},true);// (optional) removes the attached listenersremoveListener1();removeListener2();
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 withClientResponseError error:
pb.collection('example').getList(1,20)// cancelledpb.collection('example').getList(2,20)// cancelledpb.collection('example').getList(3,20)// executed
To change this behavior per request basis, you can adjust therequestKey: null|string special query parameter.Set it tonull 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 toHTTP_METHOD + path, eg. "GET /api/users")
Example:
pb.collection('example').getList(1,20);// cancelledpb.collection('example').getList(1,20);// executedpb.collection('example').getList(1,20,{requestKey:"test"})// cancelledpb.collection('example').getList(1,20,{requestKey:"test"})// executedpb.collection('example').getList(1,20,{requestKey:null})// executedpb.collection('example').getList(1,20,{requestKey:null})// executed// globally disable auto cancellationpb.autoCancellation(false);pb.collection('example').getList(1,20);// executedpb.collection('example').getList(1,20);// executedpb.collection('example').getList(1,20);// executed
If you want to globally disable the auto cancellation behavior, you could setpb.autoCancellation(false).
To manually cancel pending requests, you could usepb.cancelAllRequests() orpb.cancelRequest(requestKey).
You could specify custom TypeScript definitions for your Record models using generics:
interfaceTask{// 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:
interfaceTask{id:string;name:string;}interfacePost{id:string;title:string;active:boolean;}interfaceTypedPocketBaseextendsPocketBase{collection(idOrName:string):RecordService// default fallback for any other collectioncollection(idOrName:'tasks'):RecordService<Task>collection(idOrName:'posts'):RecordService<Post>}...constpb=newPocketBase("http://127.0.0.1:8090")asTypedPocketBase;pb.collection('tasks').getOne("RECORD_ID")// -> results in Promise<Task>pb.collection('posts').getOne("RECORD_ID")// -> results in Promise<Post>
All API services accept an optionaloptions argument (usually the last one and of typeSendOptions), that can be used to provide:
- custom headers for a single request
- custom fetch options
- or even your own
fetchimplementation
For example:
pb.collection('example').getList(1,20,{expand:'someRel',otherQueryParam:'123',// custom headersheaders:{'X-Custom-Header':'example',},// custom fetch optionskeepalive:false,cache:'no-store',// or custom fetch implementationfetch:async(url,config)=>{ ...},})
Note that for backward compatability and to minimize the verbosity, any "unknown" top-level field will be treated as query parameter.
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 thefetchrequest, allowing you to inspect/modify the request config.constpb=newPocketBase('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#optionsoptions.headers=Object.assign({},options.headers,{'X-Custom-Header':'example',});return{ url, options};};// use the created client as usual...
afterSend- triggered after successfully sending thefetchrequest, allowing you to inspect/modify the response object and its parsed data.constpb=newPocketBase('http://127.0.0.1:8090');pb.afterSend=function(response,data){// do something with the response stateconsole.log(response.status);returnObject.assign(data,{// extend the data..."additionalField":123,});};// use the created client as usual...
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:
- Create a new
PocketBaseinstance for each server-side request - "Load/Feed" your
pb.authStorewith data from the request cookie - Perform your application server-side actions
- Before returning the response to the client, update the cookie with the latest
pb.authStorestate
AllBaseAuthStore instances have 2 helper methods thatshould make working with cookies a little bit easier:
// update the store with the parsed data from the cookie stringpb.authStore.loadFromCookie('pb_auth=...');// exports the store data as cookie, with option to extend the default SameSite, Secure, HttpOnly, Path and Expires attributespb.authStore.exportToCookie({httpOnly:false});// Output: 'pb_auth=...'
Below you could find several examples:
SvelteKit
One way to integrate with SvelteKit SSR could be to create the PocketBase client in ahook handleand pass it to the other server-side actions using theevent.locals.
// src/hooks.server.jsimportPocketBasefrom'pocketbase';/**@type {import('@sveltejs/kit').Handle} */exportasyncfunctionhandle({ event, resolve}){event.locals.pb=newPocketBase('http://127.0.0.1:8090');// load the store data from the request cookie stringevent.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&&awaitevent.locals.pb.collection('users').authRefresh();}catch(_){// clear the auth store on failed refreshevent.locals.pb.authStore.clear();}constresponse=awaitresolve(event);// send back the default 'pb_auth' cookie to the client with the latest store stateresponse.headers.append('set-cookie',event.locals.pb.authStore.exportToCookie());returnresponse;}
And then, in some of your server-side actions, you could directly access the previously createdevent.locals.pb instance:
// src/routes/login/+server.js/** * Creates a `POST /login` server-side endpoint * *@type {import('./$types').RequestHandler} */exportasyncfunctionPOST({ request, locals}){const{ email, password}=awaitrequest.json();const{ token, record}=awaitlocals.pb.collection('users').authWithPassword(email,password);returnnewResponse('Success...');}
For properlocals.pb type detection, you can also addPocketBase in your your global types definition:
// src/app.d.tsimportPocketBasefrom'pocketbase';declare global{declarenamespaceApp{interfaceLocals{pb:PocketBase}}}
Astro
To integrate with Astro SSR, you could create the PocketBase client in theMiddleware and pass it to the Astro components using theAstro.locals.
// src/middleware/index.tsimportPocketBasefrom'pocketbase';import{defineMiddleware}from'astro/middleware';exportconstonRequest=defineMiddleware(async({ locals, request}:any,next:()=>any)=>{locals.pb=newPocketBase('http://127.0.0.1:8090');// load the store data from the request cookie stringlocals.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&&awaitlocals.pb.collection('users').authRefresh();}catch(_){// clear the auth store on failed refreshlocals.pb.authStore.clear();}constresponse=awaitnext();// send back the default 'pb_auth' cookie to the client with the latest store stateresponse.headers.append('set-cookie',locals.pb.authStore.exportToCookie());returnresponse;});
And then, in your Astro file's component script, you could directly access the previously createdlocals.pb instance:
// src/pages/index.astro---constlocals=Astro.locals;constuserAuth=async()=>{const{ token, record}=awaitlocals.pb.collection('users').authWithPassword('test@example.com','123456');returnnewResponse('Success...');};---
Although middleware functionality is available in bothSSG andSSR projects, you would likely want to handle any sensitive data on the server side. Update youroutput configuration to'server':
// astro.config.mjsimport{defineConfig}from'astro/config';exportdefaultdefineConfig({output:'server'});
Nuxt 3
One way to integrate with Nuxt 3 SSR could be to create the PocketBase client in anuxt pluginand provide it as a helper to thenuxtApp instance:
// plugins/pocketbase.jsimportPocketBasefrom'pocketbase';exportdefaultdefineNuxtPlugin(async()=>{constpb=newPocketBase('http://127.0.0.1:8090');constcookie=useCookie('pb_auth',{path:'/',secure:true,sameSite:'strict',httpOnly:false,// change to "true" if you want only server-side accessmaxAge:604800,})// load the store data from the cookie valuepb.authStore.save(cookie.value?.token,cookie.value?.record);// send back the default 'pb_auth' cookie to the client with the latest store statepb.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&&awaitpb.collection('users').authRefresh();}catch(_){// clear the auth store on failed refreshpb.authStore.clear();}return{provide:{ pb}}});
And then in your component you could access it like this:
<template><div> Show: {{ data }}</div></template><scriptsetup>const{ data}=awaituseAsyncData(async(nuxtApp)=>{// fetch and return all "example" records...constrecords=awaitnuxtApp.$pb.collection('example').getFullList();returnstructuredClone(records);})</script>
Nuxt 2
One way to integrate with Nuxt 2 SSR could be to create the PocketBase client in anuxt plugin and provide it as a helper to the$root context:
// plugins/pocketbase.jsimportPocketBasefrom'pocketbase';exportdefaultasync(ctx,inject)=>{constpb=newPocketBase('http://127.0.0.1:8090');// load the store data from the request cookie stringpb.authStore.loadFromCookie(ctx.req?.headers?.cookie||'');// send back the default 'pb_auth' cookie to the client with the latest store statepb.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&&awaitpb.collection('users').authRefresh();}catch(_){// clear the auth store on failed refreshpb.authStore.clear();}inject('pocketbase',pb);};
And then in your component you could access it like this:
<template><div> Show: {{ items }}</div></template><script>exportdefault{asyncasyncData({ $pocketbase}){// fetch and return all "example" records...constitems=await$pocketbase.collection('example').getFullList();return{ items}}}</script>
Next.js
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 thegetServerSideProps functions (vercel/next.js#31792).
One way to integrate with Next.js SSR could be to create a customPocketBase instance in each of yourgetServerSideProps:
importPocketBasefrom'pocketbase';// you can place this helper in a separate file so that it can be reusedasyncfunctioninitPocketBase(req,res){constpb=newPocketBase('http://127.0.0.1:8090');// load the store data from the request cookie stringpb.authStore.loadFromCookie(req?.headers?.cookie||'');// send back the default 'pb_auth' cookie to the client with the latest store statepb.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&&awaitpb.collection('users').authRefresh();}catch(_){// clear the auth store on failed refreshpb.authStore.clear();}returnpb}exportasyncfunctiongetServerSideProps({ req, res}){constpb=awaitinitPocketBase(req,res)// fetch example records...constresult=awaitpb.collection('example').getList(1,30);return{props:{// ...},}}exportdefaultfunctionHome(){return(<div>Hello world!</div>)}
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 ifContent 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 asmeta 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 helperpb.filter(expr, params) when constructing filter strings with untrusted user input to avoid eventual string injection attacks (seeBinding filter parameters).
constpb=newPocketBase(baseURL='/',authStore=LocalAuthStore);
Each instance method returns the
PocketBaseinstance 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. |
Each service call returns a
Promiseobject with the API response.
// 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={});
// 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]);
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={});
// create a new batch instanceconstbatch=pb.createBatch();// register create/update/delete/upsert requests to the created batchbatch.collection('example1').create({ ...});batch.collection('example2').update('RECORD_ID',{ ...});batch.collection('example3').delete('RECORD_ID');batch.collection('example4').upsert({ ...});// send the batch requestconstresult=awaitbatch.send()
// 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={});
// 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={});
// 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={});
// 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={});
This service is usually used with custom realtime actions.For records realtime subscriptions you can use the subscribe/unsubscribemethods 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)
// 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);
// Returns list with all available cron jobs.🔐pb.crons.getFullList(options={});// Runs the specified cron job.🔐pb.crons.run(jobId,options={});
// Checks the health status of the api.🔓pb.health.check(options={});
# run unit testsnpmtest# run prettiernpm run format# build and minify for productionnpm run build
About
PocketBase JavaScript SDK
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.