Documentation

Build on Folio

Folio sits on top of PostHog or your existing event stream, finds users failing your goals, and returns approved copy + CTAs via a headless decisions API — banners, modals, and dashboard cards your app renders. This guide covers ingestion, the decisions API, and the operator workflow that turns events into approved copy your app renders.

Overview

Folio sits on top of your existing event stream. PostHog (or your analytics tool) tells you what happened; Folio tells your app what to show next: approved copy and CTAs for users who are failing a goal you define.

The loop looks like this:

  1. Ingest: browser SDK, REST API, or PostHog webhook
  2. Goal: a plain-English outcome with a target event
  3. Intelligence: cohorts and draft recommendations (rules or LLM)
  4. Approve: a person reviews each message before anything goes live
  5. Serve: GET /decisions/:surface returns copy and a CTA
  6. Prove: serve, click and convert attribution per recommendation

Surfaces

A surface is where a message appears. Your app handles layout; Folio returns the decision payload.

  • banner: <FolioBanner />, or Folio.mountBanner() from the script tag. Intelligence drafts these.
  • dashboard_card: <FolioCard />. Intelligence drafts these.
  • modal: <FolioModal />. Intelligence doesn't draft these yet, so this surface returns null for now.
  • notification: <FolioBanner surface="notification" />, or your own toast via getDecision. Intelligence drafts these.
  • email: headless only: fetch with getDecision and send it yourself. Intelligence doesn't draft these yet, so this surface returns null for now.

Any other surface name gets a 400 that lists these.

Concepts

Project & public key

A project is one product or app. Each project has a phk_live_… public key safe to embed in browser code. Find it on the project page after signup.

Events & identities

track() records behavioral events. identify() attaches traits to a stable distinct_id. Cohort rules evaluate events and traits together.

Goals

A goal describes an outcome, for example "get trial users to complete signup", with an optional target event used for cohort rules and conversion attribution.

Cohorts & recommendations

Running intelligence proposes cohorts (groups of users the rules or the model think are at risk of missing the goal) and draft recommendations (copy per surface). Check a cohort's rule and members before approving its messages. You edit caps and holdout %, then approve drafts before they can be served.

Decisions

A decision is the copy and CTA returned for a specific user and surface. Each successful serve is logged for attribution and counts toward your monthly decision limit. Holdout impressions and empty responses are not billed as serves.

Quick start

Fastest path to a working decision, no external deploy required:

  1. Sign up and complete onboarding (leave Origin URL blank for local dev).
  2. On your project page, click Load demo data. It seeds events for folio_demo_user, creates a starter goal, and runs intelligence (that run counts toward your monthly intelligence runs). The button is shown while the project has no events yet, so use it on a fresh project.
  3. Open Recommendations and approve a banner draft.
  4. Use Preview decision with user ID folio_demo_user and surface Banner. You should see the copy.

To check your key end to end before writing any code, send one event from a terminal. Copy your public key from the project page.

Send your first event
curl -X POST https://folio-weld-seven.vercel.app/api/v1/events \
  -H "Content-Type: application/json" \
  -d '{ "publicKey": "phk_live_…", "distinctId": "user_123", "name": "signup_completed" }'

# → {"ok":true,"accepted":1,"duplicates":0}

It shows up under Recent events on the project page. For production, install the snippet below and use the same distinct_id in preview that your SDK sends.

Install
<script src="https://folio-weld-seven.vercel.app/folio.js" defer></script>
<script>
  window.folioConfig = { publicKey: "phk_live_…" };
</script>

Browser SDK

public/folio.js exposes window.folio. It keeps a distinct id for the visitor (stored in localStorage) and auto-captures $pageview. Every method acts on the current visitor, so track takes no user id: call identify after login to switch to your own id.

Track & identify
// After login, pin the user id (later calls use it)
folio.identify("user_123", { plan: "trial" });

// Custom events for the current user
folio.track("pricing_viewed", { plan: "pro" });
Fetch a decision
// Either form works; userId defaults to the current user
const decision = await folio.getDecision({ surface: "banner", userId: "user_123" });
// const decision = await folio.getDecision("banner", "user_123");

