Skip to Content
GuidesBuilding an App

Building an App

This guide walks you through building a Foir app from scratch — manifest, middleware, a custom UI placement, an operation, and an inbound webhook. By the end, you’ll have an installable app that any Foir project can adopt with one URL.

If you only need a private operation for one project (no reuse, no sharing), see Building Operations instead. This guide is for when you want a manifest-installable, reusable unit.

What You’ll Build

A “redirector” app that:

  • Defines a sink contract for redirect rules
  • Hosts a Cloudflare Worker that consumes redirect records and writes them to KV
  • Provides a custom main-editor placement for authoring redirects
  • Exposes operations: redirect-sync, deploy-worker, __uninstall

We’ll use redirector as the running example — same pattern works for Shopify-style inbound apps, Algolia-style outbound apps, DeepL-style sidecar apps, etc.

Step 1: Scaffold the project

npx @foir/cli create-config redirector --type custom-editor

custom-editor gives you a UI app + middleware API. For purely backend apps, use --type workflow. For embeddable static iframes (color picker), use --type widget.

Project structure:

redirector/ package.json foir.config.ts ui/ # Vite + React + Tailwind iframe src/ App.tsx api/ # Hono middleware src/ index.ts routes/ webhooks.ts # Inbound webhook handlers health.ts

You add manifest.json (Step 2) and api/src/routes/operations.ts (Step 3) yourself.

cd redirector npm install npm run dev

The UI runs on http://localhost:3001, the API on http://localhost:3002.

Step 2: Write the manifest

manifest.json describes what your app contributes. Required fields are name and version; everything else is whatever your app actually needs.

{ "name": "redirector", "version": "1.0.0", "metadata": { "displayName": "Cloudflare Redirector", "description": "Sync redirect records to Cloudflare KV via a Worker.", "icon": "redirect", "author": "Bob's Country Bunker" }, "middleware": { "url": "https://redirector.example.com" }, "credentials": { "strategy": "API_KEY", "schema": { "type": "object", "properties": { "cloudflareApiToken": { "type": "string", "title": "Cloudflare API token" }, "cloudflareAccountId": { "type": "string", "title": "Cloudflare account id" } }, "required": ["cloudflareApiToken", "cloudflareAccountId"] } }, "settings_schema": { "type": "object", "properties": { "cloudflareZone": { "type": "string", "title": "Zone (e.g. example.com)" }, "workerName": { "type": "string", "title": "Worker name" } }, "required": ["cloudflareZone", "workerName"] }, "sinks": { "redirect": { "label": "Redirect", "natural_key": "source", "fields": { "source": { "type": "text", "semantic": "source-url", "required": true }, "target": { "type": "text", "semantic": "target-url", "required": true }, "status": { "type": "select", "semantic": "status-code", "required": true }, "priority": { "type": "integer", "semantic": "priority", "required": false } } } }, "operations": [ { "key": "redirect-sync", "name": "Sync redirects to edge", "endpoint": "/operations/redirect-sync", "grants": ["appsecrets:read", "appconfig:read", "records:read:$redirect", "status:write"] }, { "key": "deploy-worker", "name": "Deploy Cloudflare Worker", "endpoint": "/operations/deploy-worker", "grants": ["appsecrets:read", "appconfig:read", "status:write"], "run_after_install": true }, { "key": "__validate_credentials", "name": "Validate Cloudflare credentials", "endpoint": "/operations/validate-credentials", "grants": ["appsecrets:read"] }, { "key": "__uninstall", "name": "Tear down Cloudflare resources", "endpoint": "/operations/uninstall", "grants": ["appsecrets:read", "appconfig:read", "status:write"] } ], "hooks": [ { "key": "sync-on-create", "name": "Sync on redirect create", "event": "RECORD_CREATED", "filter": { "sinkContract": "redirect" }, "operation": "redirect-sync" }, { "key": "sync-on-update", "name": "Sync on redirect update", "event": "RECORD_UPDATED", "filter": { "sinkContract": "redirect" }, "operation": "redirect-sync" }, { "key": "sync-on-delete", "name": "Sync on redirect delete", "event": "RECORD_DELETED", "filter": { "sinkContract": "redirect" }, "operation": "redirect-sync" } ], "ui": { "placements": [ { "key": "redirect-editor", "target": "MAIN_EDITOR", "model": "$redirect", "tab": "edit", "title": "Redirect editor", "url": "https://redirector.example.com/editor", "replaces_default": true } ] } }

