# User profiles & onboarding

> Pair auth accounts with clean profile tables, guide new users through frictionless onboarding, preserve guest carts across sign-in, and handle deletion safely.

- Canonical: https://exaspark.ai/docs/user-profiles-onboarding/

## Separating auth identity from app profile data

Every user account handles two distinct layers: **authentication identity** (verified email, sign-in providers, active sessions, role) and **application profile** (display name, avatar, bio, timezone, preferences, onboarding progress).

Keeping a dedicated `profiles` table linked one-to-one to `users.id` keeps both layers clean and secure:

- **Clear security boundary.** Server-controlled fields (`role`, `email_verified_at`, `stripe_customer_id`) stay locked on `users`, while `profiles` exposes an explicitly whitelisted set of editable preferences.
- **Public vs private clarity.** Public reviews or instructor cards read only safe profile fields (`display_name`, `avatar_url`, `bio`) without touching private auth columns.
- **Consistent creation across 19+ providers.** Initializing a `profiles` row automatically for email, Google, Apple, and GitHub sign-ups prevents crashes when social logins bypass signup forms.

```text
users    (id PK, email UNIQUE, role, stripe_customer_id, created_at UTC)
profiles (user_id PK & FK->users CASCADE, display_name, avatar_url, phone,
          timezone default 'UTC', onboarding_step int, onboarding_completed_at UTC)
carts    (id PK, user_id FK->users nullable, guest_token UNIQUE nullable, updated_at UTC)
```

## Post-signup onboarding flows that convert

Extra required fields on registration cut sign-up conversion. Collect only the minimum needed to create an account, then use **progressive profiling** after sign-in to ask for details when they actually matter.

| App type | Best onboarding pattern | Collect right after signup | Defer until later |
| --- | --- | --- | --- |
| **Store or booking site** | **Zero-step instant entry** | Return straight to cart or booking slot (`?next=`) | Shipping address, phone, card details at checkout |
| **B2B SaaS or team tool** | **2-to-3 step setup** | Workspace name, primary goal, optional teammate invite | Billing info, custom branding, integrations |
| **Marketplace or community** | **Quick profile setup** | Display name, avatar, location or timezone | Payout bank details (only when listing first item) |
| **Coaching or wellness app** | **Resumable intake** | Timezone, focus goals, required safety waiver | Optional progress photos and notification times |

### Track completion on the server, never only in local storage

Store `onboarding_completed_at` and `onboarding_step` directly on `profiles` in your database. If someone completes Step 1 on a laptop and reopens your app on their phone later, the server resumes cleanly at Step 2 — and once complete, they never loop back into onboarding.

## Letting guests browse and merge carts on sign-in

Forcing visitors to create an account just to browse products, calculate shipping, or pick a class slot kills conversion. Let guests build a full cart or draft booking first, then preserve every selection seamlessly when they sign in at checkout.

Here is how a clean guest-to-member handoff works under the hood:

- **Issue a guest cart token.** When an unsigned-in visitor adds their first item, the server creates a `carts` row linked to a random `guest_token` stored in an HTTP-only cookie.
- **Preserve the return URL (`?next=`).** When the visitor clicks **Checkout**, redirect to `/login?next=/checkout` (preserving `?next=` across OAuth redirects too).
- **Merge on sign-in atomically.** The moment sign-in succeeds, your server checks for a `guest_token` cookie, merges those cart items into the user's account cart (combining quantities for duplicate SKUs), deletes the temporary guest row, and redirects straight to `/checkout`.
- **Optional post-purchase claim.** If your store supports full guest checkout, auto-attach prior guest orders matching the buyer's verified email when they later create an account so their full order history appears automatically.

## Step-by-step: building profiles, onboarding, and guest handoff

Follow these four steps to build a smooth, bug-free account lifecycle in ExaSpark.

1. **Auto-create profiles on every sign-up path** — Ensure email registration, magic links, Google, Apple, and GitHub all initialize a `profiles` row (pulling initial `display_name` and `avatar_url` when supplied) so dashboards never hit null-profile crashes.
2. **Whitelist strictly user-editable profile fields** — On `PATCH /api/profile`, accept only explicit keys (`display_name`, `avatar_url`, `phone`, `timezone`, `marketing_opt_in`) and ignore anything else so callers can never tamper with `role` or `plan`.
3. **Wire server-backed onboarding and `?next=` redirects** — Redirect signed-in users with `onboarding_completed_at IS NULL` to `/onboarding`, mark completion on the final step, and honor any pending `?next=` return destination immediately afterward.
4. **Test guest-to-member handoff and avatars in Preview** — Browse signed out, add two items to the cart, sign in with a fresh Preview account, confirm both items survive intact, and verify avatar uploads save cleanly to storage.