if (decision) {
  renderBanner({
    title: decision.title,
    body: decision.body,
    cta: { label: decision.ctaLabel, href: decision.ctaUrl },
  });

  // When it renders, and on dismiss or CTA click:
  folio.feedback({ logId: decision.logId, action: "shown" });
  folio.feedback({ logId: decision.logId, action: "clicked" }); // or "dismissed"
}

folioConfig reference

  • publicKey: required. Your project's phk_live_… key.
  • baseUrl: optional. Defaults to the script host + /api/v1.
  • mock: optional. Skips network calls when true.
  • mockDecisions: optional. Fixture map keyed by surface for mock mode.

Auto pageviews

Unless mock is on, the SDK fires $pageview on load and whenever the path or query string changes (pushState, replaceState, back and forward). A replaceState that leaves the URL as it was sends nothing. Each pageview counts as an event. Session IDs reset after 30 minutes idle.

Errors

Nothing throws into your page. Methods return promises that resolve (with null when a call fails). When Foliorefuses a call (unknown key, blocked origin, trial ended, rate limit, invalid input) or can't be reached, the console gets one [folio] warning that says what to fix, including the API's own message.

Mock mode (UI only)

Pass mock: true and mockDecisions in folioConfig to render UI without network calls. Useful for Storybook, not a substitute for end-to-end testing.

Node SDK

For server-side event ingestion (cron jobs, backend handlers), install folio-sdk and use FolioClient. It needs Node 18 or newer and is an ES module: use import in a .mjs file or a package with "type": "module".

Install
npm install folio-sdk
Server-side track
import { FolioClient } from "folio-sdk";

const folio = new FolioClient({
  publicKey: "phk_live_…",
  baseUrl: "https://folio-weld-seven.vercel.app/api/v1",
  // apiKey: process.env.FOLIO_API_KEY, // optional server API key, see below
});

await folio.track("user_123", "invoice_paid", { amount_cents: 9900 });
await folio.identify("user_123", { plan: "pro" });

// null means show nothing (no approved message, the user is in the holdout,
// userId is empty, or the call failed and was logged)
const decision = await folio.getDecision("banner", "user_123");

if (decision) {
  await folio.feedback({ distinctId: "user_123", logId: decision.logId, action: "shown" });
}

Unlike the browser snippet, every Node call names the user: track(distinctId, name, properties), identify(distinctId, traits) and feedback({ distinctId, logId, action }). track also takes { idempotencyKey, occurredAt } as a fourth argument.

No method throws or rejects because of Folio. A refused request (unknown key, blocked origin, trial ended, rate limit, invalid input) or a network failure logs one [folio] warning per distinct reason, and the call resolves (getDecision with null). A fire-and-forget folio.track() in a request handler can't become an unhandled rejection.

React

folio-sdk/react ships drop-in components. Wrap your app once in FolioProvider, then place FolioBanner, FolioCard or FolioModal where messages should appear. Each one renders nothing until there's an approved message for that user, renders nothing for users in the holdout group, and reports shown, clicked and dismissed for you. React 18 or 19 is a peer dependency. Each user sees a message at most once a week by default (change this under Delivery rules before you approve), so use a fresh user id when you test.

userId may be undefined or null while your auth loads (user?.id): nothing is fetched until it has a value.

React quick start
import { FolioProvider, FolioBanner } from "folio-sdk/react";
import "folio-sdk/styles.css"; // optional default look

<FolioProvider publicKey="phk_live_…" baseUrl="https://folio-weld-seven.vercel.app/api/v1">
  <FolioBanner userId={user?.id} />
</FolioProvider>
Card, modal and notification
import { FolioBanner, FolioCard, FolioModal } from "folio-sdk/react";

<FolioCard userId={user.id} />                         {/* surface: dashboard_card */}
<FolioModal userId={user.id} />                        {/* surface: modal */}
<FolioBanner userId={user.id} surface="notification" /> {/* surface: notification */}

Styling

Components are unstyled: they output folio-banner, folio-card and folio-modal class names (with __title, __body, __cta, __dismiss parts) and no inline styles. Import folio-sdk/styles.css for a small default look, themed with three CSS variables. Its rules are a single class at most, so one class of your own overrides them:

Theme
:root {
  --folio-color: #4f46e5;  /* buttons and banner tint */
  --folio-radius: 12px;
  --folio-font: inherit;
}