A few things to call out:

  • $redirect placeholders reference the redirect sink contract. They get resolved to a concrete project model key when the console maps the sink.
  • Grants are precise: records:read:$redirect, not records:read with no model. A record grant that names no model is refused at install.
  • run_after_install: true on deploy-worker means the platform auto-runs it once after install (and after __validate_credentials passes).
  • Reserved operation keys (__validate_credentials, __uninstall) start with __. The platform calls them at specific lifecycle moments.

Check it before you serve it

The rules a manifest is held to are the platform’s, so ask the platform. validateAppManifest runs the same validation an install performs, as a dry run, and answers with every problem and where it is:

import { validateAppManifest } from '@foir/sdk/app'; const { ok, issues } = await validateAppManifest({ apiUrl, apiKey: process.env.FOIR_KEY!, manifest });

Any key may ask, a publishable one included. Put it in your build and fail on an ERROR. See The App Client for building the manifest from the platform’s own messages, so a key it does not accept cannot be written at all.

Step 3: Implement operations

Create api/src/routes/operations.ts with the dispatch-token middleware below, and wire your handlers. Each one calls Foir as the operation, with a data client built from the dispatch token, so the service holds no Foir key: its credentials and settings are read from Foir with the token the platform handed it.

import { Hono, type Context } from 'hono'; import { createFoirClient, type FoirOperationGeneratedModule, type FoirSchemaDefinition, } from '@foir/sdk/data'; import { readDispatch, requireScopedToken, ScopedTokenError, type OperationResult, type ScopedTokenIngress, } from '@foir/sdk/server'; // One module per operation, each `foir types --operation <key>`: the surface // that operation's token is served, and nothing another operation declared. import * as deployWorkerTypes from './deploy-worker.generated'; import * as redirectSyncTypes from './redirect-sync.generated'; import * as uninstallTypes from './uninstall.generated'; type Env = { Variables: { ingress: ScopedTokenIngress } }; const app = new Hono<Env>(); app.use('/operations/*', async (c, next) => { try { c.set('ingress', await requireScopedToken(c.req.raw, { expectedProjectId: process.env.FOIR_PROJECT_ID, })); await next(); } catch (err) { if (err instanceof ScopedTokenError) return c.json({ error: err.message }, err.status); throw err; } }); // The data client, as the operation that was dispatched, typed by that // operation's module. A module generated for another operation is refused. const foirFor = <S extends FoirSchemaDefinition>( c: Context<Env>, generated: FoirOperationGeneratedModule<S>, ) => createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch: c.get('ingress').dispatch, generated, }); // This install's stored credentials and its settings, read as the app. async function installOf(foir: ReturnType<typeof foirFor>) { const [credential, install] = await Promise.all([ foir.ns.middleware.appCredential(), foir.ns.middleware.integrationConfig(), ]); return { credentials: JSON.parse(atob(credential.value)) as { cloudflareApiToken: string }, settings: install.config as { cloudflareZone: string; workerName: string }, }; } // __validate_credentials — called before submitted credentials are persisted. // The submitted values are in the dispatch's `input`, because nothing has been // stored yet. app.post('/operations/validate-credentials', async (c) => { const { input } = await readDispatch<{ cloudflareApiToken: string; cloudflareAccountId: string; }>(c.req.raw); const ok = await pingCloudflare(input.cloudflareApiToken, input.cloudflareAccountId); return c.json<OperationResult>({ success: ok, error: ok ? undefined : { code: 'INVALID_CREDENTIALS', message: 'Cloudflare rejected the token' }, }); }); // deploy-worker — runs once at install time. app.post('/operations/deploy-worker', async (c) => { const { credentials, settings } = await installOf(foirFor(c, deployWorkerTypes)); const workerUrl = await deployWorker( credentials.cloudflareApiToken, settings.cloudflareZone, settings.workerName, ); return c.json<OperationResult>({ success: true, result: { workerUrl }, }); }); // redirect-sync — fired by hooks on every redirect record change. app.post('/operations/redirect-sync', async (c) => { const foir = foirFor(c, redirectSyncTypes); const { credentials, settings } = await installOf(foir); // Read every redirect as the operation: the token carries `records:read` for // the model the console mapped `redirect` onto, and nothing else. const records = await fetchAllRedirects(foir); // Push to Cloudflare KV const count = await syncToKv(credentials.cloudflareApiToken, settings.workerName, records); return c.json<OperationResult>({ success: true, result: { redirectCount: count }, }); }); // __uninstall — someone removes the app; we tear down our Cloudflare resources. app.post('/operations/uninstall', async (c) => { const { credentials, settings } = await installOf(foirFor(c, uninstallTypes)); await tearDownWorker(credentials.cloudflareApiToken, settings.workerName); return c.json<OperationResult>({ success: true }); });

