Devmachinist /Docs
Sign in Start
All docs

JavaScript client

When a project is connected to an API, Devmachinist writes a JavaScript client into the project's src/api/ folder. It wraps the Data API in plain functions and React hooks, and, when the API has sign-in, adds an auth provider, sign-in components and upload helpers. Your pages and components import from these files like any other module.

The generated files #

FileWritten whenContains
src/api/<slug>.jsthe API is connectedan object and two hooks per model, request, BASE, TOKEN_KEY, deviceId
src/api/<slug>-auth.jsxthe API has sign-in turned onAuthProvider, useAuth, Auth, NoAuth, AuthView, LoginForm, AccountSettings, RobotCheck, hasRole, uploads, memberships, page views, integrations
src/api/index.jsany API is connectedre-exports every <slug>.js (not the auth files)
src/main.jsxsign-in is onwraps <App /> in that API's <AuthProvider>

<slug> comes from the API's name: an API called "My Shop" gives src/api/my-shop.js and src/api/my-shop-auth.jsx. The examples below use an API called "Shop".

These files are managed. Devmachinist rewrites them when you connect or disconnect an API, press Sync, when the AI changes the project's API, and every time the project's preview starts, a check runs or the site is published, so edits to them are lost. Put your own helpers in src/lib/ and import the client from there.

Connect an API in the API tab under Use in App. After you change models or rules in the API tab, press Sync there (or restart the preview) so the client picks up new models and roles.

Importing #

Pages live in src/pages/ and components in src/components/, so both import the client one folder up:

jsx
import { Products, useProducts, useProduct } from '../api/shop.js'
import { useAuth, Auth, NoAuth, LoginForm } from '../api/shop-auth.jsx'
import { routeParam } from '../site.js'

The app is already wrapped in <AuthProvider> in src/main.jsx. Never add another one. If a project connects several APIs with sign-in, the provider belongs to the one the project uses for sign-in (set by its template or the AI, else the first connected API with sign-in), and only that file's useAuth() sees the signed-in person.

How requests are made #

Both files send requests to the same base URL:

js
export const BASE = (globalThis.__PB_API_ORIGIN__ || '') + '/_api/mhx3q9zk4f7p2a'
export const TOKEN_KEY = 'pb_auth_mhx3q9zk4f7p2a'
  • Address: relative on the web, so a published site calls its own origin. Native exports set window.__PB_API_ORIGIN__ to the server's address before the app loads.
  • Token: after sign-in the token is kept in localStorage under pb_auth_<apiId>. Every request from either file sends it as Authorization: Bearer <token>, so data calls are signed in automatically.
  • Device id: every request sends X-PB-Device, a random id kept in localStorage as pb_device, which the free-read meter uses for signed-out readers.
  • Errors: a response that isn't 2xx throws an Error whose message is the server's error text, such as Authentication required, or HTTP 500.

Model objects #

For every model, src/api/<slug>.js exports an object named after the model in the plural, a list hook and a single-row hook. Names are the model name in PascalCase; the plural adds s, es after s, x, z, ch or sh, and turns a final consonant + y into ies.

ModelObjectList hookRow hook
ProductProductsuseProducts(query)useProduct(id)
CategoryCategoriesuseCategories(query)useCategory(id)
AddressAddressesuseAddresses(query)useAddress(id)
blog_postBlogPostsuseBlogPosts(query)useBlogPost(id)

Each object has five methods. All return promises.

MethodRequestResolves to
list(query)GET /<model>?…{ data, total, page, limit, pageCount }
get(id)GET /<model>/<id>the row
create(data)POST /<model>the stored row, with its id
update(id, data)PATCH /<model>/<id>the whole row after the change
remove(id)DELETE /<model>/<id>{ ok: true, deleted }

query is an object of list parameters: field filters (price_lt, status_in…), _q, _sort, _order, _limit, _page, _offset and _expand. Keys whose value is null, undefined or '' are left out, which makes optional filters easy.

js
import { Products } from '../api/shop.js'

const { data, total } = await Products.list({ category_id: 2, _q: search || undefined, _sort: 'price', _limit: 24 })
const one = await Products.get(5)
const made = await Products.create({ name: 'Clay mug', price: 18, stock: 40 })
await Products.update(made.id, { stock: 39 })
await Products.remove(made.id)

