# Deployment Guide

> **Status (Phase 10, 20 Nov 2026): ready to deploy, not deployed.** No hosting account (Render, Vercel, Atlas), storage bucket, Cloudinary, SMTP or Meta account exists yet (P-02 to P-08), so nothing below has been run against those services. What **was** verified locally: a production-mode start with only production dependencies installed, configuration checks, security headers, `Secure` cookies, CORS/CSRF behaviour, the health check, first-Admin setup, the production Content-Security-Policy against the built app, and backup/restore scripts (`docs/TESTING.md` §21).
> Baseline: SRS §14, §14.2 and §19 (Vercel + Render + MongoDB Atlas + Cloudinary), Master Prompt §23. Decision IDs refer to `docs/DECISIONS.md`.

## 1. Architecture

```
Visitor / staff phone ──HTTPS──► Vercel (React static build, client/dist)
                                   └─ rewrite /api/* ──HTTPS──► Render web service (Express API + scheduler)
                                                                   ├─► MongoDB Atlas (same region)
                                                                   ├─► Cloudinary (images)
                                                                   ├─► Meta WhatsApp Cloud API ◄── webhooks (direct to the Render URL)
                                                                   ├─► SMTP provider (Admin password reset)
                                                                   └─► S3-compatible bucket (weekly encrypted backups)
```

The browser only ever talks to the Vercel address; `/api/*` is forwarded to Render (D-02). This keeps the session cookie first-party, which iPhones require.

## 2. Environments (C-36)

|            | Development               | Staging                                  | Production                                          |
| ---------- | ------------------------- | ---------------------------------------- | --------------------------------------------------- |
| Frontend   | Vite dev server           | Vercel project `gym-staging`             | Vercel project `gym-prod`                           |
| API        | Local Node                | Render service `gym-api-staging`         | Render service `gym-api-prod`                       |
| Database   | Local replica set / Atlas | Atlas staging database                   | Atlas production cluster                            |
| `NODE_ENV` | `development`             | `staging`                                | `production`                                        |
| WhatsApp   | `mock` (simulated)        | `disabled`, or `live` with a test number | `live` once Meta is set up, otherwise `disabled`    |
| Email      | console                   | real SMTP                                | real SMTP                                           |
| Backups    | `none` or `filesystem`    | `s3` (own prefix)                        | `s3`                                                |
| Domain     | localhost                 | `*.vercel.app`                           | `*.vercel.app` until the custom domain (C-37, P-09) |

## 3. Production environment variables (Render)

Set these in the Render service's **Environment** (secrets as secret values). **Never commit real values**; `server/.env.example` lists the names only. The server validates all of them at start-up and **refuses to start** when something required is missing or unsafe (tested).