This app is installed in one kind of project and generates a client per operation. An app whose models are the installer’s choice, different in every project, uses the app client instead, which names each model at request time.

The token’s grants are exactly what the manifest declared: appsecrets:read (to read the app’s own stored credential), records:read:redirect (after placeholder resolution), appconfig:read and status:write. Foir refuses a call the token does not allow, so the handler needs no per-model check of its own.

Tell the setup screen what the account holds

When a user connects your app, the setup screen runs your __discover operation (or discover) and builds their choices from the answer: which of your sources their account can give, which fields, which locales, and what you suggest for your own settings.

It is handed a DiscoveryRequest (the project’s locale codes as projectLocales, and the install’s current settings as currentSettings, so a run again can keep what the user already confirmed) and answers a DiscoveryResult. Both are published as DiscoveryRequestSchema and DiscoveryResultSchema in @foir/sdk/app/contract. Build the answer from those rather than writing the JSON by hand, because the screen reads it with the same code.

What matters most is saying why when something is missing:

{ "sources": { "user": { "availability": { "state": "AVAILABILITY_STATE_BLOCKED", "reason": { "code": "CUSTOMER_DATA_NOT_APPROVED", "severity": "NOTICE_SEVERITY_ERROR", "title": "This app is not approved to read customers", "detail": "The vendor grants this to the app, not to your account.", "remedy": { "action": "REMEDY_ACTION_RERUN_DISCOVERY", "label": "Check again once it is approved" } } }, "fields": [{ "key": "email", "availability": { "state": "AVAILABILITY_STATE_BLOCKED" } }] } }, "missingAccess": ["read_inventory"] }

A source or field that is not available is shown to the user with its reason and held off, rather than left out: an absent row reads as “your account does not have this”, which is usually false. A result that is not the contract is shown as unreadable, with the parse error, instead of as an account with nothing in it. missingAccess becomes a Connect again button.

Step 4: Build the UI placement

ui/src/App.tsx is your iframe app. The Editor SDK’s EditorProvider handles the postMessage handshake with the host:

import { useEffect, useState } from 'react'; import { EditorProvider, useEditor, useAutoResize } from '@foir/sdk'; function RedirectForm() { const { isReady, init, updateField, requestOperation, setDirty } = useEditor(); const containerRef = useAutoResize({ minHeight: 600 }); const [synced, setSynced] = useState<{ redirectCount: number } | null>(null); if (!isReady || !init) return null; return ( <div ref={containerRef} className="p-6 space-y-4"> <input defaultValue={(init.values.source as string) ?? ''} onChange={(e) => { updateField('source', e.target.value); setDirty(true); }} placeholder="Source URL" /> <input defaultValue={(init.values.target as string) ?? ''} onChange={(e) => { updateField('target', e.target.value); setDirty(true); }} placeholder="Target URL" /> <button onClick={async () => { const result = await requestOperation('redirect-sync', {}); if (result.success) setSynced(result.result as { redirectCount: number }); }} > Sync now </button> {synced && <p>Synced {synced.redirectCount} redirects</p>} </div> ); } export function App() { return ( <EditorProvider parentOrigin="https://app.foir.io"> <RedirectForm /> </EditorProvider> ); }

For sidebar placements, use configMode === 'sidebar' and the selectedFieldKeys / localeContext extras — see Editor SDK Examples.

Step 5: Deploy

Deploy the API to whatever you like — Cloudflare Workers, Render, Fly, Vercel. The middleware needs to be reachable at the URL declared in your manifest’s middleware.url.

