# Supabase apps

> Watch an app built on Supabase, from the browser's calls to your database through to Edge Functions, with database calls as spans and people identified from Supabase Auth.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://telemetry.docs.sypnia.com/guides/supabase/

This guide is for an app whose backend is Supabase: the browser talks to Supabase directly, and maybe to a few Edge Functions. It works with Sypnia Cloud and with a self-hosted engine; add `endpoint` to each `init` for your own engine.

**At the end you will have:** every call from the page to your Supabase project recorded with its table and its status, failed calls (a row-level security rule that says no, a missing column) turned into problems, people identified from Supabase Auth, and your Edge Functions traced with their own database calls.

**You need:** the [browser SDK](https://telemetry.docs.sypnia.com/sdks/browser) installed, and your Supabase project's URL, such as `https://abcdefghijkl.supabase.co`.

## In the browser

By default the SDK records calls to your own origin only. Your Supabase project is another origin, so name it.

`src/main.ts`

```ts
import { init } from '@sypnia/telemetry/browser';

const SUPABASE_URL = 'https://abcdefghijkl.supabase.co';

init({
  project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e',
  environment: location.hostname === 'shop.example' ? 'production' : 'development',
  recordTargets: [SUPABASE_URL],
  traceTargets: [`${SUPABASE_URL}/functions/v1/`],
});
```

| Option          | Covers                                                                                                       | Adds headers?                                                                                                      |
| --------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| `recordTargets` | Everything `supabase-js` calls: the database (`/rest/v1/…`), Auth (`/auth/v1/…`), Storage (`/storage/v1/…`). | No. Supabase's own services may refuse headers they do not know, and then your calls would fail.                   |
| `traceTargets`  | Your Edge Functions (`/functions/v1/…`).                                                                     | Yes: `traceparent` and `x-sypnia-session`, so the function joins the trace. You allow them in the function, below. |

You change nothing in how you create or use the Supabase client.

### What a database call looks like in Sypnia

`supabase.from('orders').insert(order)` refused by a row-level security rule becomes this event:

```json
{
  "type": "request",
  "method": "POST",
  "host": "abcdefghijkl.supabase.co",
  "path": "/rest/v1/orders",
  "status": 403,
  "dur": 87,
  "code": "42501",
  "msg": "new row violates row-level security policy for table \"orders\""
}
```

- **The table is in the path**, so Performance lists `POST /rest/v1/orders` with its speed and its failures, and a problem can say which table refused.
- **The filter is never sent.** Supabase puts filters in the query string (`?email=eq.ada@example.com`), and the SDK never records a query string.
- **In the browser, only the code and the message** are read from a failed answer, with e-mail addresses replaced. The `details` and `hint` fields, which can repeat the row that failed, are never read there; the server SDK keeps them, below. Row data and request bodies are never sent.
- **Realtime** connections are not recorded: they are not requests.

Which answers count as failures: no answer, `400`, and `500` or above. A call with no answer opens a problem only once the same call has failed for 3 people within an hour (see [Problems](https://telemetry.docs.sypnia.com/concepts/problems#what-counts-as-a-failure)). A `401` or a `404` is an answer. An insert that row-level security refuses is recorded with its `403`, its code and its message, and is counted in Performance among that route's `4xx` answers; it becomes a problem when your code throws because of it, which most code does.

### Identify people from Supabase Auth

`src/auth.ts`

```ts
import { identify } from '@sypnia/telemetry/browser';
import { supabase } from './supabase';

supabase.auth.onAuthStateChange((_event, session) => {
  if (session) identify({ person: { id: session.user.id } });
  else identify(null);
});
```

The id is Supabase's user id, a UUID. Add `email: session.user.email` only if you want e-mail addresses in Sypnia; see [Identifying people](https://telemetry.docs.sypnia.com/sdks/identifying-people). `onAuthStateChange` also fires when the page loads with a signed-in user, so this one place is enough.

## In Edge Functions

Edge Functions are functions from a `Request` to a `Response`, which is what `wrapFetchHandler` of the Node SDK traces. Import it with the `npm:` prefix.

`supabase/functions/checkout/index.ts`

```ts
import { createClient } from 'npm:@supabase/supabase-js@2';
import { init, wrapFetchHandler } from 'npm:@sypnia/telemetry/node';

init({
  project: Deno.env.get('SYPNIA_PROJECT_KEY'),
  service: 'checkout-function',
  environment: Deno.env.get('SYPNIA_ENVIRONMENT') ?? 'production',
});

const cors = {
  'Access-Control-Allow-Origin': 'https://shop.example',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, traceparent, x-sypnia-session',
};

Deno.serve(wrapFetchHandler(async (request: Request) => {
  if (request.method === 'OPTIONS') return new Response('ok', { headers: cors });

  const publishableKey = JSON.parse(Deno.env.get('SUPABASE_PUBLISHABLE_KEYS')!).default;
  const supabase = createClient(Deno.env.get('SUPABASE_URL')!, publishableKey, {
    global: { headers: { Authorization: request.headers.get('Authorization')! } },
  });

  const { data: cart, error } = await supabase.from('carts').select('id, total_cents').single();
  if (error) throw error;

  const payment = await fetch('https://payments.example/v1/payments', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ amount: cart.total_cents }),
  });

  return Response.json({ ok: payment.ok }, { status: payment.ok ? 200 : 502, headers: cors });
}));
```

```bash
supabase secrets set SYPNIA_PROJECT_KEY=spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e
supabase functions deploy checkout
```

Two lines are the whole integration: `init`, and `wrapFetchHandler` around your handler. The third thing to get right is the CORS header: **add `traceparent` and `x-sypnia-session` to `Access-Control-Allow-Headers`**. Without them the browser refuses to call the function once it is listed in `traceTargets`.

What you get for one call to this function:

```text
click «Pay $64.00»                                        browser
└─ POST /functions/v1/checkout            3,842 ms  502   checkout-function
   ├─ SELECT carts                           12 ms  ok    database
   └─ POST /v1/payments                   3,790 ms  400   payments.example   <- failed
```

- **Database calls are spans.** The SDK recognizes Supabase's database address (`/rest/v1/…`) and makes the call a `db` span, named by operation and table: `SELECT carts`, `INSERT orders`, `UPDATE carts`, `DELETE cart_items`, `CALL create_order` for a database function called with `rpc()`. It carries the database attributes and `sypnia.db.via` `postgrest` (see [semantic conventions](https://telemetry.docs.sypnia.com/reference/semantic-conventions#sypnia.db.via)).
- **A database error keeps its message.** When a database call answers with an error, the span keeps Supabase's `code` and its full `message`, values included, followed by its `details` and `hint` on lines of their own (`Detail: Key (email)=(maria@example.com) already exists.`). It is on by default and can contain personal data, such as an e-mail the database repeated; `captureDbErrors: false` in `init` turns it off. See [Database error details](https://telemetry.docs.sypnia.com/sdks/node#database-error-details).
- **Other calls are spans too**, named by method and path.
- **Errors** thrown by the handler are reported with their stack, and the request is marked failed.
- **The person** comes from the browser session that made the call. You do not identify again.

The spans are exported as OTLP, in protobuf, after the response, using the platform's way to keep a function alive for background work, which on Supabase is `EdgeRuntime.waitUntil`. Where it is missing, the SDK waits at most 50 ms. If you see spans missing from short functions, call `await flush()` before returning. Supabase's local runtime stops a function after each request, so background work can be cut short while you test with the Supabase CLI.

## What this does not cover

| Not covered                                                                      | Why                                                                                                             | Today's answer                             |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| What happens inside Postgres: triggers, database functions, slow queries by plan | Sypnia sees calls to the database, not the database's inside.                                                   | Supabase's own database reports.           |
| Database webhooks and scheduled functions that no browser called                 | They run, and are traced if they are Edge Functions with the wrapper, as traces of their own without a session. | —                                          |
| Calls made by Supabase's services to each other                                  | They are not your app's calls.                                                                                  | —                                          |
| A native mobile app using Supabase                                               | There is no native Sypnia SDK.                                                                                  | A web-view app works with the browser SDK. |

## Check that it works

### 1. The database calls are recorded

Open your app with `debug: true` in `init` and do something that reads or writes data.

**You should see:**The console prints `request` events with `host` set to your Supabase host and `path` starting with `/rest/v1/`.

### 2. Your own calls still work

Call an Edge Function from the page.

**You should see:**It answers as before. If the browser's console shows a CORS error that names `traceparent`, the function's `Access-Control-Allow-Headers` is missing the two headers.

### 3. The trace is joined

Within 10 minutes, open the trace of that call in Sypnia.

**You should see:**One trace: the browser's call, the function's request under it, and the function's database calls under that.
