Build your first plugin
Build a standalone Cloudflare Worker with persistent purchase recording, tenant-scoped reads, and local HTTP exercises.
Build acme, a plugin that records variant sales in Cloudflare D1. D1 is a persistent SQL database.
The example includes these surfaces:
- A purchase webhook records each order and variant once.
- An admin endpoint lists a store's recent purchases.
- A storefront-public endpoint returns a variant's sold quantity.
- A health endpoint exercises the database.
No Novinzo package, repository checkout, platform secret, or Cloudflare account is required for the local exercises. Use Node.js 22 or later and its bundled npm.
Local fixtures are not platform integration
Local requests bypass Novinzo's dispatch and authentication. The local-fixture-only token below
is fake and unusable against live core. Novinzo attaches signed invocation tokens to real
requests. Plugin authors never mint those tokens or receive signing secrets.
What you'll create
Create this standalone directory:
acme-plugin/
package.json
wrangler.jsonc
migrations/0001_purchases.sql
src/index.js
test/purchases.test.mjsThe Worker has no public production URL. Novinzo dispatches known plugin surfaces after registration and installation. See Plugin system for routing boundaries.
Steps
Create the standalone project
Create acme-plugin, then save these files inside it.
{
"name": "acme-plugin",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev --port 8787",
"db:local": "wrangler d1 migrations apply DB --local",
"test": "node --test test/*.test.mjs"
}
}Install the public Cloudflare CLI:
npm install --save-dev wrangler@4Commit the generated lockfile with your project.
Create the Worker app
This configuration runs locally without a remote database. Wrangler 4 needs no database_id for a local D1 database.
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "acme-plugin",
"main": "src/index.js",
"compatibility_date": "2026-05-15",
"workers_dev": false,
"preview_urls": false,
"d1_databases": [
{
"binding": "DB",
"database_name": "acme-local",
"migrations_dir": "migrations",
},
],
}Keep workers_dev and preview_urls false in every deployed environment.
Do not deploy this local configuration as a registered plugin.
Define the D1 schema
Every purchase key includes the store. Concurrent duplicate deliveries hit the same primary key. Deleted variants retain a tombstone. A tombstone is a permanent deletion marker. This prevents late purchase deliveries from restoring deleted sales.
CREATE TABLE purchases (
store_id TEXT NOT NULL,
order_id TEXT NOT NULL,
variant_id TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
purchased_at TEXT NOT NULL,
PRIMARY KEY (store_id, order_id, variant_id)
);
CREATE INDEX purchases_recent ON purchases (store_id, purchased_at DESC);
CREATE INDEX purchases_variant ON purchases (store_id, variant_id);
CREATE TABLE deleted_variants (
store_id TEXT NOT NULL,
variant_id TEXT NOT NULL,
PRIMARY KEY (store_id, variant_id)
);The example retains purchase rows for deduplication and history. Deleted variants disappear from reads.
Define a retention policy before storing additional customer information.
This example does not store customerId.
Implement the handlers
Save the complete Worker below. It accepts the live purchase payload, including its required customer UUID. The example's admin and storefront response formats belong to this plugin, not to Novinzo's shared contract.
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const uuid = (value) => typeof value === "string" && UUID.test(value);
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
const error = (status, tag, fields = {}) => Response.json({ _tag: tag, ...fields }, { status });
export default {
async fetch(request, env) {
const path = new URL(request.url).pathname;
try {
if (path === "/health" && request.method === "GET") {
await env.DB.prepare("SELECT 1").first();
return Response.json({ status: "ok" });
}
const webhook =
request.method === "POST" &&
["/webhooks/variant-purchased", "/webhooks/variant-deleted"].includes(path);
const sales = /^\/storefront-public\/variants\/([^/]+)\/sales$/.exec(path);
const read = request.method === "GET" && (path === "/admin/purchases" || sales);
if (!webhook && !read) return error(404, "NotFound");
// Private dispatch supplies real tokens. Presence is not signature verification.
if (!request.headers.get("x-novinzo-plugin-invocation")) {
return error(401, "MissingInvocation");
}
if (webhook) {
if (request.headers.get("content-type")?.split(";")[0].trim() !== "application/json") {
return error(415, "UnsupportedMediaType");
}
let payload;
try {
payload = await request.json();
} catch {
return error(400, "InvalidPayload");
}
if (!object(payload)) {
return error(400, "InvalidPayload");
}
// The trusted store header; an older sender names the store only in the payload.
const storeId = request.headers.get("x-novinzo-store-id") ?? payload.storeId;
if (!uuid(storeId) || !uuid(payload.variantId)) {
return error(400, "InvalidPayload");
}
if (path === "/webhooks/variant-deleted") {
await env.DB.prepare(
`INSERT INTO deleted_variants (store_id, variant_id)
VALUES (?, ?) ON CONFLICT DO NOTHING`,
)
.bind(storeId, payload.variantId)
.run();
} else {
if (
!uuid(payload.customerId) ||
!uuid(payload.orderId) ||
!Number.isSafeInteger(payload.quantity) ||
payload.quantity <= 0
) {
return error(400, "InvalidPayload");
}
await env.DB.prepare(
`INSERT INTO purchases
(store_id, order_id, variant_id, quantity, purchased_at)
SELECT ?, ?, ?, ?, ? WHERE NOT EXISTS
(SELECT 1 FROM deleted_variants WHERE store_id = ? AND variant_id = ?)
ON CONFLICT (store_id, order_id, variant_id) DO NOTHING`,
)
.bind(
storeId,
payload.orderId,
payload.variantId,
payload.quantity,
new Date().toISOString(),
storeId,
payload.variantId,
)
.run();
}
// Acknowledge only after the durable write completes.
return new Response(null, { status: 204 });
}
const storeId = request.headers.get("x-novinzo-store-id");
if (!uuid(storeId)) {
return error(400, "MissingStoreIdError", {
reason: storeId === null ? "missing-header" : "invalid-uuid",
});
}
if (path === "/admin/purchases") {
const { results } = await env.DB.prepare(
`SELECT order_id AS orderId,
variant_id AS variantId, quantity, purchased_at AS purchasedAt
FROM purchases p WHERE store_id = ? AND NOT EXISTS
(SELECT 1 FROM deleted_variants d
WHERE d.store_id = p.store_id AND d.variant_id = p.variant_id)
ORDER BY purchased_at DESC, order_id, variant_id LIMIT 100`,
)
.bind(storeId)
.all();
return Response.json(results);
}
const variantId = sales[1];
if (!uuid(variantId)) return error(400, "InvalidVariantId");
const row = await env.DB.prepare(
`SELECT COALESCE(SUM(quantity), 0) AS sold
FROM purchases p WHERE store_id = ? AND variant_id = ? AND NOT EXISTS
(SELECT 1 FROM deleted_variants d
WHERE d.store_id = p.store_id AND d.variant_id = p.variant_id)`,
)
.bind(storeId, variantId)
.first();
return Response.json({ sold: row.sold });
} catch {
return error(500, "UnexpectedError");
}
},
};Novinzo supplies x-novinzo-store-id on admin and storefront requests. Never use a query parameter or body field as their tenant identity.
Webhooks carry that header too. Use payload.storeId only on a delivery without it, from an older sender.
On a store domain, shoppers read /plugins/acme/storefront-public/variants/<variantId>/sales.
Novinzo forwards that request to /storefront-public/variants/<variantId>/sales and supplies its tenant context.
The local direct URL below exercises only the Worker's internal surface.
The invocation token identifies the plugin and store when calling backend or core-for-plugins, in every environment. This Worker makes no platform calls and does not decode or authenticate tokens itself. Its deployed security boundary requires private Novinzo dispatch, not a public HTTP listener. The header-presence guard alone does not authenticate callers.
Database failures return 500. Novinzo retries retryable webhook failures, so the unique key makes repeated writes safe.
The storefront route returns only a count. It never exposes order or customer data.
Run it locally
Apply your plugin's local schema, then start Wrangler:
npm run db:local
npm run devIn another terminal, send a protocol fixture:
STORE=7d5c4a7e-1f0b-4c35-9a52-1b2f0e8d9c41
VARIANT=0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90
curl -i http://localhost:8787/webhooks/variant-purchased \
-H 'content-type: application/json' \
-H 'x-novinzo-plugin-invocation: local-fixture-only' \
-d '{"storeId":"'"$STORE"'","variantId":"'"$VARIANT"'","customerId":"3c1e9a52-7b4d-4f80-a6e2-5d0c8b7f1a23","orderId":"9e2d7b14-5c3a-4b6f-8d01-7a9c2e4f6b85","quantity":2}'
curl -s http://localhost:8787/admin/purchases \
-H "x-novinzo-store-id: $STORE" \
-H 'x-novinzo-plugin-invocation: local-fixture-only'
curl -s "http://localhost:8787/storefront-public/variants/$VARIANT/sales" \
-H "x-novinzo-store-id: $STORE" \
-H 'x-novinzo-plugin-invocation: local-fixture-only'
curl -s http://localhost:8787/healthThe webhook returns 204, sales returns {"sold":2}, and health returns {"status":"ok"}.
Repeat the webhook. The admin list still contains one purchase, and the count remains two.
Restart Wrangler without removing its local storage. The purchase remains recorded.
These requests exercise local routing and storage. They do not exercise Novinzo installation, dispatch, signed tokens, or seller authorization.
Test it
Follow Testing plugins to create test/purchases.test.mjs.
Run npm test while npm run dev remains running.
The tests use the same local D1 database with fresh store identifiers.
Register the plugin in the catalog
Coordinate registration with Novinzo. There is no public self-service provisioning API.
Provide your plugin code, intended surfaces, webhook subscriptions, storage requirements, and requested platform permissions.
For this example, request variant-purchased and variant-deleted subscriptions.
Novinzo coordinates the registered Worker identity, hosting, staging installation, and production deployment. You do not need access to Novinzo's database or deployment credentials. See Registration, installs and permissions.
If the plugin is for your own store, skip the coordination: create it under Settings → Apps, add a novinzo.plugin.json and deploy it from your repository with npx @emergente-labs/plugin-cli deploy. See Your own plugins.
Wire the plugin into the platform
Replace the local D1 configuration with the resources agreed with Novinzo before deployment. Keep all deployed plugin endpoints private.
If you add platform calls, Novinzo provisions the CORE_FOR_PLUGINS service binding.
Forward the incoming invocation token unchanged through that binding.
Neither binding properties nor x-novinzo-plugin-name establish platform-call identity.
No cron or background task has store access without a current platform invocation.
See Calling the platform for HTTP requests and Deployment for coordinated rollout. Run the staging acceptance exercises in Testing plugins before production release.
