Serenities SDK

The official JavaScript/TypeScript SDK for building apps with Serenities.

Quick Start

The SDK is auto-configured in Sites projects. Just import and use.

Each site is built with one version of the SDK, and page code reads it as serenities.sdkVersion. The current version is Site SDK 1.4.0. Your site's details say which version it was last published on ("Built on Site SDK x.y.z"); a site moves to the current SDK when you publish it again.

Import Patterns

Option 1: Default Import (Recommended)

import serenities from '../api/sdk';

await serenities.entities.Tasks.list();
await serenities.user.me();

Option 2: Named Imports

import { entities, user, email, files, payments, tenants, flows, functions, serverFetch, realtime, content } from '../api/sdk';

// React Router helpers
import { Link, useNavigate, useLocation, useParams, useSearchParams } from '../api/sdk';

Option 3: A Second Client

import { createClient } from '../api/sdk';

const client = createClient({
  projectId: 'your-project-id',
  apiBase: 'https://app.serenitiesai.com',
});

await client.entities.Tasks.list();

Never put an API key in page code: everything a page holds can be read by its visitors.

Available Modules

entities

CRUD, filtering, and relations for your tables

user

Authentication and user management

email

Send transactional emails

files

File upload and management

payments

Stripe checkout, subscriptions, and billing portal

flows

Trigger automation flows

functions

Call your site's backend functions, or an account function

serverFetch

Server-side proxy for secret API keys

pwa

Installable app — home-screen install + auto-update

content

Your published table rows as pages: one row and its SEO data by address

tenants

Companies, workspaces or households inside your site: create, invite, roles

realtime

Live events your backend functions publish to open pages

connectors

Inside a workspace app: the person’s connections, and connecting a new one

agents

Inside a workspace app: the person picks one of their AI agents for the app

permissions

Inside a workspace app: ask ahead for a permission the app declared

ui

Inside a workspace app: the platform’s own confirm dialog

entities - Table CRUD

Access your database tables dynamically. Use table names exactly as they appear in your database.

A site reads the tables of its one linked base. entities.SomeTable for a table that lives in another base behaves exactly like a table that does not exist. For another base's data, call an account function with functions.invokeAccount (below).

List All Rows
const tasks = await serenities.entities.Tasks.list();
// Returns: [{ id, Title, Status, ... }, ...]

// With sorting, limit, and offset
const recent = await serenities.entities.Tasks.list('-createdAt', 50, 0);
// Params: sort (prefix - for desc), limit (default 100, max 1000), offset (default 0, at most 10,000)

// Deeper ("load more"): sorted by createdAt or updatedAt, the rows carry rows.nextCursor (null on the last page)
const more = recent.nextCursor ? await serenities.entities.Tasks.list('-createdAt', 50, 0, { cursor: recent.nextCursor }) : [];
// filter(filters, { sort, limit, cursor }) takes it the same way
Create
const result = await serenities.entities.Tasks.create({
  Title: 'New Task',
  Status: 'pending',
  Priority: 'high'
});
// Returns: { success: true, id: 'new-row-id' }
Update
await serenities.entities.Tasks.update('row-id', {
  Status: 'completed'
});
// Returns: { success: true }
Delete
await serenities.entities.Tasks.delete('row-id');
// Returns: { success: true }
Get Single Row
const task = await serenities.entities.Tasks.get('row-id');
// Returns: { id, Title, Status, Priority, _linked: { ... } }

entities - Filtering

Filter rows with equality checks or operators. All conditions are combined with AND.

Simple Equality
const completed = await serenities.entities.Tasks.filter({
  Status: 'completed'
});
Multiple Conditions (AND)
const urgentOpen = await serenities.entities.Tasks.filter({
  Status: 'open',
  Priority: 'high',
});
With Operators
const results = await serenities.entities.Products.filter({
  Price: { $gt: 10, $lte: 100 },
  Category: { $in: ['Electronics', 'Books'] },
  Name: { $contains: 'Pro' },
});
With Sort / Limit / Offset
const recent = await serenities.entities.Tasks.filter(
  { Status: 'open' },
  { sort: '-createdAt', limit: 20, offset: 0 }
);

Available Operators

OperatorDescriptionExample
$eqEquals{ Status: { $eq: "done" } }
$neNot equals{ Status: { $ne: "" } }
$gtGreater than{ Price: { $gt: 10 } }
$gteGreater or equal{ Price: { $gte: 10 } }
$ltLess than{ Price: { $lt: 100 } }
$lteLess or equal{ Price: { $lte: 100 } }
$containsString contains{ Name: { $contains: "Pro" } }
$inValue in array{ Status: { $in: ["a", "b"] } }
$isEmptyField is empty/null{ Notes: { $isEmpty: true } }
$isNotEmptyField has value{ Title: { $isNotEmpty: true } }

