AceBase Realtime Database Client
AceBase Client is a JavaScript/TypeScript library designed to connect to and interact with a remote AceBase realtime database server. It provides functionalities for reading, writing, querying, and subscribing to real-time data changes within an AceBase database. The current stable version is 1.22.3, with an active release cadence that frequently addresses bug fixes and introduces minor features, often preceded by release candidates. This client acts as the bridge for applications to leverage AceBase's NoSQL, schemaless, object-tree data model, supporting complex queries and robust authentication mechanisms. Its primary differentiator is its tight integration with the AceBase server ecosystem, enabling efficient data synchronization and real-time event handling for connected applications, both in Node.js and browser environments.
Common errors
-
ReferenceError: AceBaseClient is not defined
cause Attempting to use `AceBaseClient` in a browser environment without loading the `browser.min.js` script, or using ESM import in a CommonJS-only context (or vice versa) without proper transpilation.fixFor browsers, ensure `<script src="...">` is loaded. For Node.js, verify `import { AceBaseClient } from 'acebase-client';` for ESM or `const { AceBaseClient } = require('acebase-client');` for CommonJS is used correctly based on your project's module type. -
Error: connect ECONNREFUSED <host>:<port>
cause The AceBase server is not running, is inaccessible, or the provided host and port configuration is incorrect, preventing the client from establishing a connection.fixVerify that the AceBase server is running, listening on the specified host and port, and that no firewall is blocking the connection. Double-check `host`, `port`, and `https` options in the `AceBaseClient` constructor. -
Error: Access denied (401) or Error: Authentication failed (403)
cause The client attempted to access a protected resource without valid authentication credentials, or the provided credentials (username/password, email/password, or access token) are incorrect or expired.fixEnsure correct credentials are provided to `db.auth.signIn`, `signInWithEmail`, or `signInWithToken`. If using tokens, ensure they are still valid. Check server-side authentication rules.
Warnings
- breaking The return format for `uncached sync()` operations changed in v1.22.0. Applications using `sync()` without caching might need adjustments.
- breaking The `isNetworkError` getter was split into `isNetworkError` and `isServerError` in v1.22.2. If you relied on `isNetworkError` to catch all server-related errors, your error handling logic might need to be updated.
- gotcha The `setAccessToken` method for automatic sign-in with a stored token was introduced in v1.8.0. For older client versions, handling offline sign-in requires different manual logic or reconnect strategies.
- gotcha When using AceBase Client directly in the browser without a module bundler, you must include the `browser.min.js` script via a `<script>` tag. Standard `import` or `require` syntax will not work in this context.
Install
-
npm install acebase-client -
yarn add acebase-client -
pnpm add acebase-client
Imports
- AceBaseClient
const AceBaseClient = require('acebase-client'); // CommonJS import in an ESM project, or vice-versa. import AceBaseClient from 'acebase-client'; // Incorrect default import, it's a named export.import { AceBaseClient } from 'acebase-client'; - AceBaseRequestError
const { AceBaseRequestError } = require('acebase-client'); // Works, but ESM import is preferred in TypeScript/modern JS.import { AceBaseRequestError } from 'acebase-client'; - Browser Global (AceBaseClient)
import { AceBaseClient } from 'acebase-client'; // Will fail in browser environments without a module bundler.<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/acebase-client@latest/dist/browser.min.js"></script> // AceBaseClient is then available globally
Quickstart
import { AceBaseClient } from 'acebase-client';
// Replace with your actual AceBase server details
const host = process.env.ACEBASE_HOST ?? 'localhost';
const port = parseInt(process.env.ACEBASE_PORT ?? '5757', 10);
const dbname = process.env.ACEBASE_DBNAME ?? 'mydb';
const https = (process.env.ACEBASE_HTTPS ?? 'false') === 'true';
const db = new AceBaseClient({ host, port, dbname, https });
db.ready(async () => {
console.log('Connected to AceBase server.');
// 1. Log an event to the database
const logRef = db.ref('log');
await logRef.push({
user: 'guest_user',
type: 'quickstart_connect',
datetime: new Date().toISOString()
});
console.log('Logged connection event.');
// 2. Write and read user data
const userId = 'quickstart_user';
const userRef = db.ref(`users/${userId}`);
await userRef.set({ name: 'Jane Doe', email: 'jane@example.com', createdAt: new Date().toISOString() });
console.log(`User '${userId}' created.`);
const snapshot = await userRef.get();
console.log(`Read user data: ${JSON.stringify(snapshot.val())}`);
// 3. Subscribe to real-time changes on a 'todo' list
const todoRef = userRef.child('todo');
todoRef.on('child_added', (snapshot) => {
const item = snapshot.val();
console.log(`[REALTIME] Todo item added: ${item.text} (ID: ${snapshot.key})`);
});
// Add an item after a short delay to trigger the subscription
setTimeout(async () => {
await todoRef.push({ text: 'Learn AceBase', completed: false });
console.log('Added a todo item.');
}, 1000);
// Optional: Sign in if authentication is enabled on the server
// try {
// const authResult = await db.auth.signInWithEmail('admin@example.com', 'yourpassword');
// console.log(`Signed in as ${authResult.user.email}`);
// } catch (error) {
// console.warn('Authentication failed (if server requires it):', error.message);
// }
});
db.on('error', (error) => {
console.error('AceBase Client Error:', error);
});