| Variable                                                                                                                                                                                           | Required                 | Value                                                                                                                                                                                                                                                       |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_ENV`                                                                                                                                                                                         | yes                      | `production` (or `staging`)                                                                                                                                                                                                                                 |
| `PORT`                                                                                                                                                                                             | Render sets it           | —                                                                                                                                                                                                                                                           |
| `MONGODB_URI`                                                                                                                                                                                      | yes, **secret**          | Atlas `mongodb+srv://<user>:<password>@<cluster>/<database>?retryWrites=true&w=majority`                                                                                                                                                                    |
| `APP_ORIGIN`                                                                                                                                                                                       | yes                      | The Vercel address, e.g. `https://gym-prod.vercel.app` (comma-separate several; add the custom domain later)                                                                                                                                                |
| `APP_PUBLIC_URL`                                                                                                                                                                                   | optional                 | Address used in reset emails; defaults to the first `APP_ORIGIN`                                                                                                                                                                                            |
| `IP_HASH_SALT`                                                                                                                                                                                     | yes, **secret**          | 32+ random characters (`openssl rand -base64 32`); never change it afterwards                                                                                                                                                                               |
| `TRUST_PROXY`                                                                                                                                                                                      | yes                      | Number of proxies in front of the API: **`2`** when traffic arrives through the Vercel rewrite (browser → Vercel → Render's proxy → app). **Verify on staging** (§8 step 4); with a wrong value all visitors share one IP for rate limits and login records |
| `SMTP_HOST`, `SMTP_PORT`, `MAIL_FROM`                                                                                                                                                              | yes                      | Your SMTP provider; `MAIL_FROM` like `Gym <no-reply@yourdomain>`                                                                                                                                                                                            |
| `SMTP_USER`, `SMTP_PASS` (**secret**), `SMTP_SECURE`                                                                                                                                               | usually                  | As given by the provider (`SMTP_SECURE=true` for port 465)                                                                                                                                                                                                  |
| `SCHEDULER_ENABLED`                                                                                                                                                                                | yes                      | `true` on exactly **one** instance (jobs also use a database lock)                                                                                                                                                                                          |
| `LOG_LEVEL`                                                                                                                                                                                        | optional                 | `info` (default)                                                                                                                                                                                                                                            |
| `CLOUDINARY_CLOUD_NAME`, `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` (**secret**), `CLOUDINARY_FOLDER_PREFIX`                                                                                    | for photos               | Without them uploads are disabled with an explanation (P-05)                                                                                                                                                                                                |
| `WHATSAPP_MODE`                                                                                                                                                                                    | optional                 | `disabled` (default when deployed) or `live`; `mock` is refused in production                                                                                                                                                                               |
| `WHATSAPP_API_VERSION`, `WHATSAPP_PHONE_NUMBER_ID`, `WHATSAPP_BUSINESS_ACCOUNT_ID`, `WHATSAPP_ACCESS_TOKEN` (**secret**), `WHATSAPP_APP_SECRET` (**secret**), `WHATSAPP_VERIFY_TOKEN` (**secret**) | for `live`               | All six are required in live mode (§6.2)                                                                                                                                                                                                                    |
| `BACKUP_STORAGE`                                                                                                                                                                                   | for backups              | `s3` (`filesystem` is refused when deployed)                                                                                                                                                                                                                |
| `BACKUP_ENCRYPTION_KEY`                                                                                                                                                                            | with backups, **secret** | `openssl rand -base64 32`; keep an **offline copy** (without it backups cannot be restored)                                                                                                                                                                 |
| `BACKUP_S3_REGION`, `BACKUP_S3_BUCKET`, `BACKUP_S3_ACCESS_KEY_ID`, `BACKUP_S3_SECRET_ACCESS_KEY` (**secret**)                                                                                      | with `s3`                | Key limited to this bucket                                                                                                                                                                                                                                  |
| `BACKUP_S3_ENDPOINT`, `BACKUP_S3_PREFIX`, `BACKUP_S3_FORCE_PATH_STYLE`                                                                                                                             | optional                 | Endpoint for R2/B2/MinIO (empty for AWS); prefix defaults to `gym/<NODE_ENV>/backups/`                                                                                                                                                                      |
| `API_RATE_LIMIT`                                                                                                                                                                                   | no                       | Leave empty in production                                                                                                                                                                                                                                   |
| `WHATSAPP_GRAPH_URL`                                                                                                                                                                               | no                       | Tests only; leave empty                                                                                                                                                                                                                                     |

**Vercel** needs no secrets. Optional build variables: `VITE_APP_NAME` (shown before the gym name loads) and `VITE_API_BASE` (`/api/v1`). Anything starting with `VITE_` is public.

## 4. Service setup

### 4.1 MongoDB Atlas (P-04)

1. Create a project and a cluster in **AWS Singapore (ap-southeast-1)** (same region as Render, D-60). M0 (free) is fine for staging; choose the production tier by cost and size. M0 has no Atlas backups, which is why the app makes its own (D-61).
2. **Database Access:** a user with `readWrite` on the app database only (e.g. `gms_prod`). Use a long generated password.
3. **Network Access:** add Render's outbound IP addresses (shown in the Render service) if your plan provides fixed ones; otherwise `0.0.0.0/0` is the only option, protected by TLS and the strong password. Record which you chose.
4. Copy the `mongodb+srv://` connection string into `MONGODB_URI` (Atlas clusters are replica sets, which the app needs for transactions; TLS is on by default).
5. Collections and indexes are created by the server **at every start-up** (`syncIndexes`). The same can be run by hand: `npm run sync-indexes -w server`.

### 4.2 Render (backend)

- **Web Service**, repository root, **paid always-on instance** (Starter or higher) for staging and production (D-59, P-02). The free tier sleeps after 15 minutes, which would stop scheduled jobs, retries and webhooks.
- Region Singapore. **Node.js 24 LTS (24.15.0 or later)**, pinned with `NODE_VERSION=24` (or a `.node-version` file; confirm Render's current mechanism). `.npmrc` has `engine-strict=true`, so an unsupported Node fails the build.
- **Build command:** `npm ci --omit=dev -w server --include-workspace-root=false` (verified: installs only the server's production packages; there is no server build step, the server runs from source).
- **Start command:** `npm start -w server` (runs `node src/server.js`).
- **Health check path:** `/api/v1/health` → `{"status":"ok","db":"up"}`, `503` when the database is unreachable.
- Environment variables: §3. Auto-deploy staging from the staging branch, production from `main` after staging sign-off.

### 4.3 Vercel (frontend, P-03)

- Import the repository; **Framework preset** Vite; **Root directory** repository root; **Build command** `npm run build`; **Output directory** `client/dist`; **Install command** `npm ci`. Node.js 24.x.
- Edit `client/vercel.json` before the first deploy: replace `REPLACE-WITH-RENDER-SERVICE` with the Render service name in the `/api/:path*` rewrite (one per environment).
- `vercel.json` also sets the security headers, including a strict Content-Security-Policy (`script-src 'self'`, images only from the app and Cloudinary). The built app was checked to run under it with no violations. Vercel serves HTTPS and HSTS automatically.

### 4.4 Cloudinary (P-05)

Create an account; copy the cloud name, API key and secret into the Render variables. Uploads are signed on the server; the client never sees the key. Folders are separated per environment by `CLOUDINARY_FOLDER_PREFIX` (default `gym/<NODE_ENV>`). Not yet tested against the real service.

### 4.5 SMTP (P-07)

Any provider (for example Brevo, Mailgun, Amazon SES, or the gym's mail host). Use a sender on a domain with SPF and DKIM. Only Admin password-reset emails are sent. Test with **Forgot password** on staging. Not yet tested against a real provider.

### 4.6 Backups (P-08)

Create a private S3-compatible bucket (Cloudflare R2, Backblaze B2 or AWS S3) and an access key limited to it; set the `BACKUP_*` variables. The weekly job runs on the scheduler instance (Sundays 03:00 Karachi). After the first run check **Settings → Backups**, then do the restore drill (`docs/BACKUP_RESTORE.md` §5–6). Tested with a local folder and a local fake S3 server only.

## 5. First start in an environment

1. Deploy Render, then Vercel. Open `https://<render-service>.onrender.com/api/v1/health` and the Vercel address.
2. Create the one-time setup token from a trusted machine with the same `MONGODB_URI` (and the other required variables) as the server, or from the Render **Shell**:

   ```bash
   npm run setup-token -w server     # prints a token valid for 24 hours; only its hash is stored
   ```

3. Open `https://<vercel-address>/setup`, enter the token and create the first Admin (`docs/ADMIN_GUIDE.md` §1). Setup then closes permanently (`/api/v1/auth/setup/status` → `setupAvailable: false`).
4. Follow the Admin guide: gym details, plans, staff.

## 6. External integrations still needing real accounts

### 6.1 Summary

| Service               | Status                    | What is needed                                 |
| --------------------- | ------------------------- | ---------------------------------------------- |
| Render, Vercel, Atlas | Not created (P-02 – P-04) | Accounts, paid Render instances, Atlas cluster |
| SMTP                  | Not configured (P-07)     | Provider, sender domain                        |
| Cloudinary            | Not configured (P-05)     | Account keys                                   |
| Backup bucket         | Not configured (P-08)     | Bucket, scoped key, key custody                |
| Meta WhatsApp         | Not configured (P-06)     | §6.2                                           |
| Custom domain         | Deferred (C-37, P-09)     | Add to Vercel; add to `APP_ORIGIN`             |

### 6.2 Meta WhatsApp Cloud API (P-06)

1. Meta Business account and business verification; a WhatsApp Business Account and sender number (C-37).
2. A system-user permanent token with `whatsapp_business_messaging` and `whatsapp_business_management`; the app secret; a verify token of your choosing.
3. On Render: `WHATSAPP_MODE=live` and the six `WHATSAPP_*` variables.
4. In the Meta app: webhook URL `https://<render-service>.onrender.com/api/v1/webhooks/whatsapp`, the same verify token, subscribed to `messages` and `message_template_status_update`. Webhooks are verified with the app secret (HMAC); unsigned or wrongly signed calls are refused.
5. In the app (**WhatsApp → Templates**): create templates (or **Check status with Meta**); simulated approvals do not count (D-117).
6. Send a template to a staff phone, confirm Delivered arrives via the webhook, then share one receipt. **None of this has been tested with Meta yet.**

## 7. Free-tier limits and paid dependencies

| Service        | Free tier usable for                      | Limitation                                | Paid need                                     |
| -------------- | ----------------------------------------- | ----------------------------------------- | --------------------------------------------- |
| Vercel         | Development, staging, possibly production | Hobby terms for commercial use; confirm   | Possibly Pro (P-12)                           |
| Render         | Short demos only                          | Sleeps after 15 min idle                  | **Yes**: always-on for staging and production |
| Atlas          | Development and staging                   | 512 MB; no cloud backups                  | Production tier to be decided                 |
| Cloudinary     | Likely sufficient                         | Monthly credits                           | Only if usage grows                           |
| Meta WhatsApp  | —                                         | Per-message charges for template messages | **Yes**, per Meta pricing                     |
| SMTP           | Low volume                                | Daily caps                                | Unlikely                                      |
| Backup storage | 8 small backups                           | —                                         | Low cost if any                               |

Re-check all prices and limits at deployment (SRS §14.2, Appendix B).

## 8. Release process

1. Merge to the staging branch → staging deploys.
2. Smoke test on staging: health check; sign in; Join Now inquiry; add a member; membership with a partial payment; verify a pending online payment; receipt PDF; report PDF; Settings → Backups; WhatsApp status.
3. UAT on real phones (Android Chrome, iPhone Safari), both languages and themes.
4. **Check client IPs:** sign in from two different networks, then in **Settings → Login history** confirm the entries are recorded (and, as operator, that `ipHash` differs between them in the database). If all requests share one hash, adjust `TRUST_PROXY`.
5. Tag the release, merge to `main`, production deploys. Watch the Render logs (JSON lines; secrets and phone numbers are redacted) for 30 minutes.
6. **Rollback:** Render "Rollback to previous deploy" and Vercel "Promote previous deployment". Schema changes are additive, so a rollback never needs a database restore.

## 9. Operations

- **Logs:** structured JSON on stdout (Render log stream). Each response carries a `requestId` that also appears in error messages, for finding the log line.
- **Errors:** users get a short message and a request ID; details stay in the logs.
- **Scheduled jobs** (Asia/Karachi): membership lifecycle 00:05, expiry reminders 00:10, WhatsApp dispatcher every minute, template status 06:00, image clean-up hourly, backup Sunday 03:00.
- **Partially restored database:** the server refuses to start on it with a clear message (D-136); see `docs/BACKUP_RESTORE.md` §5.

## 10. Troubleshooting

| Symptom                                                         | Likely cause and fix                                                                                                  |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Server exits with "Invalid environment configuration"           | A required variable is missing or unsafe; the message lists each one (§3)                                             |
| Health check `503` / "db":"down"                                | Wrong `MONGODB_URI`, Atlas network access, or Atlas paused                                                            |
| Sign-in works but every request then says "Please sign in"      | The frontend is not using the Vercel rewrite (cookie on the wrong site); call the API only through the Vercel address |
| "This request was blocked because it did not come from the app" | `APP_ORIGIN` does not match the address in the browser (check https, the exact domain, no trailing slash)             |
| Everyone gets "Too many requests" together                      | `TRUST_PROXY` too low (§8 step 4)                                                                                     |
| "holds an unfinished restore" at start-up                       | `MONGODB_URI` points at a partial restore; finish it with `--resume` or point at another database                     |
| Image upload says "not set up yet"                              | Cloudinary variables missing                                                                                          |
| WhatsApp "disabled"                                             | `WHATSAPP_MODE` not `live`, or Meta not set up                                                                        |
| No reset emails                                                 | SMTP variables or sender domain; check the logs                                                                       |
| Backup warning                                                  | Settings → Backups shows the error; check bucket credentials and `BACKUP_ENCRYPTION_KEY`                              |

## 11. Deployment readiness checklist

- [ ] Accounts: Render (paid), Vercel, Atlas, SMTP, Cloudinary, backup bucket (P-02 – P-08); Meta when ready (P-06)
- [ ] All variables in §3 set in Render; none in the repository
- [ ] `client/vercel.json` rewrite points at the right Render service
- [ ] Health check green; first Admin created; setup closed
- [ ] `TRUST_PROXY` verified (§8 step 4)
- [ ] First weekly backup succeeded; restore drill done in staging
- [ ] Password-reset email received on staging
- [ ] WhatsApp templates approved and a test message delivered (when going live with WhatsApp)
- [ ] UAT signed off on real phones