Your own markup

Pass renderDecision to draw the message yourself. Call the actions you receive so clicks and dismissals are still measured.

Custom render
<FolioBanner
  userId={user.id}
  renderDecision={(d, { clickCta, dismiss }) => (
    <MyBanner title={d.title} body={d.body} onCta={clickCta} onClose={dismiss} />
  )}
/>

No React? Use the script tag

Script tag
<link rel="stylesheet" href="https://folio-weld-seven.vercel.app/folio.css">
<div id="folio-banner"></div>
<script src="https://folio-weld-seven.vercel.app/folio-embed.js"></script>
<script>
  Folio.mountBanner("#folio-banner", {
    publicKey: "phk_live_…",
    baseUrl: "https://folio-weld-seven.vercel.app/api/v1",
    userId: "user_123",
  });
</script>

In a Server Component or API route, call new FolioClient({ publicKey }).getDecision("banner", userId) and render the result yourself. Then send shown, clicked and dismissed with folio.feedback() so the message is measured.

REST API

Base URL: https://folio-weld-seven.vercel.app/api/v1. Every response, errors included, carries CORS headers, so browser code can read why a call was refused. If your project has an Allowed origin set, browser requests must come from that origin. Leave it empty during local development; you can change it on the project page at any time. Requests are JSON; a text/plain body holding JSON is accepted too (that is what folio.js sends, to skip the CORS preflight).

POST /events

Track one event, or send an array of up to 100. Every event in a batch must use the same public key.

Single event
curl -X POST https://folio-weld-seven.vercel.app/api/v1/events \
  -H "Content-Type: application/json" \
  -d '{
    "publicKey": "phk_live_…",
    "distinctId": "user_123",
    "name": "signup_completed",
    "properties": { "plan": "pro" },
    "occurredAt": "2026-11-22T16:41:00Z",
    "idempotencyKey": "signup-user_123",
    "url": "https://app.example.com/signup"
  }'

# → {"ok":true,"accepted":1,"duplicates":0}

Event fields:

  • publicKey: required.
  • distinctId: required. Your user's id, a string (numbers are converted), up to 256 characters.
  • name: required. A string up to 200 characters; surrounding spaces are trimmed and a blank name is refused.
  • properties: optional JSON object (not an array), up to 32 KB as JSON and 5 levels deep.
  • occurredAt: optional ISO 8601 time the event happened, for example 2026-11-22T16:41:00Z. Defaults to when we receive it. Must be in 2000 or later and no more than an hour ahead of our clock. Use it to backfill history.
  • idempotencyKey: optional, up to 128 characters. Sending the same key again for the project stores the event once and counts it under duplicates; both SDKs set one on every event so retries are safe. For a single event you can send an Idempotency-Key header instead.
  • sessionId: optional, up to 128 characters.
  • url: optional. Longer than 2048 characters is cut to that length.

Strings anywhere in an event, including inside properties, can't contain the NUL character (\u0000) or broken Unicode (an unpaired surrogate). Other Unicode, emoji included, is fine.

POST /events, batch

Batch (max 100)
curl -X POST https://folio-weld-seven.vercel.app/api/v1/events \
  -H "Content-Type: application/json" \
  -d '[
    { "publicKey": "phk_live_…", "distinctId": "user_1", "name": "$pageview" },
    { "publicKey": "phk_live_…", "distinctId": "user_2", "name": "$pageview" }
  ]'

A batch is all or nothing: if one event is invalid, the response names it (for example events[3].occurredAt) and none are stored.

POST /identify

Merge traits onto an identity. traits follows the same rules as properties. Requires an active plan but does not count toward event limits.

Identify
curl -X POST https://folio-weld-seven.vercel.app/api/v1/identify \
  -H "Content-Type: application/json" \
  -d '{
    "publicKey": "phk_live_…",
    "distinctId": "user_123",
    "traits": { "plan": "trial", "company_size": "10" }
  }'

GET /decisions/:surface

Surfaces: banner, dashboard_card, modal, notification, email. Returns { "decision": null } when nothing applies. Returns 402 when billing limits or trial expiry block serving.

Decision
curl "https://folio-weld-seven.vercel.app/api/v1/decisions/banner?publicKey=phk_live_…&userId=user_123"

