> ## 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.

# Reference Write Implementation

> Run PowerSync's open-source write endpoint against your source database, and connect your app to it with the reference connector.

If you don't have a write endpoint yet, you can run the reference write implementation instead of building one. It has two parts:

* The **reference write endpoint**: a Node.js (Express) server that receives uploaded transactions and applies them to your source database. It supports Postgres, MongoDB, MySQL, and SQL Server.
* The **reference connector**: a backend connector with an `uploadData()` that calls the reference write endpoint. There is one for each SDK in [Backend Connector Examples](https://docs.powersync.com/configuration/app-backend/backend-connector-examples.md#custom-backend). You copy it into your app.

An [OpenAPI spec](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-api.openapi.yaml) defines the API between the two parts. If your backend runs on another stack, see [Build Your Own Write Endpoint](https://docs.powersync.com/handling-writes/write-path/build-your-own-write-endpoint.md).

If your source database is Supabase and you rely on RLS policies to authorize writes, use the [Edge Function route](https://docs.powersync.com/handling-writes/write-path/supabase-edge-function.md) instead. The reference write endpoint on this page doesn't switch to Supabase's `authenticated` role, so the grants and RLS policies that you set up for signed-in users don't apply to its writes.

![Diagram of the reference write implementation. The source database replicates to the PowerSync Service, which syncs to the SDK in the client app. The reference connector's uploadData() sends queued transactions, as defined by the OpenAPI spec, to the reference write endpoint, which writes each transaction atomically to the source database. The write endpoint has authorization, mapping, and dead-letter hooks, and verifies the same JWTs as PowerSync.](https://mintcdn.com/powersync/O2UFKk2N_bhUL-Fp/images/handling-writes/reference-write-implementation.png?fit=max\&auto=format\&n=O2UFKk2N_bhUL-Fp\&q=85\&s=ebcbac4f4df8b97545523904c7024e25)

The reference connector sends queued transactions to the reference write endpoint, which applies each one to the source database.

## Before You Start

* A PowerSync instance that replicates your source database.
* A PowerSync app.
* Each table that your app writes to has an `id` primary key or unique column that holds the client's row ID. On MongoDB, each collection also needs a `$jsonSchema` validator that declares `_id` with one `bsonType`: `string`, `objectId`, `int`, or `long`. The reference write endpoint converts each row ID to that type.
* Docker, or Node.js 24 and pnpm 9.

> [!WARNING]
>
> By default, the reference write endpoint accepts every write from any authenticated user. Add your authorization checks (step 5) before you expose it to real users.

## Set Up

**1. Clone the Repository and Configure the Database**

Clone [powersync-reference-write-implementation](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main). In a `.env.local` file at the repository root, set:

* `DATABASE_TYPE`: `postgres` (the default), `mongodb`, `mysql`, or `mssql`.
* `DATABASE_URI`: the connection string for the database that your PowerSync instance replicates.

Tables and columns must match the names in your client-side schema, unless you add a custom mapping.

**2. Configure Authentication**

The reference write endpoint verifies the same JWTs as your PowerSync instance, so your app can use one token for syncing and for writes. It accepts only tokens signed with asymmetric keys. It reads its settings in one of two modes:

* **File mode** (the default): reads your PowerSync config. For PowerSync Cloud, export it with the [PowerSync CLI](https://docs.powersync.com/tools/cli.md):
  ```bash theme={null}
  powersync login
  powersync fetch config --instance-id="<instance-id>" --output=json > backend/standalone/config/powersync-config.json
  ```
  Also set `AUTH_ISSUER` to your auth provider's issuer, unless you use Supabase Auth on a standard Supabase domain. For a non-Supabase Cloud export, set `AUTH_INSTANCE_URL` to your PowerSync instance URL, or set `AUTH_AUDIENCE` to the complete accepted audience list. See the [authentication variables](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/setup.md#variables).
* **Env mode**: set `AUTH_MODE=env`, `AUTH_ISSUER`, `AUTH_AUDIENCE`, and `AUTH_JWKS_URI`. Use this for providers such as Clerk and Auth0, and for [development tokens](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md) when you don't have an auth provider yet.

For self-hosted PowerSync and the full list of variables, see the repository's [authentication setup](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/setup.md). For Supabase Auth and Clerk details, see [providers](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/providers.md).

**3. Start the Write Endpoint**

> [tab] Docker
>
> From the repository root:
>
> ```bash theme={null}
> docker compose up --build
> ```

> [tab] Node.js
>
> Copy `backend/.env.template` to `backend/.env` and set the same variables there. Then, from the repository root:
>
> ```bash theme={null}
> pnpm --dir backend install
> pnpm --dir backend dev
> ```

The server listens at `http://localhost:6060`. At startup, it checks its settings and connects to the database. If a setting is invalid, it stops with an error that names the setting. While it runs, `GET /` returns `200`, or `503` if it can't reach the database.

**4. Connect Your App**

Copy the reference connector for your SDK, the [Custom Backend example](https://docs.powersync.com/configuration/app-backend/backend-connector-examples.md#custom-backend) in Backend Connector Examples, into your app. If your app already has a `fetchCredentials()`, keep it, and copy only `uploadData()` and the code it uses.

In your copy:

1. Set the write endpoint URL at the top of the file. Use a URL that the device can reach: `localhost` on a phone refers to the phone.
2. Replace `[Your PowerSync instance URL or self-hosted endpoint]` with your PowerSync instance URL.
3. Replace the placeholder `fetchAuthToken()` with code that gets the current token from your auth provider. The connector caches the token until the write endpoint rejects it, so sync can keep sending an expired token after your provider refreshes the session. If your provider's SDK refreshes sessions itself, return its current token directly instead of caching it, as the comments in the example describe.

Then pass the connector to `connect()` in place of your current connector. The Rust example has a `connect()` function that does this.

The reference connector sends one transaction per request. For JavaScript and React Native apps, the repository's [`example-client`](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main/example-client) has a TypeScript connector that can also send several transactions per request and wait for the retry delay that the write endpoint suggests. See its [README](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md).

**5. Add Authorization**

Add your checks to the `authorize()` function in `backend/standalone/src/auth/authorizer.ts`. It receives the transaction's operations and the verified token's `sub` and claims, and returns `false` to reject the transaction. By default, it allows every write and logs an error for each transaction until you replace it. See the repository's [authorization guide](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/authorization.md).

On Postgres, the reference write endpoint also sets `request.jwt.claims` for each transaction, which RLS policies can read. Postgres skips RLS for table owners, superusers, and roles with `BYPASSRLS`, so policies only apply if `DATABASE_URI` connects as a role without those rights. A policy can also make an `UPDATE` or `DELETE` change nothing instead of failing. Don't rely on RLS alone unless you've checked both.

## How Uploads Are Applied

The reference connector sends transactions to a single endpoint, `POST /api/data`. The reference write endpoint applies each transaction in its own database transaction, so either all of its changes are stored or none are. It returns one result per transaction, in the order they were sent.

The reference connector sends one transaction per request. The TypeScript connector in the repository's `example-client` can send up to 50 transactions in one request: set its maximum batch size. It never splits a transaction across requests.

The reference write endpoint has no conflict detection. Writes are applied in the order they arrive, so the last write to a column wins. A `PATCH` to a deleted row changes nothing, and a `PUT` with the ID of a deleted row creates the row again. See the repository's [conflict resolution notes](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/conflict-resolution.md) and [Handling Update Conflicts](https://docs.powersync.com/handling-writes/handling-update-conflicts.md).

## How Failures Are Handled

The reference write endpoint classifies each failed transaction, and the reference connector acts on the result:

| Failure | Examples | Outcome |
| - | - | - |
| Temporary | Lost database connection, deadlock | [Retryable error](https://docs.powersync.com/handling-writes/write-path/concepts.md#retryable-errors): the connector keeps the transaction and the SDK retries it. |
| Permanent or unrecognized | Constraint violation, invalid data, unknown table, or any database error the write endpoint 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. The write endpoint passes it to the dead-letter hook, which only logs it by default, so the user's change is lost. |
| Not authorized | `authorize()` returns `false`, or Postgres returns error `42501` for a missing grant or an RLS check | [Blocked transaction](https://docs.powersync.com/handling-writes/write-path/concepts.md#blocked-transactions): the connector keeps the transaction, and later writes wait behind it. |

To resolve a blocked transaction, override `onFatalTransaction()` in your copy of the connector. Return `'complete'` to drop the transaction, or `'retain'` to keep it. The default keeps it.

The default dead-letter hook doesn't store anything. To keep rejected writes, replace `onDeadLetter()` in `backend/standalone/src/fatal-error-handler.ts` with code that writes them to your own storage. See the repository's [error handling guide](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md).

## Customization

| To change | Edit | Guide |
| - | - | - |
| Which writes each user may make | `authorize()` in `backend/standalone/src/auth/authorizer.ts` | [Authorization](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/authorization.md) |
| How client tables and columns map to the source database | A custom mapper, installed in `backend/standalone/src/persistence/persister-factories.ts` | [Schema mapping](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/schema-mapping.md) |
| Which failures are blocked transactions, and where rejected writes go | `backend/standalone/src/fatal-error-handler.ts` | [Error handling](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md) |
| What the app does with a blocked transaction | `onFatalTransaction()` in your copy of the connector | [Error handling](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md) |

## Before Production

Before you deploy the reference write endpoint for real users, review the following defaults. The [reference repository README](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/README.md#before-production) has the same checklist.

* **Configure write authorization.** The standalone write endpoint allows every write from an authenticated user by default. Add your checks to `authorize()` (step 5 in [Set Up](#set-up)) or use Postgres RLS. See [Authorization](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/authorization.md). For the [Supabase Edge Function](https://docs.powersync.com/handling-writes/write-path/supabase-edge-function.md), check that your grants and RLS policies cover every table and operation that your app writes to.
* **Replace placeholder authentication.** The reference connector returns a placeholder token. Use your auth provider's session and token refresh instead, as described in [Connect Your App](#connect-your-app).
* **Decide how to recover rejected writes.** By default, the write endpoint logs [rejected writes](https://docs.powersync.com/handling-writes/write-path/concepts.md#rejected-writes), and the connector removes them from the upload queue. The dead-letter hook does not store them or guarantee delivery. Replace `onDeadLetter()` with recovery that suits your app. See [Error handling](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md).
* **Handle blocked transactions.** A [blocked transaction](https://docs.powersync.com/handling-writes/write-path/concepts.md#blocked-transactions) stays in the upload queue and holds back every later write. Override `onFatalTransaction()` in your connector to show the problem to the user. Also review the [authorization failure defaults](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md#authorization-failure-defaults): the Supabase Edge Function retries RLS errors, but removes transactions that its optional `authorize()` check denies.
* **Validate your data and mapping.** Review which tables and fields users can write, who owns each row, and how values are validated. The [default mapping](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/schema-mapping.md#default-mapping) does not validate data for your app.
* **Review conflict and retry behavior.** Check that the [conflict resolution behavior](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/conflict-resolution.md) suits your app. Make custom writes and side effects safe to repeat, because the connector can send an upload more than once.

## Related Pages

* [Write Path Concepts](https://docs.powersync.com/handling-writes/write-path/concepts.md): authentication and what happens when a write fails.
* [Build Your Own Write Endpoint](https://docs.powersync.com/handling-writes/write-path/build-your-own-write-endpoint.md): implement the same API contract in another backend stack.
* [Client-Side Integration](https://docs.powersync.com/configuration/app-backend/client-side-integration.md): the backend connector, and when the SDK calls `uploadData()`.


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