entities - Linked Records (Relations)

Work with linked records between tables. Rows with link fields automatically include a _linked property with display values.

Auto-enriched _linked
const task = await serenities.entities.Tasks.get('row-id');
// task._linked = {
//   Project: [{ id: 'proj1', display: 'Website Redesign' }],
//   Assignee: [{ id: 'user1', display: 'John' }],
// }

// Also included in list() and filter() responses
//
// One request follows at most 5,000 links in all. When the rows asked for have more,
// _linked holds only the first 5,000 and the answer says so: get() returns the row with
// _linkedTruncated: true, and the data API's list answer has linkedTruncated: true beside rows.
// To page through every link of one row, use getLinked() below.
Link Rows Together
await serenities.entities.Tasks.link('task-id', 'Project', ['proj1', 'proj2']);
// Returns: { success: true, linked: 2 }
// At most 1,000 ids a call; for more, split the list into several calls.
Unlink Rows
await serenities.entities.Tasks.unlink('task-id', 'Project', ['proj2']);
// Returns: { success: true, unlinked: 1 }
// At most 1,000 ids a call, the same.
Get Linked Rows (Paginated)
const { rows, total, hasMore } = await serenities.entities.Tasks.getLinked(
  'task-id',
  'Project',
  { limit: 50, offset: 0 }
);
// rows = [{ id, Name, Status, ... }] — full target row data

user - Authentication

Get Current User
const result = await serenities.user.me();
// Returns: { user: { id, email, name, role, profileData, emailVerified, createdAt } }
// Returns: null if not logged in
const currentUser = result?.user;
Login
// Redirect to hosted login page
serenities.user.login();
serenities.user.login('/dashboard');  // with redirect after login

// Login with credentials (for custom login forms)
const result = await serenities.user.loginWithCredentials(email, password);
// Returns: { success: true, token: '...' }
Sign Up
// 3 params: email, password, data object (name + custom profile fields)
const result = await serenities.user.signup(email, password, {
  name: 'John Doe',
  company: 'Acme Inc',
});
// Returns: { success: true, user: { id, email, name, role } }
//
// A profile field that one of the site's access rules reads (a row, page, file or function rule,
// a tenant's create or join rule, or a secret's use rule) is the site owner's to set. A visitor
// who sends a different value for it is refused (403, the answer says the field can only be set by
// the site's owner) and nothing is saved; sending the value they already have, or a form's empty
// default, is ignored.
// Fields no rule reads stay the visitor's own.
Who Uses This Site
// 'individual' (default), 'multiTenant', or null when the site can't be reached (signed in or not)
const kind = await serenities.user.siteUsers();

// On a multi-tenant site each sign-up gets its own tenant and is its tenant admin:
// Returns: { success: true, user: {...}, tenant: { id, name } }
// A tenant's own customer signs up with no tenant:
await serenities.user.signup(email, password, { name, tenant: 'none' });
// Returns: { success: true, user: {...}, tenant: null }
Update Profile
await serenities.user.update({ name: 'New Name', company: 'New Company' });
// Returns: { success: true, user: { id, email, name, role, profileData } }
// The same rule as sign-up: a field an access rule reads is the owner's to change.
Logout
await serenities.user.logout();
// Clears token and reloads page
Password Reset & Email Verification
// Password reset flow
await serenities.user.forgotPassword(email);
await serenities.user.resetPassword(token, newPassword);

// Email verification
await serenities.user.verifyEmail(token);
await serenities.user.resendVerification(email);

// Back to the page that sent them to sign in: this page's ?return_to= when it is a path on your
// site ('/pay'), else the fallback (default null). signup and resendVerification send it themselves,
// so the verification email brings the member back too.
navigate(serenities.user.returnTo('/'));

email - Send Emails

await serenities.email.send({
  to: 'user@example.com',
  subject: 'Welcome!',
  body: '<h1>Hello</h1><p>Welcome to our app!</p>'
});

files - File Management

Upload
// Upload a File object (e.g., from <input type="file">)
// Default access: uploader + app owner can read
const result = await serenities.files.upload(fileObj);
// Returns: { success: true, file: { id, name, mimeType, size } }

