> ## Documentation Index
> Fetch the complete documentation index at: https://docs.powersync.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Supabase: Edge Function Route

> Deploy the reference write endpoint as a Supabase Edge Function, so that each uploaded transaction is applied atomically and your RLS policies authorize every write.

This route uses the [reference write implementation](https://docs.powersync.com/handling-writes/write-path/reference-write-implementation.md). You deploy its write endpoint as a Supabase Edge Function, and your app sends writes to the function with the reference connector. Compared with the [PostgREST route](https://docs.powersync.com/handling-writes/write-path/supabase-postgrest.md), you deploy and maintain one function, and in return each transaction is applied in one database transaction.

The function runs each write as the signed-in user. Inside each transaction, it switches to the `authenticated` role and sets the user's token claims. Policies that use `auth.uid()` therefore work the same way as for requests from the Supabase client SDKs.

![Diagram of the Edge Function route. Inside Supabase, an Edge Function runs the reference write endpoint as the signed-in user and writes each transaction atomically to Postgres, where RLS policies apply. Supabase Postgres replicates to the PowerSync Service, which syncs to the SDK in the client app. The reference connector's uploadData() sends queued transactions to the Edge Function. Supabase Auth issues the JWTs that the Edge Function and PowerSync verify.](https://mintcdn.com/powersync/O2UFKk2N_bhUL-Fp/images/handling-writes/supabase-edge-function.png?fit=max\&auto=format\&n=O2UFKk2N_bhUL-Fp\&q=85\&s=6f431eb429306f56ba7f09bd9ea2b8e9)

The Edge Function runs inside your Supabase project. Supabase Auth issues the tokens, and RLS policies authorize each write.

## Before You Start

* PowerSync connected to your Supabase project and configured for [Supabase Auth](https://docs.powersync.com/configuration/auth/supabase-auth.md). See the [Supabase guide](https://docs.powersync.com/integrations/supabase/guide.md).
* Your Supabase project signs tokens with asymmetric JWT signing keys, the default for new projects. Projects that use the legacy JWT secret must [migrate](https://docs.powersync.com/configuration/auth/supabase-auth.md#migrating-from-legacy-to-new-jwt-signing-keys) first.
* Each table that your app writes to has an `id` primary key or unique column that holds the client's row ID.
* An app that signs users in with Supabase Auth.
* The [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started).

## Set Up

**1. Add Grants and RLS Policies**

Grant the `authenticated` role access to every table that your app writes to, enable RLS on each one, and add a policy for each operation that your app uploads:

* A `PUT` is an upsert, so it needs `INSERT` and `UPDATE` policies, and the existing row must be visible to the user.
* A `PATCH` needs an `UPDATE` policy, and a `DELETE` needs a `DELETE` policy.

Use `WITH CHECK` so that users can't assign rows to someone else. For example:

```sql theme={null}
grant select, insert, update, delete on public.lists to authenticated;
alter table public.lists enable row level security;

create policy "Owners manage their lists" on public.lists
  for all to authenticated
  using (owner_id = (select auth.uid()))
  with check (owner_id = (select auth.uid()));
```

> [!WARNING]
>
> If `authenticated` has grants on a table that has RLS disabled, any signed-in user can write any row in it. Check every table in the schemas that your app writes to, not only the tables that you sync.

**2. Deploy the Function**

Clone [powersync-reference-write-implementation](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main). From its `backend` folder, link your project and deploy the function:

```bash theme={null}
supabase link --project-ref <project-ref>
supabase functions deploy powersync-write
```

If Docker isn't running, add `--use-api` to the deploy command.

The function connects to your project's database directly. Each function worker keeps up to three connections, and they all count against your database's connection limit. If many workers run at once, set the function to use the transaction pooler. To configure it, copy the pooler connection string from **Connect** > **Transaction pooler** in the Supabase dashboard. URL-encode any special characters in the password and add `sslmode=verify-full`:

```bash theme={null}
supabase secrets set POWERSYNC_DATABASE_URL='postgresql://postgres.<project-ref>:<password>@<pooler-host>:6543/postgres?sslmode=verify-full'
```

> [!WARNING]
>
> From this repository, run only `supabase functions deploy powersync-write` and `supabase secrets set` against your project. Other commands, such as `supabase config push`, can apply the repository's local development config to your project.

To deploy from your own repository instead, see the repository's [Supabase Edge Function guide](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/supabase/README.md#deploy-to-your-project).

**3. Check the Deployment**

```bash theme={null}
curl -i -X POST https://<project-ref>.supabase.co/functions/v1/powersync-write/api/data
```

A request without a token returns `401`.

**4. Connect Your App**

Copy the reference connector for your SDK into your app and pass it to `connect()`, as described in the reference write implementation's [Connect Your App step](https://docs.powersync.com/handling-writes/write-path/reference-write-implementation.md#connect-your-app). Then make these changes to your copy:

1. Set the write endpoint URL to `https://<project-ref>.supabase.co/functions/v1/powersync-write`. Your PowerSync instance URL doesn't change.
2. Replace `fetchAuthToken()` with code that returns the access token of the current Supabase session. The `fetchCredentials()` in the [Supabase example](https://docs.powersync.com/configuration/app-backend/backend-connector-examples.md#supabase) for your SDK shows how to read it.
3. Stop caching the token: return `fetchAuthToken()` directly from `getAuthToken()`, as the comments in the example describe. The Supabase client SDK refreshes the session itself. The connector clears its cache only after a write request fails authentication, so while the cache is in place, sync keeps sending an expired token.

For example, with supabase-js:

```typescript theme={null}
// Inside your copy of MyBackendConnector. `supabase` is your app's Supabase client.
private async getAuthToken(): Promise<string> {
  return this.fetchAuthToken();
}

private async fetchAuthToken(): Promise<string> {
  const { data: { session }, error } = await supabase.auth.getSession();
  if (!session || error) throw new Error('Not signed in to Supabase');
  return session.access_token;
}
```

The function accepts only a signed-in user's access token. It rejects API keys, anon tokens, and service-role tokens.

## How Failures Are Handled

| Failure | Outcome |
| - | - |
| An RLS policy or missing grant denies a write | [Blocked transaction](https://docs.powersync.com/handling-writes/write-path/concepts.md#blocked-transactions). The function reports the denial as a retryable error, so the connector keeps the transaction and the SDK retries it. No write is lost, but until you fix the policy, grant, or data, it holds back every later write from that device. To change this, edit `permissionErrorsRetryable` in `rls.ts`. |
| `authorize()` in `authorizer.ts` returns `false` | [Rejected write](https://docs.powersync.com/handling-writes/write-path/concepts.md#rejected-writes). The connector removes the transaction from the queue, and the function passes it to the dead-letter hook. To keep these transactions in the queue instead, change `requiresClientHandling` in `fatal-error-handler.ts`. |
| Constraint violation, invalid data, another permanent error, or any database error the function doesn't recognize | [Rejected write](https://docs.powersync.com/handling-writes/write-path/concepts.md#rejected-writes). The connector removes the transaction from the queue, and the function passes it to the dead-letter hook in `fatal-error-handler.ts`, which only logs it by default, so the user's change is lost. |
| Temporary error, such as a lost connection | Retryable error. |

A policy can also hide a row from the user. A `PATCH` or `DELETE` on a hidden row succeeds without changing anything. The app's local change reverts after the next sync.

Because an RLS denial is retried, a mistake in a policy shows up as a growing upload queue and repeated `uploadError` values in the sync status. To stop one denied write from holding up the queue, add a retry limit to your copy of the connector. When a transaction reaches the limit, drop it or store it.

## Customization

Edit these files in `backend/supabase/functions/powersync-write/`, then deploy again:

| File | Use it to |
| - | - |
| `mapper.ts` | Map client tables and columns to different names in Postgres. |
| `authorizer.ts` | Add checks that RLS can't express, such as rejecting a transaction based on the tables it touches. RLS still applies to every write it allows. |
| `fatal-error-handler.ts` | Choose which permanent failures become blocked transactions, and store rejected writes. The function waits for the dead-letter hook before it responds, so a slow hook delays uploads. In the app, the connector's `onFatalTransaction()` keeps blocked transactions by default. |
| `config.ts` | Change the batch failure policy, the connection pool size, and the statement timeout. |

## Before Production

Before you deploy the function for real users, review the [production checklist](https://docs.powersync.com/handling-writes/write-path/reference-write-implementation.md#before-production). It covers authorization, demo authentication, and how failed writes are recovered.

## Related Pages

* [Reference Write Implementation](https://docs.powersync.com/handling-writes/write-path/reference-write-implementation.md): how uploads are applied, batching, and conflict behavior.
* [Write Path Concepts](https://docs.powersync.com/handling-writes/write-path/concepts.md): what happens when a write fails.
* [Supabase guide](https://docs.powersync.com/integrations/supabase/guide.md): set up Supabase and PowerSync.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.