# Supabase + Dizo

> Enrich rows as they land in Postgres: a Supabase Database Webhook calls an Edge Function that queries Dizo and writes the result back.

Type: REST recipe — base URL `https://api.dizo.ai/v1`. No native app needed.

## Steps
1. Store your key as a secret: `supabase secrets set DIZO_API_KEY=dz_live_...`.
2. Create the Edge Function below with `supabase functions new enrich-lead`, then `supabase functions deploy enrich-lead`.
3. In the Dashboard, create a Database Webhook on your `leads` table for INSERT events that calls the `enrich-lead` Edge Function.
4. Insert a test row and check that `title`, `seniority` and `dizo_status` are filled in.

## Where to go
`supabase functions new enrich-lead`, set `DIZO_API_KEY` with `supabase secrets set`, deploy, then add a Database Webhook.

Open the Supabase Edge Functions quickstart: https://supabase.com/docs/guides/functions/quickstart

## supabase/functions/enrich-lead/index.ts
```
import { createClient } from "npm:@supabase/supabase-js@2";

const db = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);

Deno.serve(async (req) => {
  const { type, record } = await req.json(); // Database Webhook payload
  if (type !== "INSERT" || !record.email) return new Response("skip");

  const res = await fetch("https://api.dizo.ai/v1/people/enrich", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${Deno.env.get("DIZO_API_KEY")}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `lead-${record.id}`,
    },
    body: JSON.stringify({ email: record.email, max_credits: 2 }),
  });

  if (res.status === 404) {
    await db.from("leads").update({ dizo_status: "not_found" }).eq("id", record.id);
    return new Response("not found (not charged)");
  }
  if (!res.ok) return new Response(await res.text(), { status: res.status });

  const { person } = await res.json();
  await db.from("leads").update({
    title: person.title, seniority: person.seniority, dizo_status: "enriched",
  }).eq("id", record.id);
  return new Response("ok");
});
```

## Database Webhook (Dashboard)
```
Name:    enrich_new_leads
Table:   public.leads
Events:  INSERT
Type:    Supabase Edge Functions → enrich-lead
Payload: { type, table, schema, record, old_record }
```

## Notes
- Keep the Dizo key in Edge Function secrets, never in client code or a table the browser can read.
- For a backfill of an existing table, send the rows to `POST /v1/batch` once instead of firing the webhook row by row.