Response shape when a decision matches:

Response
{
  "decision": {
    "id": "rec_uuid",
    "logId": 42,
    "surface": "banner",
    "title": "You're close, one step left",
    "body": "Most users who complete signup stick around.",
    "ctaLabel": "Continue",
    "ctaUrl": "/signup",
    "priority": 0.8,
    "reasoning": null
  }
}

POST /feedback

Record shown, dismissed, clicked or converted against a served decision: send its logId (or its id as recommendationId to use the user's latest serve) and the same distinctId. The React components and script tag send the first three for you. An unknown logId gets 404.

Feedback
curl -X POST https://folio-weld-seven.vercel.app/api/v1/feedback \
  -H "Content-Type: application/json" \
  -d '{
    "publicKey": "phk_live_…",
    "distinctId": "user_123",
    "logId": 42,
    "action": "clicked"
  }'

Limits & errors

Rate limits

Per project, per minute (fixed one-minute windows):

  • Events: 600 events (a batch of 100 uses 100)
  • Identify: 300 requests
  • Feedback: 300 requests
  • Decisions: 1200 requests

Over the limit you get 429 with a Retry-After header (seconds until the window resets). Nothing in a refused request is stored, so resend it after that many seconds.

Request size

Bodies up to 1 MB. Larger ones get a JSON 413. Field limits are listed under POST /events above.

HTTP status codes

Every error is JSON: { "error": "…what to fix…" }, sometimes with a code.

  • 200: success
  • 400: invalid JSON, a missing or invalid field (the message names it), or an unknown surface. Fix the request; retrying it unchanged won't help.
  • 401: unknown publicKey, or an unknown or revoked server API key
  • 402: trial expired or monthly limit reached
  • 403: origin not allowed (Allowed origin mismatch), or a server API key from another workspace
  • 404: /feedback for a decision that wasn't served to that user
  • 413: more than 100 events in a batch, or a body over 1 MB
  • 429: rate limited; wait for Retry-After seconds
  • 500: a problem on our side. Retrying is safe (send the same idempotencyKey so events count once).

Server API keys

Create keys under Settings, API keys. A key starts with folio_, is shown once, and covers every project in your workspace, so keep it on your server and never put it in browser code. Revoking a key makes every call that uses it fail with 401 straight away. Keys are included on every plan, trial too.

List projects

GET /projects
curl https://folio-weld-seven.vercel.app/api/v1/projects \
  -H "Authorization: Bearer folio_…"

# → {"projects":[{"id":"…","name":"Shipcart","slug":"shipcart",
#     "publicKey":"phk_live_…","allowedOrigin":null,"createdAt":"…"}]}

Server-to-server calls

Add Authorization: Bearer folio_… to /events, /identify, /decisions or /feedback (or pass apiKey to FolioClient). The call still names its project with publicKey; the key must belong to that project's workspace, and the project's Allowed origin setting doesn't apply. Without the header these endpoints work exactly as above, so browser code never needs a key.

PostHog

Keep PostHog for product analytics and funnel exploration. Forward a copy of each event into Folio (included on every plan) so cohorts, intelligence, and decisions run on the same behavioral stream, without replacing PostHog.

Folio owns goals, cohorts, approvals, and the decisions API. PostHog is the ingestion pipe, not the decision brain.

Prerequisites

  • Plan: PostHog forwarding is included on every plan, trial included.
  • Folio project: You need your phk_live_… public key (Project page, Install the SDK).
  • PostHog project: Admin access to create a Data pipeline destination.

Step 1: Enable in Folio

  1. Open your project at /app/projects/[id].
  2. Scroll to Integrations and click Enable PostHog forwarding.
  3. Copy the two values Folio generates:
    • Webhook URL: includes your publicKey query param
    • Header X-Folio-Webhook-Secret: shared secret (starts with fwh_)

Use Rotate secret if the secret is ever exposed. Update the header in PostHog immediately after rotating: old secrets stop working instantly.

Step 2: Create a PostHog destination

In PostHog: Data pipeline, then Destinations, then add an HTTP Webhook destination (or customize an existing webhook template).

  1. URL: paste the Folio webhook URL exactly (includes ?publicKey=phk_live_…).
  2. Method: POST.
  3. Headers: add a custom header:
    • Name: X-Folio-Webhook-Secret
    • Value: the secret from Folio (not your PostHog API key)
  4. Body: use PostHog's template syntax. The Integrations panel on your project page shows this JSON under "PostHog destination JSON body":