// Upload with custom access rules — no follow-up call needed
await serenities.files.upload(fileObj, {
  accessRules: {
    read: [
      { type: 'creator' },                       // uploader can read
      { type: 'has_role', role: 'admin' },       // any admin can read
    ],
    delete: [{ type: 'creator' }],
  },
});

// Public file: "Anyone on this site" (always say the level; scope: 'everywhere' opens it through every site and its link)
await serenities.files.upload(fileObj, {
  accessRules: { read: [{ type: 'public', scope: 'home' }] },
});
List / Get / Delete
// List all files
const files = await serenities.files.list();

// Get file by ID
const file = await serenities.files.get('file-id');

// Delete file
await serenities.files.delete('file-id');

payments - Stripe Integration

Plans, invoices and plan changes
// The offers the site sells, each with entitlementKeys (the accesses buying it gives)
const offers = await serenities.payments.offers();

// Checkout goes to Stripe, or to another provider the owner switched on
await serenities.payments.checkout('pro'); // or { provider: 'pesapal' }

// The member's own accounts and invoices
const { accounts, invoices } = await serenities.payments.invoices();
await serenities.payments.payInvoice(invoice.id); // pay one open invoice in full

// Move between plans in the same plan group
await serenities.payments.changePlan(account.id, 'studio-plus'); // one of account.canChangeTo
await serenities.payments.cancelPlanChange(account.id);
Checkout & Products
// List available products
const products = await serenities.payments.listProducts();

// Create checkout session
const { url } = await serenities.payments.createCheckoutSession({
  priceId: 'price_xxxxx',
  successUrl: '/success',
  cancelUrl: '/cancel'
});
window.location.href = url;
Subscriptions & Billing Portal
// Get current user's subscription
const subscription = await serenities.payments.getSubscription();

// Open Stripe billing portal (manage subscription, update payment method)
const { url } = await serenities.payments.createPortalSession({
  returnUrl: '/settings'
});
window.location.href = url;

content - Published rows as pages

A table bound to your site (from the AI chat or MCP) turns its published rows into pages, such as a blog. Only the fields you mapped come back, with the page's SEO data. A draft, or an address no row gives, answers null.

const post = await serenities.content.get({ path: '/blog/hello-world' });
// → { row: { slug, title, description, body, imageAlt, tags, featured, readTime, … },
//     seo: { title, description, canonical, ogImage, noindex } }   or null

seo.ogImage is always a full address (or null), so link previews and search engines can load it. On a post preview link (the dashboard's Preview opens the post's address with ?preview=), the same call shows the post as it is now, a draft too, while the link is valid (10 minutes); you write nothing extra for it.

With the site's blog turned on, the blog list page reads one page of posts at a time: published posts only, newest first, without their body. hasMore says whether a next page exists. featured: true lists only the featured posts; readTime is the minutes to read, worked out from the body. A site with no blog at that address answers null. Both answers about the site's blog also carry blog, the blog's public settings for the page to show: listHeading, listIntro, ctaHeading,ctaText, ctaLink, twitterHandle (each left out when not set),categories, perPage and rss.

const list = await serenities.content.list({ path: '/blog', page: 1, perPage: 10, category: 'news', tag: 'launch' });
// → { rows: [{ path, slug, title, description, image, imageAlt, publishedAt, author, category, tags, featured, readTime }],
//     page: 1, hasMore: true,
//     blog: { listHeading, listIntro, ctaHeading, ctaText, ctaLink, twitterHandle, categories, perPage, rss } }   or null

tenants - Companies inside your site

Tenants are the companies, workspaces or households your site's members belong to. You set up the tenant types and roles from the AI chat, MCP or the dashboard; page code works with the signed-in member's own tenants.

// The signed-in member's own tenants
const { items } = await serenities.tenants.mine();
// → [{ id, name, typeName, status, myRole, memberCount }, …]

// Make one, when your rule for that tenant type allows it; the member becomes its Admin
const company = await serenities.tenants.create({ typeId: COMPANY_TYPE_ID, name: 'Acme Ltd' });

// Invite a colleague by email (the tenant's Admin); they join only when they accept
await serenities.tenants.invite(company.id, 'pat@example.com');

// On the page the invite link opens (#invite=<token>)
const token = new URLSearchParams(location.hash.slice(1)).get('invite');
if (token) await serenities.tenants.acceptInvite(token);

// Members, roles and leaving
const members = await serenities.tenants.members(company.id);
const roles = await serenities.tenants.roles();
await serenities.tenants.leave(company.id);

realtime - Live events

