Skip to content

Open source personal finance application

docs(deployment): add cloud and self-hosted flows with official doc links

Ilya Komichev990ef5d9aab5
diff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.md
index 8cb60d9a..14556955 100644
--- a/docs/content/en/2.development/05.deployment.md
+++ b/docs/content/en/2.development/05.deployment.md
@@ -12,7 +12,7 @@ Finapp is a pnpm workspace monorepo. Both the app and docs deploy from the same
## Vercel Setup
-Create **two projects** in Vercel, both pointing to the same GitHub repository.
+Create **two projects** in Vercel, both pointing to the same GitHub repository. Nuxt needs no special Vercel configuration beyond the per-project settings below - see [Nuxt on Vercel](https://nuxt.com/deploy/vercel) and [Vercel's Nuxt guide](https://vercel.com/docs/frameworks/full-stack/nuxt) for the framework basics.
::callout{icon="i-lucide-info" color="info"}
**Settings split: file vs project.** Most build settings live in each project's `vercel.json` (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory cannot live in `vercel.json`** because Vercel needs it to know where to look for the file. Set it once in the project's dashboard (Settings -> General -> Root Directory) or via the API:
@@ -45,6 +45,10 @@ Add the following environment variables pointing at your hosted Supabase project
| `VITE_SUPABASE_ANON_KEY` | Your Supabase publishable (anon) key |
| `VITE_POWERSYNC_URL` | Your PowerSync service URL |
+::callout{icon="i-lucide-terminal" color="info"}
+**Git-connected vs direct CLI deploy.** The two-project setup here is Git-connected (pushes auto-deploy). For a standalone or throwaway environment (e.g. a `finapp-dev` project off a feature branch), skip the Git connection and deploy the working tree straight from the repo root: create/link a project (`vercel link`) with its Root Directory set to `app`, then `vercel deploy --prod`. The whole monorepo uploads from the root and Vercel builds `app/` via the Root Directory setting.
+::
+
### Docs Project
| Setting | Value |
@@ -81,23 +85,54 @@ Set the three `VITE_*` env vars in Vercel to point at your production Supabase p
### Supabase (production project)
-1. Create a Supabase project, link the repo and push the schema:
+1. Create a Supabase project (dashboard, or `supabase projects create`), link the repo and push the schema ([Supabase migration docs](https://supabase.com/docs/guides/deployment/database-migrations)):
```bash [Terminal]
cd app
+ supabase projects create finapp --org-id <org-id> --region <region> --db-password <pw>
supabase link --project-ref <project-ref>
supabase db push # applies supabase/migrations/ (tables, RLS, signup trigger)
```
-2. Run `supabase/powersync_setup.sql` against the project database (SQL editor or `psql` over the **direct** connection string). It creates the `powersync_role` (REPLICATION + BYPASSRLS) and the `powersync` publication that the PowerSync service replicates from.
+ **No IPv6? `db push` will fail.** The direct connection `db.<ref>.supabase.co:5432` is IPv6-only, so on a network without IPv6 `db push` errors with `socket is not connected`. Push over the IPv4 **session pooler** instead - copy its string from the dashboard's **Connect** tab (Session mode):
+
+ ```bash [Terminal]
+ supabase db push --db-url "postgresql://postgres.<ref>:<pw>@aws-1-<region>.pooler.supabase.com:5432/postgres"
+ ```
+
+ This page uses two **different** connections: the **pooler** (IPv4) for `db push` and queries from your machine, and the **direct** connection for PowerSync's logical replication below (PowerSync's own infrastructure has IPv6).
+
+2. Ensure the `powersync` publication exists for the synced tables - `supabase db query` runs the setup SQL against the linked project, no `psql` required:
+
+ ```bash [Terminal]
+ supabase db query --linked -f supabase/powersync_setup.sql
+ # over the pooler a multi-statement file may hit the prepared-statement limit;
+ # then run the publication's DROP and CREATE as separate `supabase db query "..."` calls
+ ```
+
+ **Cloud vs self-hosted role.** The script's `powersync_role` (REPLICATION + BYPASSRLS) is for **self-hosted** PowerSync. On **Supabase Cloud** the `postgres` role already has REPLICATION + BYPASSRLS (and a non-superuser `postgres` cannot create a REPLICATION role anyway), so PowerSync Cloud connects as `postgres` - there only the `powersync` publication matters.
3. RLS policies and the `user_settings` signup trigger come with the migrations - nothing to configure manually.
+Self-hosting Supabase instead of the cloud? The Finapp-specific steps are identical (apply the migrations, run `powersync_setup.sql`) - follow the [self-hosting with Docker guide](https://supabase.com/docs/guides/self-hosting/docker) for the stack itself, then swap the `*.supabase.co` URL and JWKS endpoint for your instance's own.
+
### PowerSync (production service)
Two options; both replicate from the Supabase Postgres and validate Supabase JWTs via JWKS:
-- **PowerSync Cloud** (managed): create an instance, point its source database at the Supabase **direct** connection string (not the pooler - logical replication needs a direct connection), enable Supabase auth, and paste the sync rules from `app/powersync/config/sync-config.yaml`.
-- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) is the template, but it is **local-dev only** - its credentials are committed for a localhost stack. For production: move the replication URI, the bucket-storage Postgres URI, and the API token into secrets; point `client_auth.jwks_uri` at `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` and remove `allow_local_jwks`; give the service its own Postgres for bucket storage (it auto-migrates its schema); terminate TLS in front of port 8080.
+- **PowerSync Cloud** (managed): point the source database at the Supabase **direct** connection string (not the pooler - logical replication needs a direct connection), enable Supabase auth, and use the sync rules from `app/powersync/config/sync-config.yaml`. Do it in the dashboard ([Supabase + PowerSync guide](https://docs.powersync.com/integrations/supabase/guide)) or with the official [PowerSync CLI](https://docs.powersync.com/tools/cli) (`npm i -g powersync`), which keeps the instance config as code:
+
+ ```bash [Terminal]
+ powersync login
+ powersync init cloud # scaffolds powersync/service.yaml + sync-config.yaml
+ # service.yaml: replication -> Supabase direct conn (username postgres);
+ # client_auth -> supabase: true + jwks_uri https://<ref>.supabase.co/auth/v1/.well-known/jwks.json
+ # use app/powersync/config/sync-config.yaml as the sync rules
+ powersync link cloud --instance-id <id> # or --create --org-id <org> --project-id <project>
+ POWERSYNC_DATABASE_PASSWORD=<pw> powersync deploy # deploys service-config + sync-config
+ ```
+
+ A new PowerSync Cloud **project** ships with **Production** and **Development** instances already created - deploy to one of those instead of creating a third. Projects are created in the dashboard; the CLI manages instances and config, not projects.
+- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) is the template, but it is **local-dev only** - its credentials are committed for a localhost stack. For production: move the replication URI, the bucket-storage Postgres URI, and the API token into secrets; point `client_auth.jwks_uri` at `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` and remove `allow_local_jwks`; give the service its own Postgres for bucket storage (it auto-migrates its schema); terminate TLS in front of port 8080. See the [self-hosting guide](https://docs.powersync.com/self-hosting/getting-started) and [instance configuration reference](https://docs.powersync.com/configuration/powersync-service/self-hosted-instances) for the full config.
`VITE_POWERSYNC_URL` is the public URL of that service.
@@ -114,6 +149,18 @@ In production the Google provider is configured in the **hosted Supabase dashboa
2. In the Supabase dashboard: **Authentication -> Providers -> Google**, enable it and paste the client id/secret.
3. In **Authentication -> URL Configuration**, set **Site URL** to your deployed app origin (e.g. `https://finapp.ilko.me`) and add it (with a `/**` wildcard) to **Redirect URLs**, so the OAuth return to `/login` is allowed.
+::callout{icon="i-lucide-terminal" color="info"}
+**Without the dashboard.** Steps 2-3 can be done in a single Management API call (needs a [Supabase access token](https://supabase.com/dashboard/account/tokens)):
+
+```bash [Terminal]
+curl -X PATCH "https://api.supabase.com/v1/projects/<ref>/config/auth" \
+ -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" -H "Content-Type: application/json" \
+ -d '{"external_google_enabled":true,"external_google_client_id":"<id>","external_google_secret":"<secret>","site_url":"https://<your-app>","uri_allow_list":"https://<your-app>/**"}'
+```
+
+Do **not** use `supabase config push` for a hosted project - it pushes the whole `config.toml`, whose `site_url` is the local `http://localhost:3050`, overwriting the remote URL config. The Management API changes only the fields you send.
+::
+
Google needs no extra app env vars - it reuses `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase issues its own JWT regardless of the sign-in provider, so PowerSync keeps validating it via JWKS unchanged.
## Premium (Finapp Premium)
diff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.md
index 27e91ed9..9e9d42be 100644
--- a/docs/content/ru/2.development/05.deployment.md
+++ b/docs/content/ru/2.development/05.deployment.md
@@ -12,7 +12,7 @@ Finapp - это монорепа на pnpm workspaces. Приложение и
## Настройка Vercel
-Создайте **два проекта** в Vercel, оба указывают на один GitHub-репозиторий.
+Создайте **два проекта** в Vercel, оба указывают на один GitHub-репозиторий. Nuxt не требует особой настройки Vercel помимо настроек проектов ниже - базовая интеграция описана в [Nuxt on Vercel](https://nuxt.com/deploy/vercel) и [гайде Vercel по Nuxt](https://vercel.com/docs/frameworks/full-stack/nuxt).
::callout{icon="i-lucide-info" color="info"}
**Где что настраивать: файл vs проект.** Большинство build-настроек живут в `vercel.json` каждого проекта (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory нельзя положить в `vercel.json`**, потому что Vercel должен знать его заранее, чтобы понять где искать файл. Ставится один раз в dashboard (Settings -> General -> Root Directory) или через API:
@@ -45,6 +45,10 @@ curl -X PATCH \
| `VITE_SUPABASE_ANON_KEY` | Публичный (anon) ключ Supabase |
| `VITE_POWERSYNC_URL` | URL вашего сервиса PowerSync |
+::callout{icon="i-lucide-terminal" color="info"}
+**Git-connected vs прямой CLI-деплой.** Схема из двух проектов выше - git-connected (пуши деплоятся автоматически). Для отдельного или временного окружения (например, проект `finapp-dev` на feature-ветке) можно обойтись без git-привязки и задеплоить рабочее дерево прямо из корня репозитория: создайте/слинкуйте проект (`vercel link`) с Root Directory = `app`, затем `vercel deploy --prod`. Вся монорепа грузится из корня, а Vercel собирает `app/` по настройке Root Directory.
+::
+
### Проект документации
| Настройка | Значение |
@@ -81,23 +85,54 @@ Nuxt SPA хостится статически (выше описан Vercel, н
### Supabase (продакшен-проект)
-1. Создайте проект Supabase, привяжите репозиторий и примените схему:
+1. Создайте проект Supabase (через дашборд или `supabase projects create`), привяжите репозиторий и примените схему ([доки Supabase по миграциям](https://supabase.com/docs/guides/deployment/database-migrations)):
```bash [Terminal]
cd app
+ supabase projects create finapp --org-id <org-id> --region <region> --db-password <pw>
supabase link --project-ref <project-ref>
supabase db push # applies supabase/migrations/ (tables, RLS, signup trigger)
```
-2. Выполните `supabase/powersync_setup.sql` на базе проекта (SQL editor или `psql` по **прямой** строке подключения). Скрипт создаёт `powersync_role` (REPLICATION + BYPASSRLS) и публикацию `powersync`, из которой реплицирует сервис PowerSync.
+ **Нет IPv6? `db push` упадёт.** Прямое подключение `db.<ref>.supabase.co:5432` - только IPv6, поэтому в сети без IPv6 `db push` падает с `socket is not connected`. Пушьте через IPv4 **session-пулер** - строку возьмите во вкладке **Connect** дашборда (режим Session):
+
+ ```bash [Terminal]
+ supabase db push --db-url "postgresql://postgres.<ref>:<pw>@aws-1-<region>.pooler.supabase.com:5432/postgres"
+ ```
+
+ На этой странице используются два **разных** подключения: **пулер** (IPv4) - для `db push` и запросов с вашей машины, и **прямое** подключение - для логической репликации PowerSync ниже (у инфраструктуры PowerSync IPv6 есть).
+
+2. Убедитесь, что публикация `powersync` существует для синхронизируемых таблиц - `supabase db query` выполняет setup-SQL на привязанном проекте, `psql` не нужен:
+
+ ```bash [Terminal]
+ supabase db query --linked -f supabase/powersync_setup.sql
+ # через пулер мультистейтмент-файл может упереться в prepared-statement limit;
+ # тогда выполните DROP и CREATE публикации отдельными вызовами `supabase db query "..."`
+ ```
+
+ **Роль: cloud vs self-hosted.** `powersync_role` (REPLICATION + BYPASSRLS) из скрипта нужен для **self-hosted** PowerSync. В **Supabase Cloud** у роли `postgres` уже есть REPLICATION + BYPASSRLS (а не-суперюзер `postgres` всё равно не может создать REPLICATION-роль), поэтому PowerSync Cloud подключается как `postgres` - там важна только публикация `powersync`.
3. RLS-политики и триггер `user_settings` при регистрации приходят вместе с миграциями - вручную ничего настраивать не нужно.
+Поднимаете self-hosted Supabase вместо облака? Шаги, специфичные для Finapp, идентичны (применить миграции, выполнить `powersync_setup.sql`) - сам стек разворачивается по [гайду self-hosting с Docker](https://supabase.com/docs/guides/self-hosting/docker), после чего подставьте вместо `*.supabase.co` URL и JWKS-эндпоинт адреса своего инстанса.
+
### PowerSync (продакшен-сервис)
Два варианта; оба реплицируют из Supabase Postgres и проверяют JWT Supabase через JWKS:
-- **PowerSync Cloud** (управляемый): создайте инстанс, укажите в качестве исходной базы **прямую** строку подключения Supabase (не pooler - логической репликации нужно прямое подключение), включите Supabase auth и вставьте правила синхронизации из `app/powersync/config/sync-config.yaml`.
-- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) - это шаблон, но он предназначен **только для локальной разработки** - его учётные данные закоммичены для localhost-стека. Для продакшена: вынесите URI репликации, Postgres URI bucket-хранилища и API-токен в секреты; укажите в `client_auth.jwks_uri` адрес `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` и уберите `allow_local_jwks`; выделите сервису собственный Postgres для bucket-хранилища (свою схему он мигрирует сам); терминируйте TLS перед портом 8080.
+- **PowerSync Cloud** (управляемый): укажите в качестве исходной базы **прямую** строку подключения Supabase (не pooler - логической репликации нужно прямое подключение), включите Supabase auth и используйте правила синхронизации из `app/powersync/config/sync-config.yaml`. Сделать это можно в дашборде ([гайд Supabase + PowerSync](https://docs.powersync.com/integrations/supabase/guide)) или официальным [PowerSync CLI](https://docs.powersync.com/tools/cli) (`npm i -g powersync`), который держит конфиг инстанса как код:
+
+ ```bash [Terminal]
+ powersync login
+ powersync init cloud # создаёт powersync/service.yaml + sync-config.yaml
+ # service.yaml: replication -> прямое подключение Supabase (username postgres);
+ # client_auth -> supabase: true + jwks_uri https://<ref>.supabase.co/auth/v1/.well-known/jwks.json
+ # в качестве sync rules используйте app/powersync/config/sync-config.yaml
+ powersync link cloud --instance-id <id> # или --create --org-id <org> --project-id <project>
+ POWERSYNC_DATABASE_PASSWORD=<pw> powersync deploy # деплоит service-config + sync-config
+ ```
+
+ Новый **проект** в PowerSync Cloud сразу содержит инстансы **Production** и **Development** - деплойте в один из них, а не создавайте третий. Сами проекты создаются в дашборде; CLI управляет инстансами и конфигом, но не проектами.
+- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) - это шаблон, но он предназначен **только для локальной разработки** - его учётные данные закоммичены для localhost-стека. Для продакшена: вынесите URI репликации, Postgres URI bucket-хранилища и API-токен в секреты; укажите в `client_auth.jwks_uri` адрес `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` и уберите `allow_local_jwks`; выделите сервису собственный Postgres для bucket-хранилища (свою схему он мигрирует сам); терминируйте TLS перед портом 8080. Полная конфигурация - в [гайде по self-hosting](https://docs.powersync.com/self-hosting/getting-started) и [референсе конфигурации инстанса](https://docs.powersync.com/configuration/powersync-service/self-hosted-instances).
`VITE_POWERSYNC_URL` - публичный URL этого сервиса.
@@ -114,6 +149,18 @@ Nuxt SPA хостится статически (выше описан Vercel, н
2. В дашборде Supabase: **Authentication -> Providers -> Google**, включите провайдер и вставьте client id/secret.
3. В **Authentication -> URL Configuration** задайте **Site URL** = origin вашего приложения (например, `https://finapp.ilko.me`) и добавьте его (с шаблоном `/**`) в **Redirect URLs**, чтобы возврат после OAuth на `/login` был разрешён.
+::callout{icon="i-lucide-terminal" color="info"}
+**Без дашборда.** Шаги 2-3 можно выполнить одним вызовом Management API (нужен [access-токен Supabase](https://supabase.com/dashboard/account/tokens)):
+
+```bash [Terminal]
+curl -X PATCH "https://api.supabase.com/v1/projects/<ref>/config/auth" \
+ -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" -H "Content-Type: application/json" \
+ -d '{"external_google_enabled":true,"external_google_client_id":"<id>","external_google_secret":"<secret>","site_url":"https://<your-app>","uri_allow_list":"https://<your-app>/**"}'
+```
+
+**Не** используйте для хостируемого проекта `supabase config push` - он отправляет весь `config.toml`, где `site_url` = локальный `http://localhost:3050`, и перезатрёт URL-конфиг на remote. Management API меняет только переданные поля.
+::
+
Дополнительные env-переменные для Google не нужны - используются те же `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase выдаёт собственный JWT независимо от провайдера входа, поэтому PowerSync продолжает проверять его через JWKS без изменений.
## Premium (Finapp Premium)