cd redirector/api npm run build # Deploy with your platform of choice

Deploy the UI as static assets (Cloudflare Pages, Netlify, Vercel, S3+CloudFront). The URL needs to match your manifest’s placement url.

Host manifest.json somewhere reachable (S3, Cloudflare Pages, your own domain). One file, no build pipeline required.

Your service holds no signing secret: dispatches are verified with requireScopedToken, and async callbacks are signed with the run’s own callback.signingKey.

Step 6: Test the install

From a Foir project, install the app:

foir apps install https://redirector.example.com/manifest.json \ --sink-map '{"redirect":{"toModel":"redirect","naturalKey":"sourcePattern","fields":{"source":"sourcePattern","target":"targetPattern","status":"statusCode","priority":"priority"}}}'

Or from foir.config.ts:

apps: { redirector: { source: 'https://redirector.example.com/manifest.json', settings: { cloudflareZone: 'bobscountrybunker.com', workerName: 'foir-redirects-bcb' }, mappings: { sinks: { redirect: { toModel: 'redirect', naturalKey: 'sourcePattern', fields: { source: 'sourcePattern', target: 'targetPattern', status: 'statusCode', priority: 'priority', }, }, }, }, }, },
foir push

Then write the credentials from the app’s detail page in the console. Once credentials land, __validate_credentials runs first; if it returns success, deploy-worker runs next (because of run_after_install: true). Both calls hit your middleware with a scoped token in X-Foir-Token.

After that, every record write on the mapped redirect model fires redirect-sync via the hooks.

Step 7: Update flow

Bump your manifest’s version and adjust whatever you need (new operation, new field, new placement). Projects that have your app installed run:

foir apps update redirector --dry-run

…to see the review: what changes, classified as safe, confirm or rejected, and what your app gains. Without --dry-run it applies an update that gives your app nothing more. One that gives it more (a grant, a new operation’s grants, a hook, an inbound route) is applied only when the user runs it again with the --accept-gains code the review prints, so say in your release notes what a version asks for and why.

The platform never silently re-fetches your manifest. Every update is explicit.

Step 8: Publish

Your manifest URL is the publish step. Anyone who has it can install your app; nothing has to approve that, and nothing about your app is registered with Foir until you ask for it to be.

  • Add the manifest URL to your README
  • Share it with specific projects

Getting listed in the marketplace

The marketplace is curated, not self-serve. There is no submission endpoint and no queue: listings are created by Foir staff, so ask us and we will look at your manifest.

Being listed adds discovery metadata — a name, a summary, an icon, a category, an ordering. It adds nothing functional. What your app can read and write is resolved live from your manifest every time somebody views the listing, never copied into it, so a listing cannot describe your app as touching something it does not. The consequence for you is that updating your manifest updates what your listing says, with no listing edit and no re-approval.

Unlisted stays a first-class route. An app for one client, an internal tool, or one you are still building installs from its URL exactly as a listed one does.

Tips

  • Keep the manifest minimal. If you don’t need credentials, omit them. If you don’t need middleware, omit it. Color-picker apps are six lines of JSON.
  • Use __validate_credentials for any app where the validity of the credentials isn’t visible until the first real call. Surface the error early.
  • Use run_after_install: true for one-time setup operations. Nobody has to remember to click Trigger after install.
  • Use replaces_default: true on MAIN_EDITOR placements when your custom editor fully owns the record-authoring surface (Redirector). Skip it for tabs that augment the default editor (Shopify “Open in admin” deep-link).
  • Use sinks for outbound, sources for inbound. Redirector is a sink: project owns the data, app pushes it out. Shopify is a source: external owns the data, app brings it in.
  • Use placeholders for grants and filters. records:read:$redirect and { sinkContract: 'redirect' } resolve at install. They let one manifest install into many projects with different mapped model keys.
  • Use runs_on_mapped_sources: true on an operation that covers several sources and can work with whichever of them the console mapped, such as one sync for products, collections and users. Declining users then leaves the user grants out, and the sync keeps running for products and collections. Without it, the whole operation is dropped. Such an operation finds each model by its source name in the install’s mappings (appconfig:read), never by its position in the list of grants, because a declined source’s entry is missing.

Next Steps

Last updated on