## Related API docs
- [/docs/people-enrich](https://dizo.ai/docs/people-enrich.md)
- [/docs/batch](https://dizo.ai/docs/batch.md)
- [/docs/keys](https://dizo.ai/docs/keys.md)


## Supabase as the home for your GTM data

Supabase is a Postgres development platform. Each project gives you a full Postgres database plus authentication, storage, auto-generated APIs and Edge Functions, which are server-side TypeScript functions that run on Deno. Many product teams already keep their signups, trial accounts and waitlist entries in Supabase tables, which makes the database the natural place to attach enrichment.

This integration does not install anything into Supabase. It uses two features Supabase documents for exactly this kind of job. A Database Webhook fires after a row is inserted, updated or deleted, and it can call an Edge Function directly with the changed row as the request body. The Edge Function then calls Dizo's REST API at `https://api.dizo.ai/v1` with an ordinary `fetch` and writes the answer back to the same row.

## Why enrich at the database layer

A signup row usually holds an email and a timestamp. Everything you want to do next, such as routing a lead to sales, deciding whether a trial deserves a call, or personalizing onboarding, depends on fields you do not have yet: title, seniority, department, company size and industry. If enrichment happens in a separate tool after an export, those fields arrive late and live somewhere else. Enriching in the database means every downstream query, dashboard and app screen sees the same complete row.

The trigger model also keeps the cost honest. Each insert produces at most one Dizo call, and [person enrich](/docs/people-enrich) charges 2 credits only when a person is matched. A personal address that matches nobody returns `404` and costs nothing, so your function records `not_found` and moves on. There are no seats and no monthly plan to size; you pay per record that actually comes back with data.

## What you can build

The page's function enriches a person from an email. The same webhook-plus-function pattern covers other jobs by changing the endpoint and the columns you write:

- Fill `title`, `seniority` and `department` on every new signup so product-qualified lead queries can filter on role.
- Turn the domain of a new workspace into a company profile with `GET /v1/companies/{domain}`, 1 credit only if found, and store headcount and industry.
- Identify a signup on insert with `POST /v1/people/enrich` from the email, at 2 credits only if matched, and store the title, seniority and employer next to the row before your onboarding emails go out.
- Add a mobile number only for rows marked high intent, by checking a column in the function before you include `"phone"`.
- Register signups who become paying customers on a job-change watchlist with `POST /v1/signals/watch`, so you hear when a champion moves.
- Add customer domains to your Dizo suppression list when an account converts, so prospecting searches never return people you already sell to.

## Setting it up step by step

Start with the secret. Run `supabase secrets set DIZO_API_KEY=dz_live_...` from your project directory. Supabase makes secrets available to deployed functions immediately and exposes them through `Deno.env.get`. Supabase also provides `SUPABASE_URL` and a service role key to Edge Functions by default, which is what the function uses to write back to the table. Both bypass Row Level Security, so they belong in server-side code only.

Next, create the function with `supabase functions new enrich-lead`, replace its contents with the code on this page, and deploy it with `supabase functions deploy enrich-lead`. The function reads the webhook payload, which Supabase documents as `type`, `table`, `schema`, `record` and `old_record`. For an insert, `record` is the new row and `old_record` is null.

Then open the Dashboard and create a Database Webhook. Name it, pick your `leads` table, select the INSERT event and choose your Edge Function as the target. Supabase builds Database Webhooks on top of the `pg_net` extension, so the HTTP call happens asynchronously after the row is committed and does not slow down the insert itself.

Finally, insert a test row with a known work email and watch the columns fill in. [Sign up](/signup) for a live key and 250 free credits, with no card. Until then, a `dz_test_` key returns synthetic data for free, which is enough to build and test the whole flow.

## Controlling spend

A trigger runs every time a row arrives, so put the limits in place before the webhook goes live. The function sends `max_credits: 2` on each request, which matches the cost of a matched person without email or phone add-ons. If you later add `include: ["phone"]`, raise it to 12: 2 for the match plus 10 for a phone that is found. The request can never spend more than that ceiling.

Create a key just for this function through [API keys](/docs/keys) with `data:read` scope, a daily and monthly credit cap, a per-request ceiling and an allow-list containing only `/v1/people/enrich`. If a bulk import fires thousands of inserts at once, the daily cap stops the spending and Dizo returns a 402 rather than draining the balance. An account-wide monthly USD cap sits above that, and auto-refill never exceeds it.

Worked numbers at the $10–$499 tier, $0.025 per credit, assuming a 60% match rate on mixed signup emails:

- **1,000 signups a month, profile only:** 600 matches × 2 = 1,200 credits, or $30. The 400 misses cost nothing.
- **Same volume with phones for 100 high-intent rows:** 1,200 + (100 × 10) = 2,200 credits, or $55, if every phone is found.
- **Work emails for 200 matched signups who used personal addresses:** add `include: ["email"]` (and raise `max_credits` to 3). If 150 are found, 1,200 + 150 = 1,350 credits, or $33.75. Emails not found add nothing.

## Example workflows

**Product-qualified leads.** Your app writes a row to `signups` on account creation. The webhook calls the function, which enriches the email and stores seniority. A Postgres view selects director-and-above signups at companies over a headcount threshold, and your sales team works from that view. The enrichment happens once per row, so the view stays cheap to query.

**Workspace firmographics.** When a row is inserted into `workspaces`, a second function calls domain to company with the workspace's domain. It stores industry, headcount and funding stage on the workspace. Onboarding screens read those columns to pick a template, and the cost is 1 credit per workspace whose domain is found.

**Backfilling an existing table.** Webhooks only fire on new changes, so older rows need a one-off job. Select the rows missing a title, send them as one [batch](/docs/batch) of up to 10,000 items with a `webhook_url` pointing at another Edge Function, and write results from the JSONL file when the `batch.completed` event arrives. Misses are still free in a batch.

## Troubleshooting

If nothing happens after an insert, check that the webhook is attached to the right schema and table and that INSERT is selected, then look at the function's logs in the Dashboard to see whether it was invoked at all. If the function runs but Dizo returns 401, the secret is missing or misnamed: `Deno.env.get("DIZO_API_KEY")` must match the name you set, and the header value must be the word `Bearer`, a space, then the key.

A 402 means a cap was reached, not a code bug. Check your balance and limits with the free `GET /v1/billing` endpoint before changing the function. A 404 is a normal not-found result and should not be retried. For other errors, Dizo returns a stable `error.code` and a plain-English `error.fix`; retry only when `error.retryable` is true. Because the function sends an `Idempotency-Key` built from the row id, a retried request within 24 hours is never charged twice.

If the update to the row fails, confirm the column names exist and that the client is using the service role key rather than an anon key, which Row Level Security would block.

## Security practices

Never call Dizo from browser code that uses the Supabase client, even with a test key. Keep every Dizo call inside Edge Functions where the key lives in secrets. Do not store the key in a table, even a private one, because a policy mistake could expose it. Rotate the key in the Dizo console if you suspect it leaked, then run `supabase secrets set` again; deployed functions pick up the new value without a redeploy.

Keep billing scopes off the function's key. Keys are read-only for billing by default, and the account owner can lock billing entirely. If enriched data turns out wrong, such as a bounced email or an outdated title, report it through `POST /v1/feedback`; confirmed reports are credited back. Read [trust](/trust) for how Dizo handles opt-outs and data-subject requests.

## FAQ

### Is there a native Dizo extension or integration in Supabase?
No. You connect the two with a Database Webhook and an Edge Function that calls Dizo's REST API with `fetch`. You own the function, so the logic and the columns it writes are entirely up to you.

### Does the enrichment slow down inserts?
No. Supabase runs Database Webhooks after the row is changed, using the `pg_net` extension, so the insert commits first and the HTTP call to your function happens asynchronously.

### What does it cost when Dizo cannot match a signup?
Nothing. Person enrich charges 2 credits only when a person is matched. An unmatched email returns `404`, and the function writes `not_found` to the row instead of retrying.

### Can I use the Dizo MCP server from Supabase?
Edge Functions are plain server code, so the simple path is the REST API shown here. If you build an AI agent inside a function, you could connect it to `https://mcp.dizo.ai/mcp` with an MCP client library, but for row-by-row enrichment REST is simpler.

### How do I enrich rows that already exist?
Webhooks only fire on new changes. Select the rows you want, send them to `POST /v1/batch` as one job of up to 10,000 lookups, and write the results back when the completion webhook arrives.

### How do I stop a large import from spending too much?
Give the function's key a daily cap, a monthly cap and a per-request ceiling, and send `max_credits` on every call. When a cap is hit, Dizo returns a 402 and stops charging.