List hook #

useProducts(query) loads a list when the component mounts and again whenever query changes (it compares JSON.stringify(query)).

ReturnsMeaning
datathe rows, [] until loaded
meta{ total, page, pageCount }
loadingtrue while a request runs
errorthe error message as a string, or null
reload()fetch again with the same query

The hook doesn't refetch when someone signs in or out. If a list depends on who is signed in, call reload(), or put something that changes into the query, such as { user_id: user?.id } on an owner model (the server sets that filter itself anyway).

Row hook #

useProduct(id) loads one row, and again when id changes. It returns { data, loading, error, reload }. With id of null or undefined it fetches nothing and data stays null.

Pass null, not an empty string, when there's no id. useProduct('') requests the model's path without an id, which is the list.

request #

For anything the model objects don't cover, request(method, path, body) calls any path under the API with the same headers and error handling:

js
import { request } from '../api/shop.js'

const cheap = await request('GET', '/product?price_lte=10&_expand=category_id')
const shipping = await request('GET', '/store')

Example: a list page #

jsx
// src/pages/Shop.jsx
import { useState } from 'react'
import { useProducts } from '../api/shop.js'

export default function Shop() {
  const [q, setQ] = useState('')
  const [page, setPage] = useState(1)
  const { data: products, meta, loading, error } = useProducts({ _q: q || undefined, _page: page, _limit: 12, _sort: 'id', _order: 'desc' })

  return (
    <main className="mx-auto max-w-5xl p-6">
      <input value={q} onChange={e => { setQ(e.target.value); setPage(1) }} placeholder="Search" className="w-full rounded-lg border px-3 py-2" />
      {error && <p className="mt-4 text-red-600">{error}</p>}
      {loading && <p className="mt-4 text-slate-500">Loading…</p>}
      <ul className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
        {products.map(p => (
          <li key={p.id} className="rounded-xl border p-4">
            <a href={`#product/${p.id}`} className="font-semibold">{p.name}</a>
            <p className="text-slate-600">${p.price}</p>
          </li>
        ))}
      </ul>
      <div className="mt-6 flex gap-2">
        <button disabled={page <= 1} onClick={() => setPage(page - 1)}>Previous</button>
        <span>{page} / {meta.pageCount || 1}</span>
        <button disabled={page >= meta.pageCount} onClick={() => setPage(page + 1)}>Next</button>
      </div>
    </main>
  )
}

Example: a detail page #

Pages use hash routing: #product/3 opens the product page, and the page reads 3 itself with routeParam(1) from src/site.js. Moving from #product/3 to #product/4 keeps the same page on screen, so listen for hashchange to pick up the new id.

jsx
// src/pages/Product.jsx
import { useEffect, useState } from 'react'
import { routeParam } from '../site.js'
import { useProduct } from '../api/shop.js'

const idFromRoute = () => routeParam(1) || null

export default function Product() {
  const [id, setId] = useState(idFromRoute)
  useEffect(() => {
    const onHash = () => setId(idFromRoute())
    window.addEventListener('hashchange', onHash)
    return () => window.removeEventListener('hashchange', onHash)
  }, [])
  const { data: product, loading, error } = useProduct(id)

  if (!id) return <p className="p-6">No product chosen.</p>
  if (loading) return <p className="p-6">Loading…</p>
  if (error) return <p className="p-6 text-red-600">{error}</p>
  return (
    <article className="mx-auto max-w-2xl p-6">
      <h1 className="text-3xl font-bold">{product.name}</h1>
      <p className="mt-2 text-xl">${product.price}</p>
    </article>
  )
}

Example: a form that adds a row #

The model's create rule decides who may add rows; a contact form's Message model usually has create public and read and write admin.

jsx
// src/components/ContactForm.jsx
import { useState } from 'react'
import { Messages } from '../api/shop.js'