PostHog destination body (recommended)
{
  "event": {
    "event": "{event.event}",
    "distinct_id": "{event.distinct_id}",
    "timestamp": "{event.timestamp}",
    "properties": "{event.properties}"
  }
}

PostHog substitutes {event.event}, {event.distinct_id}, etc. at send time. This wrapped shape matches PostHog's CDP destination format and is what Folio parses by default.

Optional: add destination filters in PostHog to forward only specific events (e.g. exclude $feature_flag_called) and reduce Folio event usage.

What Folio does with each webhook

When PostHog POSTs to Folio, the server:

  1. Resolves publicKey from the URL and verifies X-Folio-Webhook-Secret against the project's stored secret.
  2. Parses the JSON body into one or more normalized events (see supported shapes below) and checks them against the same field limits as POST /events.
  3. Checks billing: forwarded rows count toward your monthly events meter the same as SDK track() calls.
  4. Inserts into the events table, updates identity last_seen_at, and runs goal conversion attribution when the event name matches a goal target.

Webhook requests are server-to-server: they do not go through browser CORS or your project's Origin URL allowlist. That only applies to SDK and REST calls from the browser.

Supported payload shapes

Folio accepts any of these JSON bodies (verified by the ingestion parser):

Wrapped CDP (recommended, matches the template above)

Single wrapped event
{
  "event": {
    "event": "$pageview",
    "distinct_id": "user_abc",
    "timestamp": "2025-06-01T12:00:00.000Z",
    "properties": { "$current_url": "https://app.example.com/home", "plan": "trial" }
  }
}

Flat Folio-style

Flat event
{
  "distinct_id": "user_abc",
  "event": "signup_completed",
  "timestamp": "2025-06-01T12:00:00.000Z",
  "properties": { "plan": "pro" }
}

Batch array

An array of flat or wrapped events in one request. Useful if you customize the PostHog Hog function to batch sends.

Batch
[
  { "distinct_id": "user_1", "event": "trial_started" },
  { "event": { "event": "$pageview", "distinct_id": "user_2", "timestamp": "…" } }
]

Property handling

  • PostHog system properties prefixed with $ (e.g. $lib, $device_type) are stripped before storage, except $current_url, which is copied to the event's url column when present.
  • String, number, and boolean custom properties are kept.
  • If PostHog sends properties as a JSON string (common with template substitution), Folio parses it automatically.
  • Every ingested PostHog event gets properties.source = "posthog" so you can distinguish forwarded traffic in cohort rules.

Webhook endpoint reference

Request
POST https://folio-weld-seven.vercel.app/api/v1/webhooks/posthog?publicKey=phk_live_…
Content-Type: application/json
X-Folio-Webhook-Secret: fwh_…

{ "event": { "event": "…", "distinct_id": "…", … } }
Success response
{ "ok": true, "accepted": 1 }

Webhook HTTP status codes

  • 200: event(s) accepted and stored
  • 400: missing publicKey param, invalid JSON, no parseable events in the body, or an event that breaks a field limit (bad timestamp, NUL character, oversized properties). The message names the field.
  • 401: unknown publicKey, or a missing or wrong X-Folio-Webhook-Secret
  • 403: PostHog forwarding not enabled for this project (click Enable in Integrations first)
  • 402: trial ended or monthly event limit reached
  • 413: body over 1 MB
  • 500: a problem on our side (PostHog retries; events dedupe on their PostHog id)

