vibes.diy Make an app → Discord
creator docs · reference · generated

Squarespace orders — read a seller's own store: new orders and each customer's totals

This is the same document the Vibes code generator reads when it builds apps — rendered from prompts/pkg/llms/squarespace.md on every deploy, so it can't drift from what the platform actually does. Read it from your terminal any time with npx vibes-diy skills.

When someone who sells on Squarespace asks for an app over their store — "my Squarespace orders", "the orders to pack from my Squarespace shop", "which Squarespace customers order the most" — build it on the store's own Commerce API key from backend.js. The owner pastes the key into the vibe's Secrets once, and backend.js reads their orders and customers with it on a schedule. This page reads; the owner keeps fulfilling, refunding and editing products in Squarespace, where they already do.

This is a backend.js feature, and the key is the owner's own (the owner-key rules that load with this page). This page is the recipe that keeps every Squarespace call on the server, copies the store's orders into the app's own records, and keeps those records the owner's alone.

1. The setup item: the owner's Squarespace API key

The Squarespace item is the API key: the backend answers missing-key while ctx.secrets.SQUARESPACE_API_KEY is absent, and its steps link the Squarespace account dashboard by URL and name SQUARESPACE_API_KEY in so many words.

The Setup surface the item lands on (the owner-only entry in the app's navigation, the verdict from /setup, the re-read on focus) is the use-vibe docs' Some apps need setup before they work; this recipe contributes one item to it. The steps use Squarespace's own words:

  1. Open https://account.squarespace.com, sign in, and open the site you sell on.
  2. Go to Settings, scroll to Advanced, open Developer API Keys and press Generate Key. Give it any name, such as this app's.
  3. Tick Orders and Profiles, each with Read Only, and save. Copy the key now: Squarespace shows it only once.
  4. Save it under Secrets on this vibe's Settings tab as SQUARESPACE_API_KEY, then come back: the owner-key steps every item ends with.

API keys need the site's Commerce Advanced plan; the Setup screen says so beside step 2, so an owner on another plan learns it before they look for the page. The item is done when the key is saved and Squarespace answered the backend's first read of the orders list. A key Squarespace refuses leaves the item To do with the status it answered.

2. Squarespace stays on the server

Every Squarespace request is made in backend.js with ctx.fetch and ctx.secrets.SQUARESPACE_API_KEY, with a User-Agent header naming the app; App.jsx never calls api.squarespace.com.

api.squarespace.com sends no CORS headers, so the browser could not reach it anyway. Each request carries Authorization: Bearer <key> and a User-Agent (Squarespace rejects a request without one). The host is https://api.squarespace.com, and every path starts with /1.0/.

backend.js calls only the three Squarespace reads the platform admits: GET /1.0/commerce/orders, GET /1.0/commerce/orders/{id} and GET /1.0/profiles.

Marking an order fulfilled, importing orders, products, inventory and webhook subscriptions stay in Squarespace. Webhooks need OAuth, which an API key is not, so the app learns about new orders by asking on a schedule.

3. A scheduled poll copies new and changed orders in

A scheduled poll every 15 minutes asks for the orders modified since the last poll and saves one record per Squarespace order, keyed by its order id, so a changed order replaces its own record.

The orders list takes either a time window or a cursor, never both:

  • The first page names the window: modifiedAfter and modifiedBefore together, each an ISO 8601 UTC time. One without the other is refused.
  • Every later page passes cursor alone: the pagination.nextPageCursor of the page before it, while pagination.hasNextPage is true.
  • A page holds up to 50 orders, in result.
js// The window opens where the last poll's window closed; the first poll looks back 30 days.
const params = `modifiedAfter=${encodeURIComponent(after)}&modifiedBefore=${encodeURIComponent(before)}`;
let page = await squarespace(ctx, `/1.0/commerce/orders?${params}`);
let cursor = null;
while (page.ok) {
  for (const o of page.body.result ?? []) await putIfChanged(ctx, orderRecord(o));
  if (!page.body.pagination?.hasNextPage) break;
  const next = page.body.pagination.nextPageCursor;
  // No new cursor: the poll stops as failed, so the watermark stays put.
  if (!next || next === cursor) {
    page = { ok: false, reason: "squarespace", message: "Squarespace sent no new page cursor." };
    break;
  }
  cursor = next;
  page = await squarespace(ctx, `/1.0/commerce/orders?cursor=${encodeURIComponent(cursor)}`);
}

The watermark is a sync record holding the modifiedBefore of the last poll that read every page. It moves only after the last page: a poll that stops early (a refused key, a 429 on an order page) leaves it where it was, and the next poll asks for the same window again. Saving is an upsert that writes only a record whose fields changed, so reading an order twice writes nothing, and a poll that finds no orders leaves the watermark alone and writes nothing at all.

An order record keeps what the app shows: orderNumber, createdOn, modifiedOn, fulfillmentStatus (PENDING, FULFILLED or CANCELED), the customer's email, each line's productName, quantity, sku and variantOptions, the shipping address, and grandTotal, a { currency, value } pair. Read value with Number(...): it is a decimal amount in the currency (49.99), never cents. Leave testmode orders out of the totals and show them marked test.

4. Each customer's totals come from Profiles

A customer's order count and lifetime spend come from their profile's transactionsSummary, looked up by email with GET /1.0/profiles?filter=email,

, and are never added up from the copied orders.

The copied orders reach back only as far as the first poll, while the profile counts every order the store ever took:

  • transactionsSummary.orderCount: how many orders.
  • transactionsSummary.totalOrderAmount: lifetime spend, { currency, value }.
  • transactionsSummary.lastOrderSubmittedOn and firstOrderSubmittedOn.

Squarespace computes that summary from the site asynchronously, so a customer's count can trail an order that just arrived by a poll or two. Say so beside the numbers (Totals from Squarespace, updated every 15 minutes). A saved order puts its customer's email on a re-read list, one sync record the poll reads by id. Each poll reads a few of them (20), oldest first, and keeps each for two hours of re-reads, so totals catch up even when no order changes and a busy first poll stays under the rate limit. The email goes into the query URL-encoded, and the profile that comes back is used only when its email matches the one asked for. Orders and customers join on the lower-cased email.

The Profiles API is in maintenance mode: Squarespace recommends its Contacts API for new work, and the platform admits Profiles today because it is the one that carries transactionsSummary.

5. Rate limits and errors keep their reason

Squarespace allows 300 requests a minute across its Commerce APIs and answers a 429 past that, with a one-minute cool-down. A poll that meets a 429 stops where it is, keeps its watermark, and stores backoffUntil on the sync record; the next tick reads it first and waits it out (the mirror section's A refusal pauses the mirror). It never retries in a loop.

Return { ok: false, reason, message } so the page can say why:

  • missing-key: the key is not saved yet. The owner sees the Setup item.
  • 401 or 403: Squarespace refused the key. The item reads To do, and the fix is a fresh key with Orders and Profiles set to Read Only.
  • 429: Squarespace asked us to slow down; the next poll picks up where this one stopped.

Wrap every route in try/catch and answer with a reason, because an uncaught throw reaches the page as a bare 500 that names nothing the owner can fix.

6. The records are the owner's alone

Orders carry customers' names, emails and addresses, so access.js takes every order, customer, sync and setup record from backend.js alone and grants them to the owner's role only. A visitor who opens the app sees the Setup verdict and nothing of the store.

Complete backend.js

The worked example is a packing station: the owner sees the orders still to pack, newest first, and each customer's order count and lifetime spend beside their order.

backend.js

js// A Squarespace store's orders and customer totals, read with the owner's own API key and copied
// into the app's records on a schedule. Read only: fulfilment stays in Squarespace.
export const config = {
  scheduled: { interval: "15m" },
};

const DB = "store";
const SYNC_ID = "sync:orders";
const RECHECK_ID = "sync:recheck";
const SETUP_ID = "setup:squarespace";
const HOST = "https://api.squarespace.com";
const FIRST_LOOK_BACK_MS = 30 * 24 * 60 * 60 * 1000; // the first poll copies the last 30 days
const RECHECK_MS = 2 * 60 * 60 * 1000; // a customer's totals are re-read for two hours after their order
const RECHECK_EVERY_MS = 10 * 60 * 1000; // at most one re-read per customer per poll
const PROFILE_READS_PER_POLL = 20; // keeps a big first poll well under 300 requests a minute
const RECHECK_MAX = 500;

function json(body, status = 200) {
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}

// One Squarespace read on the owner's store. The key rides only this request, and Squarespace
// rejects a request with no User-Agent.
async function squarespace(ctx, path) {
  const key = ctx.secrets.SQUARESPACE_API_KEY;
  if (!key) return { ok: false, reason: "missing-key" };
  const res = await ctx.fetch(`${HOST}${path}`, {
    method: "GET",
    headers: { authorization: `Bearer ${key}`, "user-agent": `vibes-diy ${ctx.appInfo.appSlug}` },
  });
  const out = await res.json().catch(() => null);
  if (res.status === 429) return { ok: false, reason: "rate-limited", status: 429, message: "Squarespace asked us to slow down." };
  if (!res.ok) return { ok: false, reason: res.status === 401 || res.status === 403 ? "unauthorized" : "squarespace", status: res.status, message: out?.message ?? `HTTP ${res.status}` };
  return { ok: true, body: out };
}

// A Squarespace amount is { currency, value } with value a decimal in the currency.
const amount = (m) => ({ currency: m?.currency ?? "USD", value: Number(m?.value ?? 0) });
const emailKey = (e) => String(e ?? "").trim().toLowerCase();

// A poll that changes nothing writes nothing: every field is compared (as JSON, so line items and
// totals count) with the stored record, and only a real change is put. No per-poll timestamps.
function unchanged(existing, next) {
  if (!existing) return false;
  return Object.keys(next).every((k) => JSON.stringify(existing[k]) === JSON.stringify(next[k]));
}
async function putIfChanged(ctx, next) {
  const existing = await ctx.db.get(next._id, { db: DB });
  if (unchanged(existing, next)) return false;
  await ctx.db.put(next, { db: DB, id: next._id });
  return true;
}

// The customer's totals, from their profile, looked up by email. The answer is matched against the
// email asked for, so a lookup that comes back with someone else never lands on this customer.
async function saveCustomer(ctx, email) {
  const r = await squarespace(ctx, `/1.0/profiles?filter=email,${encodeURIComponent(email)}`);
  if (!r.ok) return r;
  const p = (r.body.profiles ?? []).find((x) => emailKey(x.email) === email);
  if (!p) return { ok: true };
  const t = p.transactionsSummary ?? {};
  await putIfChanged(ctx, {
    _id: `customer-${p.id}`,
    type: "customer",
    email,
    name: [p.firstName, p.lastName].filter(Boolean).join(" "),
    orderCount: t.orderCount ?? 0,
    totalSpent: amount(t.totalOrderAmount),
    lastOrderOn: t.lastOrderSubmittedOn ?? null,
  });
  return { ok: true };
}

// The customers whose totals may trail a recent order, kept as one record the poll reads by id. Each
// is read at least once, then on each poll until `until`, a few per poll: Squarespace builds the
// summary asynchronously, and the totals catch up whether or not another order changes.
async function refreshCustomers(ctx, list) {
  const now = Date.now();
  const kept = [];
  let reads = 0;
  let stopped = null;
  for (const entry of [...list].sort((a, b) => a.next - b.next)) {
    if (stopped || reads >= PROFILE_READS_PER_POLL || entry.next > now) {
      kept.push(entry);
      continue;
    }
    reads += 1;
    const r = await saveCustomer(ctx, entry.email);
    if (!r.ok) {
      stopped = r; // a 429 or a refused key: stop here, and the rest wait for the next poll
      kept.push(entry);
    } else if (now < entry.until) {
      kept.push({ ...entry, next: now + RECHECK_EVERY_MS });
    }
  }
  // Past the cap, the entries due soonest stay and the ones furthest off drop.
  kept.sort((a, b) => a.next - b.next);
  await putIfChanged(ctx, { _id: RECHECK_ID, type: "sync", list: kept.slice(0, RECHECK_MAX) });
  return stopped ?? { ok: true };
}

// One record per Squarespace order, keyed by its id: a changed order replaces its own record.
function orderRecord(o) {
  return {
    _id: `order-${o.id}`,
    type: "order",
    squarespaceId: o.id,
    orderNumber: o.orderNumber,
    createdOn: o.createdOn,
    modifiedOn: o.modifiedOn,
    fulfillmentStatus: o.fulfillmentStatus,
    testmode: o.testmode === true,
    email: emailKey(o.customerEmail) || null,
    shipTo: o.shippingAddress ?? null,
    lines: (o.lineItems ?? []).map((l) => ({ name: l.productName, qty: l.quantity, sku: l.sku ?? null, options: l.variantOptions ?? [] })),
    total: amount(o.grandTotal),
  };
}

// Copy every order modified since the last complete poll. The watermark moves only once every page
// is read, so a poll that stops early asks for the same window next time. Profile reads wait on the
// re-read list instead of running once per order, so a busy first poll never meets Squarespace's
// limit halfway through its pages.
async function poll(ctx) {
  const sync = await ctx.db.get(SYNC_ID, { db: DB });
  const recheck = await ctx.db.get(RECHECK_ID, { db: DB });
  const queue = new Map((recheck?.list ?? []).map((e) => [e.email, e]));
  const after = sync?.modifiedBefore ?? new Date(Date.now() - FIRST_LOOK_BACK_MS).toISOString();
  const before = new Date().toISOString();
  const params = `modifiedAfter=${encodeURIComponent(after)}&modifiedBefore=${encodeURIComponent(before)}`;
  let page = await squarespace(ctx, `/1.0/commerce/orders?${params}`);
  let seen = 0;
  let saved = 0;
  let cursor = null;
  while (page.ok) {
    for (const o of page.body.result ?? []) {
      const record = orderRecord(o);
      seen += 1;
      if (await putIfChanged(ctx, record)) saved += 1;
      if (record.email) queue.set(record.email, { email: record.email, next: 0, until: Date.now() + RECHECK_MS });
    }
    if (!page.body.pagination?.hasNextPage) break;
    // A next page with no new cursor stops the poll (watermark held) instead of asking for one page forever.
    const next = page.body.pagination.nextPageCursor;
    if (!next || next === cursor) return { ok: false, saved, reason: "squarespace", message: "Squarespace sent no new page cursor." };
    cursor = next;
    // A cursor is passed alone: Squarespace refuses it beside the window.
    page = await squarespace(ctx, `/1.0/commerce/orders?cursor=${encodeURIComponent(cursor)}`);
  }
  if (!page.ok) {
    // A 429 keeps the watermark and stores the wait, so the next tick sits out Squarespace's cool-down.
    if (page.status === 429) await ctx.db.put({ ...sync, _id: SYNC_ID, type: "sync", backoffUntil: new Date(Date.now() + 60_000).toISOString() }, { db: DB, id: SYNC_ID });
    return { ok: false, saved, reason: page.reason, message: page.message };
  }
  // An empty window leaves the watermark where it is: the next poll's window simply starts there.
  if (seen > 0 || !sync) await ctx.db.put({ _id: SYNC_ID, type: "sync", modifiedBefore: before }, { db: DB, id: SYNC_ID });
  const refreshed = await refreshCustomers(ctx, [...queue.values()]);
  if (!refreshed.ok) return { ok: false, saved, reason: refreshed.reason, message: refreshed.message };
  return { ok: true, saved };
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  try {
    // The setup verdict. The item (and the handle + slug the Setup screen links with) is the
    // owner's alone; a visitor learns only whether the app is ready.
    if (url.pathname === "/setup" && request.method === "GET") {
      const owner = ctx.userInfo?.userHandle === ctx.appInfo.ownerHandle;
      const hasKey = Boolean(ctx.secrets.SQUARESPACE_API_KEY);
      let kept = await ctx.db.get(SETUP_ID, { db: DB });
      let problem = hasKey ? null : { reason: "missing-key" };
      let warning = null;
      if (owner && hasKey) {
        // The first poll is the check: a key Squarespace takes reads the orders list. Once the key
        // has worked, a passing failure (a 429, Squarespace down) is a warning and the orders stay
        // open; only a refused key reopens the item.
        const r = await poll(ctx);
        if (r.ok) {
          if (!kept) {
            kept = { _id: SETUP_ID, type: "setup", verifiedOn: new Date().toISOString() };
            await ctx.db.put(kept, { db: DB, id: SETUP_ID });
          }
        } else if (kept && r.reason !== "unauthorized") {
          warning = r.message ?? null;
        } else {
          problem = r;
        }
      }
      const done = hasKey && !problem && Boolean(kept);
      const items = [{ id: "squarespace-key", label: "Your Squarespace API key", done, problem: problem?.message ?? null }];
      const ready = items.every((item) => item.done);
      if (!owner) return json({ ok: true, ready, owner });
      return json({ ok: true, ready, owner, items, warning, ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug });
    }

    // The owner's Refresh: poll now instead of waiting for the next tick.
    if (url.pathname === "/refresh" && request.method === "POST") {
      if (ctx.userInfo?.userHandle !== ctx.appInfo.ownerHandle) return json({ ok: false, reason: "owner-only" }, 403);
      return json(await poll(ctx));
    }

    return json({ ok: false, reason: "not-found" }, 404);
  } catch (err) {
    ctx.log("error", "squarespace route failed", { path: url.pathname, message: String(err?.message ?? err) });
    return json({ ok: false, reason: "handler-failed", message: "Something went wrong reaching Squarespace." }, 500);
  }
}

// The poll: new and changed orders reach the app within 15 minutes of Squarespace having them.
export async function scheduled(event, ctx) {
  if (!ctx.secrets.SQUARESPACE_API_KEY) return;
  try {
    const sync = await ctx.db.get(SYNC_ID, { db: DB });
    if (sync?.backoffUntil && Date.parse(sync.backoffUntil) > Date.now()) return; // still in the cool-down
    const r = await poll(ctx);
    ctx.log(r.ok ? "info" : "warn", "squarespace poll", { saved: r.saved, reason: r.reason ?? null, at: event.scheduledTime });
  } catch (err) {
    // A throw (the network, the database) still leaves a line saying which tick failed and why.
    ctx.log("error", "squarespace poll failed", { message: String(err?.message ?? err), at: event.scheduledTime });
  }
}

access.js — only the backend writes, and only the owner reads

access.js

jsexport function store(doc, oldDoc, user, ctx) {
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
  if (!["order", "customer", "sync", "setup"].includes(doc.type)) throw { forbidden: "unknown document type" };
  // Every record is a copy of the owner's store, written by backend.js: the poll, /setup or /refresh.
  ctx.requireBackend();
  // Orders carry customers' names, emails and addresses, so they reach the owner alone.
  return { channels: ["store"], grant: { roles: { owner: ["store"] } } };
}

App.jsx sketch

App.jsx

jsximport React, { useEffect, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch } from "use-vibes";
import { Badge, Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";

const money = (m) => new Intl.NumberFormat(undefined, { style: "currency", currency: m.currency }).format(m.value);

// The setup verdict, read on mount and again whenever the app comes back into view: the owner saves
// the key in another tab and returns, and the orders appear without a reload.
function useSetup() {
  const [setup, setSetup] = useState(null); // { ready, owner, items?, ownerHandle?, appSlug? }
  const latest = useRef(0);
  useEffect(() => {
    const load = () => {
      const n = ++latest.current;
      apiFetch("/setup").then((r) => r.json()).catch(() => ({ ready: false, owner: false })).then((s) => { if (n === latest.current) setSetup(s); });
    };
    load();
    const onVisible = () => { if (document.visibilityState === "visible") load(); };
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", load);
    return () => { document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("focus", load); };
  }, []);
  return setup;
}

// The item's steps: each a link to the exact page, in Squarespace's own words, with this vibe's real
// handle and slug filled in.
function setupSteps(vibe) {
  return [
    { href: "https://account.squarespace.com", link: "your Squarespace account", text: ": sign in and open the site you sell on." },
    { href: "https://account.squarespace.com", link: "Settings", text: ": scroll to Advanced, open Developer API Keys and press Generate Key (this needs the Commerce Advanced plan). Tick Orders and Profiles, each Read Only, save, and copy the key: Squarespace shows it once." },
    { href: `https://vibes.diy/vibes/mine/${vibe}/settings`, link: "this vibe's Settings tab", text: `: under Secrets, enter SQUARESPACE_API_KEY, paste the key, and save. Or run npx vibes-diy secrets set SQUARESPACE_API_KEY --vibe ${vibe}.` },
  ];
}

// The Setup surface, the owner's alone.
function SetupScreen({ setup }) {
  const item = setup.items.find((i) => i.id === "squarespace-key");
  return (
    <Stack>
      <Heading>Setup</Heading>
      <Row gap={2}>
        <Text>{item.label}</Text>
        <Badge tone={item.done ? "up" : "info"}>{item.done ? "Done" : "To do"}</Badge>
      </Row>
      {item.problem && <Text>Squarespace said: {item.problem}</Text>}
      <ol>
        {setupSteps(`${setup.ownerHandle}/${setup.appSlug}`).map((step) => (
          <li key={step.link}>
            Open <a href={step.href} target="_blank" rel="noreferrer">{step.link}</a>
            {step.text}
          </li>
        ))}
      </ol>
      <Text muted>The key stays on the server and reads your store; packing and refunds stay in Squarespace.</Text>
    </Stack>
  );
}

export default function App() {
  const { useLiveQuery } = useFireproof("store");
  const { docs: orders } = useLiveQuery("type", { key: "order" });
  const { docs: customers } = useLiveQuery("type", { key: "customer" });
  const setup = useSetup();
  const [picked, setPicked] = useState(null);
  const [note, setNote] = useState(null);
  const byEmail = Object.fromEntries(customers.map((c) => [c.email, c]));
  const toPack = orders.filter((o) => o.fulfillmentStatus === "PENDING").sort((a, b) => (a.createdOn < b.createdOn ? 1 : -1));
  const refresh = async () => {
    const r = await apiFetch("/refresh", { method: "POST" }).then((res) => res.json()).catch(() => ({ ok: false }));
    setNote(r.ok ? `${r.saved} orders read from Squarespace.` : r.message ?? "Squarespace did not answer; the next poll tries again.");
  };

  const ready = setup?.ready === true;
  const screen = picked ?? (setup?.owner && !ready ? "setup" : "orders");
  return (
    <Stack>
      <Row gap={2}>
        <Button variant="quiet" onClick={() => setPicked("orders")}>To pack</Button>
        {setup?.owner && (
          <Button variant={ready ? "quiet" : "solid"} onClick={() => setPicked("setup")}>
            Setup{ready ? "" : " · to do"}
          </Button>
        )}
      </Row>
      {screen === "setup" && setup?.owner ? (
        <SetupScreen setup={setup} />
      ) : !setup?.owner ? (
        <Text muted>{setup ? "This packing station is its owner's. Make your own from the remix button." : "Opening your store…"}</Text>
      ) : !ready ? (
        <Text muted>The packing station is not open yet: finish Setup to read your store.</Text>
      ) : (
        <Stack>
          <Row gap={2}>
            <Heading>To pack · {toPack.length}</Heading>
            <Button variant="quiet" onClick={refresh}>Refresh</Button>
          </Row>
          {setup.warning && <Text muted>Squarespace said: {setup.warning} The orders below are from the last poll.</Text>}
          {note && <Text muted>{note}</Text>}
          {toPack.length === 0 ? (
            <Text muted>All packed. New orders land here within 15 minutes of checkout.</Text>
          ) : (
            toPack.map((o) => {
              const c = o.email ? byEmail[o.email] : null;
              return (
                <Stack key={o._id}>
                  <Row gap={2}>
                    <Text>#{o.orderNumber} · {money(o.total)}</Text>
                    {o.testmode && <Badge tone="info">test</Badge>}
                  </Row>
                  <Text>{o.lines.map((l) => `${l.qty} × ${l.name}`).join(", ")}</Text>
                  {c && <Text muted>{c.name || c.email}: {c.orderCount} orders, {money(c.totalSpent)} all time</Text>}
                </Stack>
              );
            })
          )}
          <Text muted>Customer totals come from Squarespace and can trail a brand-new order by a poll.</Text>
        </Stack>
      )}
    </Stack>
  );
}