export default function ContactForm() {
  const [form, setForm] = useState({ name: '', email: '', body: '' })
  const [state, setState] = useState({ busy: false, error: null, sent: false })
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }))

  const submit = async (e) => {
    e.preventDefault()
    setState({ busy: true, error: null, sent: false })
    try {
      await Messages.create(form)
      setForm({ name: '', email: '', body: '' })
      setState({ busy: false, error: null, sent: true })
    } catch (err) {
      setState({ busy: false, error: err.message, sent: false })
    }
  }

  return (
    <form onSubmit={submit} className="space-y-3">
      <input required value={form.name} onChange={set('name')} placeholder="Name" className="w-full rounded-lg border px-3 py-2" />
      <input required type="email" value={form.email} onChange={set('email')} placeholder="Email" className="w-full rounded-lg border px-3 py-2" />
      <textarea required value={form.body} onChange={set('body')} placeholder="Message" className="w-full rounded-lg border px-3 py-2" />
      {state.error && <p className="text-red-600">{state.error}</p>}
      {state.sent && <p className="text-green-700">Thanks, we got it.</p>}
      <button disabled={state.busy} className="rounded-lg bg-slate-900 px-4 py-2 text-white">{state.busy ? 'Sending…' : 'Send'}</button>
    </form>
  )
}

The sign-in client #

src/api/<slug>-auth.jsx exists only when sign-in is on for the API. It reads the site's name and logo from src/site.js, so it works inside the project it was written for. The server routes it calls are in App sign-in.

useAuth #

useAuth() never returns null. Outside an <AuthProvider> it returns a signed-out stand-in whose login and register throw an error saying the provider is missing.

FieldWhat it is
userthe signed-in account, or null
loadingtrue until the stored token has been checked on load
providersthe external sign-in providers that are on: [{ id, type, label }]
login(email, password, robot)signs in, stores the token, resolves to the user
register(email, password, name, robot)creates an account (password 6 characters or more), signs in, resolves to the user
logout()forgets the token on this device
loginWithProvider(id)sends the browser to that provider; the token comes back in the address and is stored on load
refresh()checks the token and reloads user and providers
updateProfile({ name })changes the person's name, resolves to the user
changePassword(current, password)new password of 8 characters or more; a new token is stored
deleteAccount({ password, confirm })deletes the account with its password (or confirm: 'delete' when it has none), then signs out

The user object:

FieldExample
id"mhx40b1c9a2kd3" (text)
email"ada@example.com"
name"Ada"
role"user", "admin" or a custom role
provider"password" or a provider id
membertrue while a membership is active
memberUntilwhen a membership ends, or null
hasPasswordfalse for accounts made through a provider
createdAtwhen the account was made
metadataextra provider data, or null

Prefer <LoginForm /> to calling login and register yourself: it includes the robot check, which the server requires when the API has it on.

AuthView, Auth and NoAuth #

ComponentShows its children
<AuthView fallback={…}>once sign-in has loaded; until then fallback, or a small "Loading…"
<Auth role={[…]} fallback={…}>to a signed-in person with one of the roles. A signed-in person without one sees fallback; signed-out visitors see nothing
<NoAuth>to signed-out visitors only

<Auth> with no role means any signed-in account. role={['admin']} means admins only. A custom role, such as role={['editor']}, means accounts with that role and admins. Auth and NoAuth render nothing while loading, so wrap them in <AuthView> to avoid an empty flash.

hasRole and CUSTOM_ROLES #