Verify it's working

  1. Trigger an event in PostHog (or use PostHog's destination test/debug mode).
  2. On your Folio project page, check Recent events: forwarded events appear within seconds.
  3. Confirm properties.source is posthog in the event row.
  4. Run intelligence (or wait for cron) so cohorts materialize, then approve a recommendation and preview a decision for that distinct_id.

PostHog destinations run asynchronously with automatic retries, so a transient Folio 500 does not block PostHog's own event capture.

Advanced: Hog function alternative

If you need more control (custom filters, batching, or dynamic headers), edit the PostHog destination source code and use Hog's fetch() to POST the same URL and header. The body must still match one of the supported shapes above.

Operator console

Everything after ingestion happens in the dashboard at /app.

Goals

Create a goal with a clear target event. The intelligence engine uses it for cohort rules and conversion tracking.

Run intelligence

On the project page, click Run intelligence. This proposes cohorts, materializes members, and drafts recommendations. Without an Anthropic API key, rule-based fallback runs automatically. Each run counts toward your monthly intelligence runs.

Approve recommendations

Edit drafts on the Recommendations page (cooldown days, max serves per user, holdout %, priority and suppression rules), then approve. Only approved recommendations are served.

Recommendation settings

Before approving, you can tune each draft under Delivery rules:

  • Priority (0 to 100): when several live messages match the same user and surface, the highest is shown
  • Cooldown days (1 to 90): window for frequency-cap checks
  • Max per user (1 to 20): cap on impressions in that window
  • Holdout % (0 to 50): deterministic control group (logged, not billed as serves)
  • Stop once the user reaches the goal / Stop if they dismiss it: stop re-showing after a user action

A value outside its range is changed to the nearest allowed one.

Pipeline checklist

Each project page shows a five-step checklist. When all steps are green, preview and live serving should work for users materialized into cohorts.

Attribution

Every billed serve writes a row to decision_log with a logId.

  • shown: the message actually rendered (sent by the SDK components)
  • clicked: user tapped the CTA (POST /feedback with action: "clicked")
  • dismissed: user closed the surface
  • converted: user fired the goal's target event after a serve (recorded automatically when the event arrives)

Per-recommendation stats appear on the Recommendations page. Project overview shows 7-day serve, click and convert rollups.

Billing & limits

Folio meters three things: events ingested, decisions served, and intelligence runs. See pricing for tier details.

  • Events: each track() call, REST event or PostHog row ingested (duplicates and refused requests are not counted)
  • Decisions: each successful serve that returns copy (holdouts excluded)
  • Intelligence runs: each manual, cron or Load demo data intelligence pass

The trial lasts 14 days with every feature on and these caps: 2 projects, 100,000 events, 25,000 decisions, 10 intelligence runs and 10 live (approved) recommendations at a time. Paid plans have no cap on live recommendations.

View usage at Settings, Billing. Expired trials return 402 on ingest and decision endpoints.

Troubleshooting

Browser calls fail silently

Open the console: every refusal logs a [folio] warning with the API's message. In the network panel the response body says what to fix.

PostHog webhook returns 401 or 403

  • 403 PostHog forwarding isn't enabled for this project: click Enable PostHog forwarding in Project, Integrations before PostHog sends traffic.
  • 401 Wrong X-Folio-Webhook-Secret or Missing X-Folio-Webhook-Secret header: the header value must match Folio exactly (case-sensitive). Re-copy after rotating.
  • 401 Unknown publicKey: the webhook URL must include the correct ?publicKey=phk_live_… from your project page.

PostHog webhook returns 400

  • No events parsed from payload: the body is missing event and distinct_id. Use the destination JSON template from Integrations.
  • Confirm PostHog substituted template variables: raw {event.event} strings in the body mean templating wasn't applied.

PostHog events missing in Folio

  • Check PostHog destination logs for failed deliveries and retry status.
  • Destination filters may exclude the events you expect. Widen filters or test with $pageview.
  • A 402 from Folio means billing limits or plan tier. Check Settings, Billing.

Preview returns nothing

  • Confirm the user ID matches a distinct_id in your events and is materialized into a cohort (check Cohorts, member count).
  • Ensure at least one recommendation is approved for that surface.
  • Check suppression: the user may have dismissed, converted, or hit frequency caps.

SDK requests fail with 403

The project's allowed origin does not match the page making the call. On the project page, under Allowed origin, click Allow any origin while you build, or set it to the exact origin (for example http://localhost:5173).

402 Payment Required

Trial expired or monthly limit reached. Upgrade via pricing or check usage in billing settings.

0 members after intelligence

Cohort rules need matching events. Send real traffic (or, on a project with no events yet, use Send test events), then re-run intelligence. Goals with a target event produce better cohorts.

Still stuck?

Create a fresh project and use Load demo data for a known-good path, then compare your live distinct_id to the preview field.