> **Example prompt (App):** Create a `profiles` table linked 1-to-1 to `users.id` with `display_name`, `avatar_url`, `timezone`, `onboarding_step`, and `onboarding_completed_at`. Auto-create a profile row on every sign-up method (email, Google, Apple) without overwriting customized fields on returning logins. Build a clean 2-step `/onboarding` flow (Step 1: display name and timezone; Step 2: optional avatar upload and goal selection) that saves progress server-side and returns users to their `?next=` URL once finished. Support guest shopping carts via an HTTP-only `guest_token` cookie and merge guest cart items automatically into the user's account on sign-in. Also add a `/settings/account` page with whitelisted profile editing and a confirmed self-service "Delete account" flow.

## Handling self-service account deletion safely

Providing a clear, self-service **Delete account** button inside Account Settings is both a privacy best practice and a strict requirement if you publish an Android app on Google Play (see [Google Play publishing](https://exaspark.ai/docs/google-play/)).

Deleting a real customer account involves more than running `DELETE FROM users` — doing that naively can either crash on foreign keys or keep charging a deleted customer's credit card every month. Implement four clean steps on the server:

- **Require fresh confirmation.** Ask the signed-in user to type `DELETE` (or re-verify their password/session) and display a plain-English summary of what will be removed.
- **Cancel active Stripe subscriptions first.** Call Stripe on the server to cancel active recurring subscriptions immediately before completing deletion so a departed user is never billed again.
- **Delete personal files and scrub PII.** Remove uploaded avatars and private attachments from File Storage, clear sessions, and delete personal profile data (`display_name`, `phone`, `avatar_url`, saved addresses).
- **Preserve financial ledger integrity safely.** For accounting and tax compliance, either anonymize paid `orders` and `invoices` (`user_id = NULL`, customer name replaced with `"Deleted user"`, keeping amounts, dates, and tax totals) or retain minimal non-personal transaction snapshots rather than corrupting revenue reports.

## Common profile & onboarding pitfalls

Check this troubleshooting table if new sign-ups stumble between login, onboarding, and their first dashboard screen.

| Symptom | Likely cause | Clean fix |
| --- | --- | --- |
| **Social login succeeds, then dashboard crashes with "Profile not found"** | Profile creation ran only on the email `/signup` form, not on OAuth first-login callbacks | Initialize `profiles` centrally inside the server's post-auth user creation hook for every provider |
| **User finishes onboarding, reloads, and gets sent back to Step 1** | Onboarding state lived only in React state or `localStorage`, or route read a stale cached session | Persist `onboarding_completed_at` on `profiles` and read live database state on the server |
| **Guest cart empties immediately after "Continue with Google"** | Cart lived only in temporary tab memory, or OAuth redirect dropped the guest cookie/merge hook | Persist guest carts via an HTTP-only `guest_token` cookie and run the merge hook in the OAuth callback |
| **Deleting an account fails with a foreign-key constraint error** | Paid `orders` or `bookings` reference `users.id` with `RESTRICT` | Anonymize personal details and set `orders.user_id = NULL` (keeping tax totals intact) before removing the user row |
| **Deleted user gets charged next month on Stripe** | Account deletion erased local rows without canceling the customer's active Stripe subscription | Cancel active Stripe subscriptions on the server as step one of account deletion, then verify cancellation |

> **Note:** **Validate avatar uploads on the server.** Limit profile photo uploads to safe image types (`image/jpeg`, `image/png`, `image/webp`) and a modest file cap (such as 2–5 MB) inside File Storage so oversized uploads never bloat page loads. See [File storage & uploads](https://exaspark.ai/docs/file-storage/).

## Next steps

- [Social login providers](https://exaspark.ai/docs/social-login-setup/) — Configure Google, Apple, GitHub, and 19+ providers with clean profile initialization.
- [File storage & uploads](https://exaspark.ai/docs/file-storage/) — Handle profile avatars and private user attachments safely in Cloud storage.
- [Subscriptions & upgrades](https://exaspark.ai/docs/subscriptions-and-upgrades/) — Coordinate active Stripe memberships cleanly with account lifecycle and deletion.

## From the blog

- [How sign-in works](https://exaspark.ai/blog/how-sign-in-works/) — How user accounts, sessions, and first-time sign-in flows fit together.
- [How to get your first users](https://exaspark.ai/blog/how-to-get-your-first-users/) — Designing frictionless guest browsing and onboarding that turns visitors into members.
- [App launch checklist](https://exaspark.ai/blog/app-launch-checklist/) — Final verification for profiles, guest checkout handoff, and account deletion.
