Multi-stage build: node builds the SPA, dotnet publishes the API, the
runtime image serves the SPA from wwwroot/ and exposes /health. Frontend
Supabase URL + publishable key are baked in at build time; DB conn string
and Supabase JWKS metadata come from Coolify env vars. VITE_API_URL empty
means same-origin, so the browser hits /api/todos on the same host that
serves the SPA.
2026-08-15 12:10:45 +00:00
7 changed files with 297 additions and 2 deletions
Reusable template for a per-user CRUD app backed by Supabase Auth + Postgres. The stack:
- **React** (Vite + TypeScript) SPA in the browser — uses `@supabase/supabase-js` only for authentication.
- **ASP.NET Core 9** Web API — validates Supabase-issued JWTs against the project's JWKS and owns all database access.
- **Supabase** — hosted auth + Postgres.
The .NET backend is the sole gateway to data. The browser never talks to PostgREST. Row-level security stays off; the backend enforces ownership in SQL.
## Architecture at a glance
```
[React SPA] ──(bearer JWT)──▶ [ASP.NET Core Web API] ──(Npgsql / EF Core)──▶ [Supabase Postgres]
│ ▲
└──(auth handshake with supabase-js)─┘
└────(JWKS fetch via OpenID discovery)─────┘
```
- React reads its session with `supabase.auth.getSession()` and attaches `Authorization: Bearer <access_token>` to every `/api/todos*` request.
- The .NET backend validates the JWT asymmetrically against `https://<ref>.supabase.co/auth/v1/.well-known/openid-configuration` — no shared secret. The `sub` claim (a UUID) becomes `user_id` on every query.
- Every mutation is scoped by `WHERE user_id = @currentUser`. Non-owned rows return 404 (not 403) — no existence leak.
- Backend connects to Postgres via Supabase's **session pooler** (`aws-<n>-<region>.pooler.supabase.com:5432`). The direct DB host is IPv6-only for new Supabase projects and unreachable from IPv4-only environments.
3. **Disable email confirmation for dev:** Supabase dashboard → Authentication → Providers → Email → toggle **Confirm email** OFF. Otherwise `supabase.auth.signUp` won't return a session and the SignIn UI hangs at "Working…" while a confirmation email is queued (and often silently rate-limited to 2–4/hour on the default SMTP).
4. **Install and run:**
```bash
cd frontend && npm install
# Terminal 1
cd backend && dotnet run # http://localhost:5057
# Terminal 2
cd frontend && npm run dev # http://localhost:5173
"Postgres": "Host=aws-<n>-<region>.pooler.supabase.com;Port=5432;Database=postgres;Username=postgres.<ref>;Password=<db-password>;SSL Mode=Require;Trust Server Certificate=true"
`Audience` is always `authenticated` for user-issued JWTs — do not change unless you're validating service-role tokens (you shouldn't be, in this app).
The backend's port comes from `backend/Properties/launchSettings.json` (`applicationUrl` — default `http://localhost:5057`). If you move the backend to a different port, also update `VITE_API_URL` and the CORS `WithOrigins(...)` clause in `Program.cs`.
### Frontend (`frontend/.env.local`)
```
VITE_SUPABASE_URL=https://<ref>.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...
VITE_API_URL=http://localhost:5057
```
`VITE_API_URL` empty (or unset) means **same-origin** — used when the backend serves the built SPA from `wwwroot/` in production (Dockerfile path). Set it explicitly during local dev when frontend and backend run on different ports.
### Container / Coolify (`docker-compose.yml`)
Six env vars flow in from Coolify's env-var UI:
| Coolify env | Purpose |
|---|---|
| `VITE_SUPABASE_URL` | Baked into the client bundle at image-build time (compose `build.args`) |
| `VITE_SUPABASE_PUBLISHABLE_KEY` | Same |
| `DB_CONNECTION_STRING` | Runtime, mapped to `ConnectionStrings__Postgres` |
| `SUPABASE_METADATA_ADDRESS` | Runtime, mapped to `Supabase__MetadataAddress` |
| `SUPABASE_ISSUER` | Runtime, mapped to `Supabase__Issuer` |
| — | `Supabase__Audience` is hard-coded to `authenticated` in the compose |
The compose file also declares `SERVICE_FQDN_APP_8080: /`. Coolify substitutes this with the app's real domain and injects the matching Traefik routing labels — **only if `docker_compose_domains` is set on the Coolify application**. Skipping that field turns every request into a 404 (see the `deploying-to-coolify-via-api` skill for the fix).
## Data model
Single table:
```sql
create table public.todos (
id bigserial primary key,
user_id uuid not null, -- Supabase auth.users.id (JWT sub claim)
title text not null check (length(title) between 1 and 500),
completed boolean not null default false,
created_at timestamptz not null default now()
);
create index todos_user_id_created_at_idx on public.todos (user_id, created_at desc);
```
No FK to `auth.users` — decouples from Supabase's internal schema and avoids permission headaches at migration time.
## Extending the pattern
To add a new entity (e.g. `notes`), the same shape repeats:
1. Add a table with `user_id uuid not null` + a `(user_id, created_at desc)` index. Ship as `migrations/00N_create_notes.sql`.
3. Register the DbSet in `AppDbContext` with `HasIndex(...)` matching the SQL index name.
4. Add `NotesController` — copy `TodosController` verbatim, swap entity/DTO names. Keep the `CurrentUserId()` + `WHERE user_id == userId` pattern for every read/write; that's what enforces per-user isolation without RLS.
5. Frontend: an `api.notes` object with `list/create/setX/remove` alongside the existing `api` todos block, plus a `NotesList` component modelled on `TodoList`.
The critical invariant, everywhere: **every query filters by `userId = CurrentUserId()`**. Missing that on a single endpoint leaks other users' data.
## Known gotchas (all bit us during initial build — documented so they don't bite you)
| Symptom | Cause | Fix |
|---|---|---|
| `connection to server at "db.<ref>.supabase.co" failed: Network is unreachable` | Direct DB host is IPv6-only on new Supabase projects; sandbox has no IPv6 egress | Use the session pooler (`aws-<n>-<region>.pooler.supabase.com`, port 5432, user `postgres.<ref>`) |
| `dotnet add package X` restore fails with `NU1202` | CLI grabbed a newer major version incompatible with `net9.0` | Pin: `dotnet add package X --version 9.*` |
| Sign-up hangs / "email rate limit exceeded" | Email confirmation ON; Supabase default SMTP limits to 2–4/hour | Toggle Auth → Providers → Email → **Confirm email** OFF for dev; or wire real SMTP |
| Sign-up rejects `@example.com` with `email_address_invalid` | Supabase blocklists disposable domains on the ordinary signup endpoint | For E2E scripts, use the admin API (`POST /auth/v1/admin/users` with `email_confirm:true`) — see `docs/superpowers/plans/2026-08-15-supabase-todo-app.md` Task 8 |
| Deploy on Coolify finishes green, live URL returns `404 page not found` | Missing / mis-shaped `docker_compose_domains` on the Coolify app | See the `deploying-to-coolify-via-api` skill: PATCH the array-form after the first deploy loads the compose file |
| Vite template's `index.css` styles fight your inline styles | Scaffolded `index.css` ships opinionated marketing styles (large h1, fixed `#root` width) | Replace with the minimal reset in `frontend/src/index.css` |
| Backend port 5000 collisions across dev sessions | Common default for other Linux services / stale processes | This project uses `5057` — check the same for any port you pick |
## What NOT to change without thinking
- **RLS off** is a deliberate choice. If you enable RLS on `public.todos`, you must also either (a) write `USING (auth.uid() = user_id)` policies, or (b) have the backend run as a role with `BYPASSRLS`. Otherwise the backend's own queries stop returning rows.
- The **DTO response shape** deliberately omits `user_id`. Adding it back exposes the caller's own id (harmless) but invites confusion.
- **`RequireHttpsMetadata = true`** on the JwtBearer options. If you're testing against a non-HTTPS Supabase project (there is no such thing in practice), set to false — otherwise leave it. This prevents downgrade attacks on the JWKS fetch.
- **`MapInboundClaims = false`** — keeps the raw `sub` claim instead of remapping to `ClaimTypes.NameIdentifier`. If you flip this, update the `CurrentUserId()` helper.
## Related skills / docs
- `docs/superpowers/specs/2026-08-15-supabase-todo-app-design.md` — the original design decisions and out-of-scope list.
- `docs/superpowers/plans/2026-08-15-supabase-todo-app.md` — the 17-task implementation plan, including manual E2E verification recipes for backend (curl) and frontend (Playwright).
- Global skill: `creating-supabase-app-from-boilerplate` — clones this repo and reconfigures it against a new Supabase project.
- Global skill: `preparing-dotnet-react-app-for-coolify` — the Dockerfile + compose pattern this repo already implements.
- Global skill: `deploying-to-coolify-via-api` — how the Coolify project + application were created; run again against a new project or copy `deploy.json` and change the values.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.