Skip to content

Data

Keep records in collections and reach them with an API: a static site can collect sign-ups without server code, and a server app can read and write with its secret key.

On this page

How it works

Every project with an account has a headless data layer. Data lives in Perafly, and your site reaches it at https://api.perafly.com/v1/projects/{project}/data/{collection}. Typical uses:

  • Forms and lists: a static site collects a waitlist, contact form or survey. Public create, secret read.
  • Content: posts or products live in a collection; the site reads them at build or request time, and a change hook refreshes it.
  • App data: a server app (for example Next.js) reads and writes with the secret key.

Queries are deliberately simple: equality and range filters, sorting and paging. There are no joins. A project that needs a full relational database connects its own through environment variables. Projects published without an account have no data layer.

Collections

A collection is a set of records with a schema. Its name matches ^[a-z][a-z0-9_-]{0,63}$ and is unique in the project. A collection has up to 100 fields; id, createdAt and updatedAt are reserved for the system.

TypeHolds
textText; maxLength 1–100,000 (default 10,000).
numberA number; optional min, max, integer.
booleanTrue or false.
dateAn ISO 8601 date.
selectOne of options (1–100 values).
jsonAny JSON up to 32 KB.
fileA path in project storage (public/… or private/…).
relationThe id (rec_…) of a record in another collection of the project (collection).

Filtering and sorting work only on indexed fields and on id, createdAt and updatedAt. A collection can have up to 5 indexed fields; json and file can't be indexed. A field's type (and a relation's target) can't change: delete the field and add a new one. One record is at most 64 KB.

signups.schema.json
{
  "fields": [
    { "name": "email", "type": "text", "required": true, "indexed": true, "maxLength": 320 },
    { "name": "plan", "type": "select", "options": ["free", "pro"], "indexed": true }
  ],
  "rules": { "read": "secret", "create": "public", "update": "secret", "delete": "secret" }
}
Terminal
perafly data collections create signups --schema signups.schema.json
perafly data collections ls
perafly data collections show signups

perafly data collections update <name> --schema <file> takes the full field list. Removing a collection deletes its records too.

Rules

Each collection has a rule per action (read, create, update, delete): public lets the publishable key do it from a browser, secret needs the secret key or a team credential. Without rules, everything is secret.

Opening data to everyone is a person's decision. An agent credential may make create public, but not read, update or delete (rule_requires_person).

Project keys

KeyWhere it belongsCan do
Publishable pfp_…In the browser; it isn't a secret. Created with the first collection.Only actions whose rule is public.
Secret pfk_…On the server only, as PERAFLY_SECRET_KEY. Shown once when created.All of the project's records whatever the rules, reading collections, and storage.
Hook secret pfw_…Never shown; only as PERAFLY_WEBHOOK_SECRET. Created with the first hook.Signs change hook requests.

The secret key and the hook secret become environment variables of the project and take effect from the next version. The publishable key is also available as PERAFLY_PUBLISHABLE_KEY. Creating or rotating keys needs a person's sign-in; agents can't.

Terminal
perafly data keys                       # publishable key, and whether the others exist
perafly data keys --create-secret       # shown once
perafly data keys --rotate-publishable  # the old key stops working at once
perafly data keys --revoke-secret

Reading and writing records

A record is a flat object: the system fields id (rec_…), createdAt, updatedAt and the fields of the schema. Send keys as Authorization: Bearer <key>. The API accepts browser requests from any origin.

From a static page

Browser
await fetch("https://api.perafly.com/v1/projects/my-site/data/signups", {
  method: "POST",
  headers: {
    Authorization: "Bearer pfp_…", // publishable key: fine in the browser
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ email: "ada@example.com" }),
});

From a server

Server
const res = await fetch(
  `${process.env.PERAFLY_API_URL}/v1/projects/${process.env.PERAFLY_PROJECT_ID}/data/signups?sort=-createdAt&limit=20`,
  { headers: { Authorization: `Bearer ${process.env.PERAFLY_SECRET_KEY}` } },
);
const { data, nextCursor } = await res.json();
QueryMeaning
filter[plan]=proEquality.
filter[views][gte]=100Operators eq, ne, gt, gte, lt, lte, in (comma-separated).
sort=-createdAtUp to two fields, comma-separated; - for descending.
limit, cursor1–100 per page (default 50); follow nextCursor.

PATCH changes only the fields you send; null removes a field (a required field can't be removed). Unknown fields, missing required fields and wrong types answer validation_error; a relation to a missing record answers relation_not_found.

Terminal
perafly data ls signups --filter plan=pro --filter views:gte=100 --sort -createdAt --limit 20
echo '{"email":"ada@example.com"}' | perafly data add signups
perafly data get signups rec_…
perafly data export signups --format csv --out signups.csv

Limits and requests

  • Collections per project, records per project and monthly data requests come from your plan; see Pricing. Requests from the dashboard don't count.
  • When a plan without overage runs out of data requests, the API answers data_quota_exceeded until the next period. Plans with overage keep serving and bill the extra requests.
  • Rate limits: with the publishable key, 30 writes and 300 reads a minute per address and project; with the secret key, 600 requests a minute per project.
  • Export (CSV or JSON) needs the plan's data export feature and can't be done with the publishable key.

Change hooks

A collection can call your site when a record is created, updated or deleted, for example to rebuild a page. Set hook: { path, events } on the collection; Perafly sends a POST to your live address plus path. Hooks need a plan with the change hooks feature.

Request body
{
  "id": "hkd_…",
  "type": "record.updated",
  "createdAt": "…",
  "project": { "id": "prj_…", "name": "acme-blog" },
  "collection": "posts",
  "record": { "id": "rec_…", "createdAt": "…", "updatedAt": "…", "title": "…" }
}

type is record.created, record.updated or record.deleted (on delete, record is only { id }). Headers: Perafly-Event, Perafly-Delivery (hkd_…) and Perafly-Signature. A delivery that doesn't get a 2xx within 10 seconds is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours (at most 6 attempts); redirects aren't followed. perafly data hooks shows the last 50 deliveries.

Verify the signature

Perafly-Signature is t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of "<t>.<raw body>" with the hook secret. Compute it over the raw body before parsing, compare in constant time and reject a t older than 5 minutes.

Node.js
import crypto from "node:crypto";

// rawBody: the request body as received (a string), before JSON.parse
export function verifyPeraflySignature(rawBody, header, secret = process.env.PERAFLY_WEBHOOK_SECRET) {
  if (typeof header !== "string" || !secret) return false;
  const parts = Object.fromEntries(header.split(",").map((part) => part.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
  if (!/^[a-f0-9]{64}$/.test(parts.v1 ?? "")) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  const given = Buffer.from(parts.v1, "hex");
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}