@mozia/js
v0.3.0
Published
Mozia JavaScript/TypeScript SDK for Mozia Core 1.0 (MBaaS)
Downloads
259
Maintainers
Readme
Availability. This branch is 0.3.0, for Mozia Core 1.0.0. npm has only 0.2.0, which predates the Core 1.0 contract. Check which version you have before relying on anything here.
Mozia JavaScript/TypeScript SDK for MBaaS — a thin wrapper around the Mozia API.
Installation
0.3.0 is not published yet. npm has 0.2.0, which predates the Mozia Core 1.0 contract
(its signup is refused with 422 on every call), so until 0.3.0 is on npm, install it from a
source checkout:
git clone https://github.com/Mozia-Platform/mozia-js.git
cd mozia-js && npm ci && npm run build && npm pack # then: npm install ./mozia-js-0.3.0.tgzRequires Mozia Core 1.0.0 and a runtime with fetch, FormData, Blob and
AbortController (browsers, React Native, Node 18+). Developing the SDK itself (npm run build,
npm test) needs Node 22.18+ or 24.11+ (see .nvmrc).
The package is ESM only. Use import. require('@mozia/js') works only where Node loads
ES modules synchronously (Node 20.19+ or 22.12+). Under Jest, let it be transformed:
transformIgnorePatterns: ['/node_modules/(?!@mozia/js)']; the default Jest configuration does
not transform node_modules and cannot load it.
Quick Start
import { Mozia } from '@mozia/js';
const mozia = new Mozia({
serverURL: 'https://your-mozia-server.com',
appKey: 'your-public-client-key', // a public key type; see Key safety
});
// Auth — the signup field is `name`, not `username`, and the
// confirmation is sent as `password_confirmation` for you.
await mozia.auth.signup(appId, {
name: 'Ada Lovelace',
email: '[email protected]',
password: 'secret',
passwordConfirmation: 'secret',
});
const { data } = await mozia.auth.login(appId, {
email: '[email protected]',
password: 'secret',
});
const client = mozia.withSession(data.session_token);
// Records
const { data: records } = await client.records.query(appId, collectionId, {
where: { status: 'active' },
limit: 10,
includeTotal: false,
});
await client.records.create(appId, collectionId, { title: 'Hello' });
await client.records.patch(appId, collectionId, recordId, { status: 'archived' });
// Files
await client.files.upload(appId, fileBlob, 'photo.jpg');
const downloaded = await client.files.download(appId, fileId);
// LiveQuery (realtime, Beta) — needs the Reverb options shown under "LiveQuery" below
const unsubscribe = await client.livequery.subscribe(
appId,
'posts',
{ where: { status: 'published' }, order: '-createdAt' },
{
onEnter: (r) => console.log('created', r),
onUpdate: (r) => console.log('updated', r),
onLeave: (r) => console.log('deleted', r),
onError: (e) => console.warn(e.code, e.message),
}
);
// later: await unsubscribe();Key safety
appKey in a client application must be a public key type — javascript_key,
client_key or dotnet_key. Never ship a secret key (rest_api_key, master_key,
webhook_key, file_key): a key compiled into an app or served in a bundle can be read
from it, and secret keys carry write access to every record in the app.
A public key authorizes reads and realtime subscriptions only on collections that have been
opened to public keys. It can also list the collections it
is allowed to see. Nothing is open by default: a collection that has not been
granted public_key_permissions.read answers 404, the same answer it gives for a collection that
does not exist.
Record writes and file uploads require an app-user session token — sign the user in, then use
the session client — and those collections need app_user_permissions too. The server applies the
record ACL on top of both.
Grant access with mozia collections permissions --app <id> --collection <id> --public-read
(or --app-user create,read), or a PUT /api/apps/{app}/collections/{id} using a server-side key.
Sessions
auth.signup and auth.login return data.session_token. withSession(token) returns a new
client that sends it as X-Mozia-Session-Token on every request, alongside the app key; the
original client is not changed. auth.logout revokes the session server-side.
Pagination
records.query takes where, order (-field for descending), limit (default 20),
skip, cursor, cursorDirection ('after', the default, or 'before') and
includeTotal. meta carries limit and skip, total unless includeTotal: false, and
next_cursor / prev_cursor when a cursor was sent. A cursor cannot be combined with
skip, and supports at most one order field; the server answers 422 otherwise.
Errors
Every failed request rejects with MoziaError: status, code, message, errors
(per-field messages on a 422) and retryAfter (seconds, on a 429 that sends Retry-After,
in either the seconds or the HTTP-date form). code is the server's — UNAUTHENTICATED,
FORBIDDEN, NOT_FOUND, VALIDATION_ERROR, PAYLOAD_TOO_LARGE, RATE_LIMIT,
SERVICE_UNAVAILABLE, REALTIME_UNAVAILABLE and so on — or, when a proxy answered without
Mozia's JSON body, the same code derived from the status. A missing or null message, an HTML
body or an empty body never throws anything but a MoziaError.
status is 0 when no HTTP answer was involved:
| code | Meaning |
|---|---|
| NETWORK_ERROR | fetch got no answer (DNS, refused connection, CORS, offline). cause holds the platform error. |
| TIMEOUT | No answer within timeoutMs (a client option; unset means no SDK timeout). |
| CLIENT_UNSUPPORTED | A server-key feature called from a client (see below). No request was sent. |
| REALTIME_NOT_CONFIGURED | livequery.subscribe without the Reverb options. No request was sent. |
| REALTIME_CLIENT_UNAVAILABLE | livequery.subscribe could not load pusher-js or found no Pusher constructor in it. No request was sent. |
| INVALID_ARGUMENT | An app, collection, record or file id that is not a positive integer; the SDK checks ids locally. No request was sent. (Sent by hand, a non-numeric collection id gets 404 NOT_FOUND from Core 1.0.0.) |
A 2xx answer whose body is not JSON (a captive portal, a misrouted proxy) rejects with
INVALID_RESPONSE and that status. The SDK never retries a request on its own — whether a
write may be repeated is your decision; on a 429 use retryAfter when the server sends it.
A collection the caller may not read answers 404, the same as one that does not exist.
Deletes resolve to { success, message }.
API
- Auth:
signup,login,logout,me,withSession - Records:
query,get,create,update,patch,delete - Files:
list,upload(optional{ acl }),download,getUrl(deprecated),delete - LiveQuery:
subscribe(realtime record events, Beta)
Browser and mobile file operations require an authenticated app-user client created with
withSession(...): a public key alone cannot list, upload or read files, and an app user lists
only their own uploads. File metadata never includes the storage path. A file over 50 MiB is
refused with 422, and a request body over the server's limit with 413.
An uploaded file is readable and writable by its uploader only, unless you pass an ACL:
files.upload(appId, blob, 'a.pdf', { acl: { read: { app_users: [42] } } }). A file ACL has
read.public, read.app_users and write.app_users — no roles and no field access.
Not available from a client in Core 1.0
Push, installations and Cloud Functions require a server key and are not available to client
SDKs in Mozia Core 1.0. push.send, push.register and functions.invoke remain for source
compatibility but are deprecated: they reject immediately with a MoziaError coded
CLIENT_UNSUPPORTED (status 0) and send no request. Core serves these routes only to a
server key or a dashboard session — and even then push answers 501 PUSH_UNAVAILABLE and
functions 503 CLOUD_CODE_DISABLED. This SDK has no way to send a server key, and you must not
ship one in a client to work around this; call those routes from your own server instead.
LiveQuery (Beta)
Realtime needs a Pusher-protocol WebSocket server (Laravel Reverb) that the operator runs
alongside Core; without one, subscribe rejects with 503 REALTIME_UNAVAILABLE. Pass its
connection options to the client. All four are required by livequery.subscribe — there is
no default key, host, port or scheme that matches a Core deployment — and a missing one rejects
with REALTIME_NOT_CONFIGURED before anything is sent:
const mozia = new Mozia({
serverURL: 'https://your-mozia-server.com',
appKey: 'your-public-client-key',
reverbKey: 'your-reverb-app-key', // the Reverb app key, which is public
reverbHost: 'reverb.your-server.com',
reverbPort: 443,
reverbSecure: true,
});Subscriptions use opaque private channels returned by the server; the SDK never constructs a channel name, and channel authorization is bound to the connection that subscribed.
The WebSocket client is pusher-js (a dependency), loaded with import('pusher-js') on the
first subscribe. Bundlers (Vite, webpack, Metro, …) and Node resolve it on their own; the SDK
accepts each export shape pusher-js ships, including the React Native build's { Pusher }.
pusher-js has no ES module build, so a browser page that loads the SDK as native ES modules
without a bundler must provide it: load its browser build with a classic script and map the
specifier to a module that re-exports the global.
<script src="/vendor/pusher-js/dist/web/pusher.js"></script>
<script type="importmap">
{ "imports": { "@mozia/js": "/vendor/mozia-js/dist/index.js", "pusher-js": "/pusher-js-shim.js" } }
</script>
<!-- /pusher-js-shim.js contains: export default globalThis.Pusher; -->Limitations in Core 1.0:
- Delivery is best effort and at most once. There is no replay: events published while the
socket is down are lost. Load the current rows with
records.query, then apply events. subscriberesolves when the server has registered the subscription. The WebSocket and channel authorization complete afterwards:onReadyfires once the channel is joined — no event can arrive before it — and again whenever it is re-joined after an outage. Failures arrive ononErrorwith codeFORBIDDEN/UNAUTHENTICATED(permanent),REALTIME_TRANSPORT_UNAVAILABLE(the socket keeps retrying) orREALTIME_SUBSCRIPTION_EXPIRED(permanent; subscribe again).- There is no automatic renewal after an expiry or an authorization failure.