hasRole(user, roles) is the same check as <Auth> for plain code: false without a user; 'admin' matches admins; a role listed in CUSTOM_ROLES (the API's own roles from API → Auth → Roles) matches that role and admins; any other name, 'user' included, matches every signed-in account. roles may be a string or an array.

js
import { useAuth, hasRole } from '../api/shop-auth.jsx'

const { user } = useAuth()
const columns = hasRole(user, ['admin']) ? ['name', 'price', 'stock', 'cost'] : ['name', 'price']

These checks only decide what the page shows. What people may read and change is enforced by the API's access rules.

LoginForm #

A complete sign-in and sign-up card in the site's brand colors, with provider buttons, the robot check and error messages.

PropDefaultMeaning
title"Welcome back" or "Create your account"heading
subtitle"Sign in to <site name>" or similarline under the heading
initialMode'login''login' or 'register'
onSuccess(user)nonecalled after signing in or up

RobotCheck #

<RobotCheck purpose="login" onChange={setRobot} resetKey={n} /> is the "I'm not a robot" button for your own forms. When the API doesn't ask for a check, it renders nothing and calls onChange(''). Otherwise onChange(null) until it's solved and then onChange(token); pass the token as the robot argument of login or register. purpose is 'login' or 'signup', and changing resetKey starts over (do that after a failed attempt).

AccountSettings #

<AccountSettings onDeleted={…} /> lets the signed-in person change their name and password and delete their account. Put it inside <Auth>. After a deletion it calls onDeleted, or goes to #home.

Example: a page for signed-in people #

jsx
// src/pages/Account.jsx
import { AuthView, Auth, NoAuth, LoginForm, AccountSettings, useAuth } from '../api/shop-auth.jsx'
import { useOrders } from '../api/shop.js'

function MyOrders() {
  const { user } = useAuth()
  // Order has read: owner, so the server returns only this person's orders.
  const { data: orders, loading } = useOrders({ user_id: user.id, _sort: 'id', _order: 'desc' })
  if (loading) return <p>Loading…</p>
  return (
    <ul className="divide-y">
      {orders.map(o => <li key={o.id} className="py-2">Order #{o.id}: {o.status}</li>)}
    </ul>
  )
}

export default function Account() {
  const { user, logout } = useAuth()
  return (
    <AuthView>
      <Auth>
        <main className="mx-auto max-w-2xl space-y-6 p-6">
          <h1 className="text-2xl font-bold">Hi {user?.name || user?.email}</h1>
          <MyOrders />
          <AccountSettings />
          <button onClick={() => { logout(); window.location.hash = '#home' }}>Sign out</button>
        </main>
      </Auth>
      <NoAuth><LoginForm /></NoAuth>
    </AuthView>
  )
}

You can also limit a whole page to some roles in More → Pages: the generated App.jsx then shows the site's login page to signed-out visitors and a "This page isn't for your account" note to accounts without the role.

Example: an admin-only section #

jsx
// src/components/StockAdmin.jsx
import { Auth } from '../api/shop-auth.jsx'
import { Products, useProducts } from '../api/shop.js'

export default function StockAdmin() {
  return (
    <Auth role={['admin']} fallback={<p>You need an admin account.</p>}>
      <LowStock />
    </Auth>
  )
}

function LowStock() {
  const { data, reload } = useProducts({ stock_lte: 3, _sort: 'stock' })
  const restock = async (p) => { await Products.update(p.id, { stock: p.stock + 10 }); reload() }
  return (
    <ul>
      {data.map(p => (
        <li key={p.id} className="flex justify-between py-1">
          {p.name}: {p.stock} left
          <button onClick={() => restock(p)}>+10</button>
        </li>
      ))}
    </ul>
  )
}

The write rule on Product must be admin for this to be safe: hiding the button doesn't stop anyone calling the API.

Files #

The sign-in client stores files in the API's file storage. Admins can upload; other accounts only when API → Auth → Who can upload files allows them. Accepted files, sizes, access and the routes behind these helpers are in Files.

ExportWhat it does
uploadFile(file, { access })uploads a File or Blob; resolves to { ok, name, url, size, type, access }. access is 'public' (default), 'private', 'users' or a custom role
isPrivateFile(url)true for a file that needs sign-in to open
useFileUrl(url){ url, loading, error }: a URL any <img>, <video>, <audio> or <a> can use; private files are fetched with the visitor's token
<FileImage src={url} … />an <img> that works for public and private files; other props go to the <img>
downloadFile(url, filename)saves a file, with the visitor's token when it's private
files.list({ mine }){ ok, files }: admins get every file (or their own with mine: true), others their own
files.remove(name)deletes a file you uploaded (admins: any file)

Save the returned url in a url or string field. A plain <img src> can't open a private file, because the browser won't send the token; use <FileImage> or useFileUrl.

Example: an upload #

jsx
// src/components/ProductPhoto.jsx
import { useState } from 'react'
import { uploadFile, FileImage } from '../api/shop-auth.jsx'
import { Products } from '../api/shop.js'

export default function ProductPhoto({ product, onSaved }) {
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState(null)

  const pick = async (e) => {
    const file = e.target.files?.[0]
    if (!file) return
    setBusy(true); setError(null)
    try {
      const { url } = await uploadFile(file, { access: 'public' })
      onSaved(await Products.update(product.id, { image: url }))
    } catch (err) {
      setError(err.message)
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="space-y-2">
      {product.image && <FileImage src={product.image} alt={product.name} className="h-40 w-40 rounded-lg object-cover" />}
      <input type="file" accept="image/*" onChange={pick} disabled={busy} />
      {error && <p className="text-red-600">{error}</p>}
    </div>
  )
}

Memberships #

useMembership() reads the API's membership plan and the visitor's status from GET /membership.

ReturnsMeaning
info{ enabled, payments, name, price, interval, currency, freeReads, perks, signedIn, isAdmin, member, status, until, cancelAt, comp }, or null
isMembertrue while the visitor's membership is active
loadingtrue while info is null
subscribe()starts Stripe Checkout and sends the browser there
cancel(), resume()cancel at the end of the period, or undo that
refresh()reload info

It reloads when the signed-in person changes. Reads of the paid model come back with _locked and _meter for non-members; see metered reads and Payments.

jsx
import { useMembership } from '../api/shop-auth.jsx'
import { usePost } from '../api/shop.js'

function PostBody({ id }) {
  const { data: post } = usePost(id)
  const { subscribe, info } = useMembership()
  if (!post) return null
  if (post._locked) return <button onClick={subscribe}>Become a member for {info?.price}/{info?.interval}</button>
  return <div>{post.body}</div>
}

Page views and device id #

usePageViews() sends one cookieless page view to POST /track when the app loads and another on every hashchange. Call it once, in a component that's on every page such as the nav. Admins see the report at GET /admin/traffic (the store and blog admin portals show it).

deviceId() returns the random id stored as pb_device, the same one sent as X-PB-Device. Both files export it.

getToken(), from the auth file, returns the stored token or null, for calling /_api with fetch yourself.

Posting to linked accounts #

When the project's owner has linked a Facebook Page, Instagram, Threads, X or LinkedIn account in the builder and pressed Let my app post, the app's admins can post through it. Tokens stay on the server.

js
import { integrations } from '../api/shop-auth.jsx'

const linked = await integrations.list()   // [{ connector: 'facebook', label: 'Facebook', account: … }]
const { url } = await integrations.post('facebook', { text: 'New arrivals are in', link: 'https://example.com/#shop' })

post(connector, { text, link, image, target }) resolves to { ok: true, url, … } and throws with the server's message otherwise. Both calls need an admin's token: other accounts get 401 or 403. Instagram needs an image. Each linked account can post at most 30 times an hour. Use these only in admin screens.

Routes and src/site.js #

Every project has a managed src/site.js with the brand, the page list and route helpers. Don't edit it; it's rewritten when pages or the brand change.

ExportReturns
site{ name, tagline, logo, colors, pages, allPages }; each page is { name, slug, label, href }, plus roles on pages limited to some roles
pagesFor(user)the menu for this visitor: every page without roles, plus role pages they may open
route()the current route without the #, such as product/3
routeParam(i)part i of the route, decoded, or ''; routeParam(1) is 3 for product/3
currentSlug()the page slug, such as product, or the first page's slug

Read ids with routeParam, never from window.location.hash. In the builder's preview the route is the hash (#product/3). On a published site the page may be at a real address such as /product/3/, and route() returns product/3 either way.

pagesFor(user) shows a page with roles when one of them is user and someone is signed in, when the visitor is an admin, or when the visitor's role is listed. A nav uses it with useAuth():

jsx
import { site, pagesFor, currentSlug } from '../site.js'
import { useAuth } from '../api/shop-auth.jsx'

export default function SiteNav() {
  const { user } = useAuth()
  return (
    <nav className="flex gap-4 p-4">
      <strong>{site.name}</strong>
      {pagesFor(user).map(p => (
        <a key={p.slug} href={p.href} className={currentSlug() === p.slug ? 'font-semibold' : ''}>{p.label}</a>
      ))}
    </nav>
  )
}