A backend function publishes an event (ctx.realtime.publish) and every open page subscribed to that channel gets it. The SDK reconnects by itself. Keep events small and reload the real data when one arrives: around a reconnect an event can arrive twice or be missed.

useEffect(() => {
  const off = serenities.realtime.subscribe('chat:general', (event, data) => {
    if (event === 'message_created') setMessages((m) => [...m, data]);
  });
  return () => { off.then((fn) => fn && fn()); };
}, []);

flows - Automation

// Invoke a flow by name
const result = await serenities.flows.invoke('send-welcome-email', {
  userId: 'user-123',
  email: 'user@example.com'
});

A flow a page starts runs as your workspace and can read any of your bases, so return from its response node only what the visitor may see.

functions - Server-side logic

invoke returns the function's result directly and throws if it fails, so use try/catch. A function needs its own access rule: with no rule, site users are refused.

// A backend function of this site
const order = await serenities.functions.invoke('processOrder', { item: 'Widget', qty: 3 });

// An ACCOUNT function (More → Functions) — e.g. to use another base's data
const stats = await serenities.functions.invokeAccount('salesStats', { month: '2026-10' });

invokeAccount works only when all three are set on the function: this site is in its Site access, it has an execute rule that lets the caller in, and Who can run this function has Visitors on the site page (directly) ticked. It then sees only what the person calling may see, unless the Owner or an Admin switched on "Runs as Admin" for it.

serverFetch - Server-Side Proxy

Call external APIs that require secret keys. Use {{secret:NAME}} placeholders — they are filled in on the server, so secrets never reach the browser.

A visitor's call fills in a secret only for a host on that secret's Allowed hosts (Environment Variables → Edit hosts), for example api.openai.com. With no hosts, visitors' calls that use the secret are refused; your own preview still works.

// Call an external API using secret env vars
const data = await serenities.serverFetch(
  'https://api.openai.com/v1/chat/completions',
  {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer {{secret:OPENAI_API_KEY}}',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: [{ role: 'user', content: 'Hello!' }],
    }),
  }
);

Complete Example

A full React component showing authentication, CRUD, and filtering:

import React, { useState, useEffect } from 'react';
import serenities from '../api/sdk';

export default function TasksPage() {
  const [tasks, setTasks] = useState([]);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      // Check auth
      const result = await serenities.user.me();
      setUser(result?.user || null);

      // Load only open tasks using filter
      const openTasks = await serenities.entities.Tasks.filter(
        { Status: { $ne: 'completed' } },
        { sort: '-createdAt', limit: 50 }
      );
      setTasks(openTasks);
      setLoading(false);
    }
    loadData();
  }, []);

  const addTask = async (title) => {
    const result = await serenities.entities.Tasks.create({
      Title: title,
      Status: 'pending'
    });
    // Reload the list
    const updated = await serenities.entities.Tasks.filter(
      { Status: { $ne: 'completed' } },
      { sort: '-createdAt', limit: 50 }
    );
    setTasks(updated);
  };

  const completeTask = async (id) => {
    await serenities.entities.Tasks.update(id, { Status: 'completed' });
    setTasks(tasks.filter(t => t.id !== id));
  };

  const deleteTask = async (id) => {
    await serenities.entities.Tasks.delete(id);
    setTasks(tasks.filter(t => t.id !== id));
  };

  if (loading) return <div className="p-8">Loading...</div>;

  if (!user) {
    return (
      <div className="p-8 text-center">
        <p className="mb-4">Please log in to view tasks</p>
        <button
          onClick={() => serenities.user.login()}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          Log In
        </button>
      </div>
    );
  }

  return (
    <div className="p-8 max-w-2xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">My Tasks</h1>
      {/* ... rest of UI */}
    </div>
  );
}

pwa - Installable app

Every published app is automatically a Progressive Web App — members can install it to their home screen and run it full-screen on Android, iOS, and desktop. Nothing to set up: the icon, name, and colors come from your app icon and brand kit. Apps also auto-update — when you publish a new version, installed apps quietly load it without a manual refresh, while live data always stays current.

Automatic install banner

A subtle “Install this app” banner appears on its own — Android shows the native install prompt, iOS shows an “Add to Home Screen” hint. Members can dismiss it. You don’t have to add anything for this to work.

Trigger install from your own button
// Show your own "Install" button, then on click:
if (serenities.pwa.canInstall()) {
  serenities.pwa.promptInstall();
}
Check install state
serenities.pwa.isInstalled();  // true when running as an installed app
serenities.pwa.canInstall();   // true when it can be installed right now