# Supabase Auth

URL: https://iscredible.com/docs/integrations/supabase

> Check every new Supabase user before it is created, with a Before User Created auth hook and an Edge Function.

Supabase Auth can call your code before it creates a user, through its **Before User Created** auth hook. Point that hook at an Edge Function that asks isCredible, and blocked signups never become rows in `auth.users`.

## How it works

1. Someone signs up: email or phone, OAuth, SSO or an anonymous sign-in.
2. Before creating the user, Supabase Auth sends a signed request to your Edge Function with the new user's details and the client's IP address.
3. Your function calls isCredible and either lets the signup through or rejects it with a message.

The hook runs only when a new user would be created, not when existing users sign in. Users you create from your own server with the admin API don't go through it, so check those yourself.

## 1. Write the Edge Function

supabase/functions/before-user-created/index.ts:

```typescript
import { Webhook } from "https://esm.sh/standardwebhooks@1.0.0";
import { IsCredibleClient, decide } from "npm:is-credible";

const hook = new Webhook(Deno.env.get("BEFORE_USER_CREATED_HOOK_SECRET")!.replace("v1,whsec_", ""));
const iscredible = new IsCredibleClient({
  apiKey: Deno.env.get("ISCREDIBLE_API_KEY")!,
  timeoutMs: 2500, // Supabase waits about 5 seconds for HTTP hooks
  maxRetries: 0
});

const json = (body: unknown, status = 200) =>
  new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });

Deno.serve(async (req) => {
  const payload = await req.text();
  let event: any;
  try {
    event = hook.verify(payload, Object.fromEntries(req.headers));
  } catch {
    return json({ error: { http_code: 401, message: "Invalid signature" } }, 401);
  }

  const user = event.user ?? {};
  try {
    const result = await iscredible.verify({
      email: user.email || undefined,
      phone: user.phone || undefined,
      ip: event.metadata?.ip_address,
      deviceId: user.user_metadata?.device_id, // optional, see below
      eventType: "signup",
      accountCreation: true
    });
    if (decide(result).action === "DENY") {
      return json({ error: { http_code: 403, message: "We couldn't create your account." } });
    }
  } catch (err) {
    console.warn("isCredible unavailable, allowing signup", err); // fail open
  }
  return json({});
});
```

To let a signup through, return an empty JSON object. To reject it, return an `error` object: Supabase Auth refuses the signup with the `http_code` and `message` you set, and your client receives that message.

## 2. Deploy it and set the secrets

```bash
supabase functions deploy before-user-created --no-verify-jwt
supabase secrets set ISCREDIBLE_API_KEY=your_api_key
```

`--no-verify-jwt` is needed because Supabase Auth signs hook requests with a webhook secret, not a user token. The function checks that signature itself.

## 3. Turn on the hook

1. In the Supabase dashboard, open **Authentication** and find the auth hooks settings.
2. Add a **Before User Created** hook, choose **HTTPS**, and enter your function's URL.
3. Generate the hook secret and save it as a function secret:

```bash
supabase secrets set BEFORE_USER_CREATED_HOOK_SECRET="v1,whsec_..."
```

## Send a device ID (optional)

A device ID makes repeat-account detection much stronger. Pass one from the browser as user metadata when you sign up, and the hook receives it in `user.user_metadata`:

```typescript
await supabase.auth.signUp({
  email,
  password,
  options: { data: { device_id: getDeviceId() } } // see "Send device signals"
});
```

See [Send device signals](https://iscredible.com/docs/guides/device-signals) for `getDeviceId`. User metadata is visible to the user, so don't put anything else sensitive there.

## Acting on the decision

The hook can only allow or reject. For **REVIEW**, let the signup through and hold back the valuable part in your app: keep **Confirm email** turned on in Supabase, and grant free credits or API keys only after confirmation. To branch on REVIEW inside the hook, record it in your own table keyed by email, then read it after the user confirms.

| Decision | In the hook | In your app |
|---|---|---|
| APPROVE | Return `{}` | Nothing extra |
| REVIEW | Return `{}` | Grant credits only after email or phone confirmation |
| DENY | Return the `error` object | Show the message from Supabase Auth |

## Errors and limits

The hook has a short time budget, so the function above uses a 2.5 second timeout and no retries, and lets the signup through on any error.

| Situation | What to do |
|---|---|
| Timeout, network error or 5xx | Return `{}` (fail open) and log it |
| `429` rate limit or daily quota | Return `{}`. Upgrade if it happens every day |
| `402` with `code` `trial_ended` or `subscription_ended` | Your isCredible account has no active plan. Return `{}` and choose a plan in the dashboard |
| Invalid hook signature | Return the `401` error shown above |

> **Warning: Keep the hook responding**
>
> If your function fails or responds too slowly, Supabase Auth can't complete the signup. Keep the `try`/`catch` around the isCredible call, and test the hook in a staging project first.
