# Namecheap Deployment Guide

Internal operational document. Do not publish this guide to platform users. It contains deployment assumptions and environment setup details that should stay inside the engineering/operations workspace.

This guide covers deployment of the Smart Estate API to Namecheap. It includes two paths:

- **Recommended production path:** Namecheap VPS or Dedicated Server with Node.js, PostgreSQL, reverse proxy, and process manager.
- **Staging/MVP or small-production path:** Namecheap Stellar Plus Shared Hosting cPanel using **Setup Node.js App** and cPanel PostgreSQL.

Official Namecheap references:
- Shared Hosting plan features: https://www.namecheap.com/hosting/shared/
- Shared server software versions: https://www.namecheap.com/support/knowledgebase/article.aspx/129/22/what-version-of-the-software-is-used-on-your-servers/
- Node.js on Shared Hosting: https://www.namecheap.com/support/knowledgebase/article.aspx/10047/2182/how-to-work-with-nodejs-app/
- Node.js on VPS/Dedicated server: https://www.namecheap.com/support/knowledgebase/article.aspx/10202/48/how-to-install-nodejs-on-a-vps-or-a-dedicated-server/
- cPanel overview, including Node.js App, Terminal, and PostgreSQL tools: https://www.namecheap.com/support/knowledgebase/article.aspx/9797/29/cpanel-control-panel-overview/

## Deployment Decision

Use **Namecheap VPS** for higher-volume production if you expect many real estates, heavy mobile app usage, frequent payment callbacks, and live OTP traffic. It gives you better control over Node.js, PostgreSQL, SSL, firewall, backups, process management, and future Redis.

Use **Namecheap Stellar Plus Shared Hosting cPanel** for staging, demos, MVP launch, or small production where cPanel confirms Node.js App and PostgreSQL are available. It can run Node.js apps and PostgreSQL from cPanel, but you have less control over long-running processes, logs, package installation, background jobs, and scaling.

## Stellar Plus Production Assumption

You said the backend and WebApp frontend will run on Namecheap Stellar Plus, with PostgreSQL available through cPanel.

Use this deployment shape:

```text
WebApp: https://gatewise.ng
API:    https://api.gatewise.ng
API v1: https://api.gatewise.ng/v1
Docs:   https://api.gatewise.ng/docs
```

Recommended Stellar Plus setup:

- Create `api.gatewise.ng` as a subdomain in cPanel.
- Create the backend as a cPanel Node.js App attached to `api.gatewise.ng`.
- Create the frontend as a static build or frontend app attached to `gatewise.ng`.
- Create the production database in cPanel PostgreSQL Databases.
- Keep `API_PREFIX=""` so the API exposes `/v1` at the API subdomain root.
- Set WebApp and MobileApp API base URLs to `https://api.gatewise.ng/v1`.
- Set production CORS to `https://gatewise.ng,https://www.gatewise.ng`.
- Keep Swagger and sandbox protected by super-admin console login.

Important Stellar Plus caveats:

- Confirm PostgreSQL, Node.js App, Terminal or SSH, and SSL are active in your exact cPanel account before launch.
- Shared hosting is resource-limited. Monitor CPU, memory, process restarts, storage, inodes, logs, and database size.
- Keep a migration, backup, and restore routine before adding real estates.
- Upgrade to VPS when traffic, background jobs, real-time needs, or compliance requirements outgrow shared hosting.

## Production URLs

GateWise production domains:

```text
Web app:   https://gatewise.ng
API base:  https://api.gatewise.ng/v1
Swagger:   https://api.gatewise.ng/docs
Sandbox:   https://api.gatewise.ng/v1/sandbox
Console:   https://api.gatewise.ng/v1/console/login
```

Both WebApp and MobileApp should consume the same API base:

```text
API_BASE_URL=https://api.gatewise.ng/v1
```

Swagger and sandbox are protected by super-admin console login. They are not public.

## Pre-Deploy Checklist

Run locally before uploading:

```powershell
npm.cmd install
npm.cmd --workspace apps/api run db:generate
npm.cmd --workspace apps/api run lint
npm.cmd --workspace apps/api run test
npm.cmd --workspace apps/api run build
npm.cmd audit --omit=dev
```

Confirm the migrations are ready:

```powershell
npm.cmd --workspace apps/api run db:generate
npm.cmd --workspace apps/api exec prisma migrate status
```

For production deployments, use:

```powershell
npm.cmd --workspace apps/api run db:deploy
```

Do not use `prisma migrate dev` on production.

Clean local deployment noise before packaging:

```powershell
Remove-Item -Force *.log -ErrorAction SilentlyContinue
git diff --check
git status --short
```

Do not package local secrets or generated dependency folders:
- Do not upload `.env` from your local machine.
- Do not upload `node_modules`.
- Do not upload local log files.
- Upload source, `package.json`, `package-lock.json`, `server.js`, `apps/api/prisma`, and the rest of the repository code.

## Required Environment Variables

Set these in Namecheap cPanel Node.js App variables, `.env`, or the VPS process manager:

```env
NODE_ENV=production
PORT=3000
API_PORT=3000
API_PREFIX=""
API_VERSION=1
DATABASE_URL="postgresql://USER:PASSWORD@HOST:5432/DB_NAME?schema=public"
CORS_ORIGINS="https://gatewise.ng,https://www.gatewise.ng"
JWT_ACCESS_SECRET="replace-with-long-random-secret"
JWT_REFRESH_SECRET="replace-with-another-long-random-secret"
INTEGRATION_CONFIG_SECRET="replace-with-third-long-random-secret"
CONSOLE_SESSION_TTL=8h

SUPER_ADMIN_PHONE="+234..."
SUPER_ADMIN_NAME="Platform Super Admin"

OTP_DELIVERY_PROVIDER=TERMII
OTP_PROVIDER_PRIORITY=TERMII,AFRICAS_TALKING,CUSTOM_HTTP
OTP_CODE_TTL_SECONDS=300
OTP_CODE_LENGTH=6
OTP_MAX_ATTEMPTS=5
OTP_EXPOSE_DEV_CODE=false

TERMII_BASE_URL="https://api.ng.termii.com"
TERMII_API_KEY="replace"
TERMII_SENDER_ID="SmartEstate"
TERMII_CHANNEL="dnd"

AFRICASTALKING_BASE_URL="https://api.africastalking.com/version1/messaging"
AFRICASTALKING_USERNAME="replace"
AFRICASTALKING_API_KEY="replace"
AFRICASTALKING_SENDER_ID="SmartEstate"

PAYMENT_GATEWAY_MODE=live
PUBLIC_API_BASE_URL="https://api.gatewise.ng"
PAYMENT_CALLBACK_URL="https://api.gatewise.ng/v1/onboarding/payments/callback"
STRIPE_SUCCESS_URL="https://api.gatewise.ng/v1/onboarding/payments/callback?provider=STRIPE&reference={reference}&status=success&session_id={CHECKOUT_SESSION_ID}"
STRIPE_CANCEL_URL="https://api.gatewise.ng/v1/onboarding/payments/callback?provider=STRIPE&reference={reference}&status=cancelled&session_id={CHECKOUT_SESSION_ID}"
```

For a staging server, keep `PAYMENT_GATEWAY_MODE=sandbox` and use sandbox keys.

For the dedicated API subdomain deployment, run the Node.js app at the subdomain root:

- Use `API_PREFIX=""` so the backend exposes `/v1` directly on `https://api.gatewise.ng`.
- Do not point the production WebApp or MobileApp at `https://gatewise.ng/api/v1` now that the API subdomain exists.
- If you later deploy behind a path-based proxy, you may restore `API_PREFIX="api"` and use `/api/v1`, but that is no longer the preferred GateWise setup.

## Shared Hosting / cPanel Deployment

Use this when you are deploying to Namecheap Shared Hosting.

Namecheap shared hosting uses cPanel's **Setup Node.js App** interface for Node apps. That interface lets you set the Node.js version, application mode, application root, application URL, startup file, run NPM install, restart the app, and add environment variables.

### 1. Create Database

In cPanel:

1. Open **PostgreSQL Databases**.
2. Create a database, for example `cpaneluser_smart_estate`.
3. Create a PostgreSQL user.
4. Assign the user to the database.
5. Build `DATABASE_URL`:

```env
DATABASE_URL="postgresql://cpaneluser_dbuser:password@localhost:5432/cpaneluser_smart_estate?schema=public"
```

If Namecheap gives a different database host, use that host instead of `localhost`.

### 2. Upload Clean Code

Recommended upload options:

- cPanel Git Version Control if your repository is hosted remotely.
- cPanel File Manager zip upload and extract.
- SSH/SFTP upload.

If using a zip, create it from a clean working tree and exclude:

```text
node_modules
apps/api/node_modules
apps/api/dist
.env
apps/api/.env
*.log
.git
```

Install dependencies and build on the server.

### 3. Create Node.js App

In cPanel:

1. Open **Setup Node.js App**.
2. Click **Create Application**.
3. Select Node.js `22` or `24` if available.
4. Set **Application mode** to `Production`.
5. Set **Application root** to your uploaded repository folder.
6. Set **Application URL** to `https://api.gatewise.ng` so the Node.js app owns the API subdomain root.
7. Set **Application startup file** to:

```text
server.js
```

The root `server.js` file loads the compiled Nest API from `apps/api/dist/src/main.js`.

Recommended cPanel field values:

| Field | Value |
| --- | --- |
| Node.js version | `22` or `24` |
| Application mode | `Production` |
| Application root | Uploaded repository folder |
| Application URL | `https://api.gatewise.ng` |
| Startup file | `server.js` |

### 4. Add Environment Variables

In the Node.js App environment variables screen, add the production values from **Required Environment Variables** above.

Also create a server `.env` file in the application root with the same values so NestJS and Prisma CLI both resolve configuration consistently:

```bash
cd /home/CPANEL_USER/smart-estate-api
nano .env
```

Then copy it to the API workspace for Prisma commands:

```bash
cp .env apps/api/.env
```

Never commit or upload your local development `.env`.

### 5. Install, Build, Migrate

Open cPanel Terminal or SSH into the application root:

```bash
npm install
npm --workspace apps/api run db:generate
npm --workspace apps/api run build
npm --workspace apps/api run db:deploy
```

Create the initial super admin:

```bash
SUPER_ADMIN_PHONE="+234..." SUPER_ADMIN_NAME="Platform Super Admin" npm --workspace apps/api run db:seed:superadmin
```

If disk space is tight after a successful build and migration, you may prune dev dependencies:

```bash
npm prune --omit=dev
```

Use this only after `db:deploy` and `build` have already succeeded.

Restart the Node.js app in cPanel.

### 6. Verify Backend

Open:

```text
https://api.gatewise.ng/v1
https://api.gatewise.ng/docs
```

Expected health response:

```json
{
  "message": "Smart Estate API is running",
  "version": "1",
  "status": "ok"
}
```

Swagger should redirect to the super-admin console login.

If the health URL returns `404`:

1. Open the app root URL in cPanel to confirm the Node app is running.
2. Confirm `API_PREFIX=""`.
3. Restart the Node.js app.
4. Reopen `https://api.gatewise.ng/v1`.

### 7. Configure Live Third-Party Keys

After the first super-admin login, update live provider keys through the Super Admin UI or API. Secrets are encrypted with `INTEGRATION_CONFIG_SECRET` and are never returned in full.

Useful endpoints:

```text
GET   /v1/admin/integrations/templates
GET   /v1/admin/integrations/config
PATCH /v1/admin/integrations/config/FLUTTERWAVE
PATCH /v1/admin/integrations/config/TERMII
PATCH /v1/admin/integrations/config/SMTP
```

Example Flutterwave update:

```json
{
  "category": "PAYMENT",
  "enabled": true,
  "publicConfig": {
    "baseUrl": "https://api.flutterwave.com/v3",
    "publicKey": "FLWPUBK_LIVE_xxx"
  },
  "secretConfig": {
    "secretKey": "FLWSECK_LIVE_xxx",
    "encryptionKey": "FLW_ENCRYPTION_KEY"
  }
}
```

Example Termii update:

```json
{
  "category": "SMS",
  "enabled": true,
  "publicConfig": {
    "baseUrl": "https://api.ng.termii.com",
    "senderId": "SmartEstate",
    "channel": "dnd"
  },
  "secretConfig": {
    "apiKey": "TERMII_API_KEY"
  }
}
```

Payment and OTP providers read refreshed values immediately with `.env` values as fallback. Email keys can be stored now for the future email module.

## VPS Deployment

Use this path for production.

### 1. Server Requirements

Recommended minimum:

- Ubuntu 22.04 or 24.04
- Node.js 22 LTS or later
- PostgreSQL 15+
- Nginx
- PM2 or systemd
- SSL certificate

### 2. Install Node.js and PM2

```bash
node --version
npm --version
npm install -g pm2
```

If Node is not installed, install Node.js 22 using your preferred server package method.

### 3. Clone and Build

```bash
git clone <your-repo-url> smart-estate
cd smart-estate
npm install
npm --workspace apps/api run db:generate
npm --workspace apps/api run build
npm --workspace apps/api run db:deploy
```

Create the initial super admin:

```bash
SUPER_ADMIN_PHONE="+234..." SUPER_ADMIN_NAME="Platform Super Admin" npm --workspace apps/api run db:seed:superadmin
```

### 4. Start with PM2

```bash
PORT=4000 NODE_ENV=production pm2 start apps/api/dist/src/main.js --name smart-estate-api
pm2 save
pm2 startup
```

### 5. Nginx Reverse Proxy

Example:

```nginx
server {
  server_name gatewise.ng www.gatewise.ng;

  location /api/ {
    proxy_pass http://127.0.0.1:4000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}
```

Add SSL using your preferred certificate flow.

### 6. Deploy Updates

```bash
cd smart-estate
git pull
npm install
npm --workspace apps/api run db:generate
npm --workspace apps/api run build
npm --workspace apps/api run db:deploy
pm2 restart smart-estate-api
```

## Production Security Checklist

- Set `OTP_EXPOSE_DEV_CODE=false`.
- Do not enable `DEV` in `OTP_ENABLED_PROVIDERS`.
- Use long random JWT secrets.
- Use a long random `INTEGRATION_CONFIG_SECRET`; changing it later prevents existing stored third-party secrets from decrypting.
- Set `CORS_ORIGINS` to real frontend domains.
- Use `PAYMENT_GATEWAY_MODE=live` only after live provider credentials are ready.
- Keep `https://api.gatewise.ng/docs` and `https://api.gatewise.ng/v1/sandbox` super-admin protected.
- Restrict database access to the API server where possible.
- Enable automated database backups.
- Keep `.env` out of git.

## Frontend Handoff Values

Give frontend engineers:

```text
WEBAPP_ORIGIN=https://gatewise.ng
API_BASE_URL=https://api.gatewise.ng/v1
MOBILEAPP_API_BASE_URL=https://api.gatewise.ng/v1
SWAGGER_URL=https://api.gatewise.ng/docs
SANDBOX_URL=https://api.gatewise.ng/v1/sandbox
FRONTEND_API_GUIDE=docs/frontend-api-guide.md
PRODUCTION_READINESS_CHECKLIST=docs/production-readiness-checklist.md
```

They should not call the Swagger or sandbox URLs from the public app.

Before publishing frontend clients against the deployed API, run the WebApp and MobileApp gates in `docs/production-readiness-checklist.md`. The WebApp strict check must use an HTTPS API URL, and the MobileApp must not ship with hardcoded localhost API values.

Before deploying the WebApp, sync public legal policy pages from the backend workspace:

```powershell
npm.cmd run legal:sync
```

This keeps `https://gatewise.ng/legal` as the single public Policy Center used by the WebApp, MobileApp, and customer-facing references.

## Troubleshooting

### App Does Not Start on cPanel

- Confirm startup file is `server.js`.
- Confirm `npm --workspace apps/api run build` created `apps/api/dist/src/main.js`.
- Confirm Node.js version is 22 or later.
- Check cPanel Node.js app logs.
- Confirm `PORT` is set by cPanel or `API_PORT` is set manually.

### Prisma Generate Fails on Windows

Stop running Node/Nest/API processes, then rerun:

```powershell
npm.cmd --workspace apps/api run db:generate
```

### Migrations Pending

On production:

```bash
npm --workspace apps/api run db:deploy
```

On local development:

```powershell
npm.cmd --workspace apps/api run db:migrate
```

### CORS Errors in Frontend

Set:

```env
CORS_ORIGINS="https://gatewise.ng,https://www.gatewise.ng,http://localhost:3000,http://localhost:5173"
```

Restart the API after changing it.

For the GateWise production deployment, use:

```env
CORS_ORIGINS="https://gatewise.ng,https://www.gatewise.ng"
```

### OTP Does Not Arrive

- Confirm live provider credentials.
- Confirm sender ID approval.
- Confirm `OTP_EXPOSE_DEV_CODE=false` only after SMS delivery is verified.
- Check `/v1/admin/otp/config` with a super-admin token.

### Payment Callback Does Not Match Payment

- Confirm `PAYMENT_CALLBACK_URL`.
- Confirm provider dashboard callback/redirect URLs.
- Confirm the callback includes `reference`, `tx_ref`, `trxref`, `paymentReference`, `transaction_id`, `session_id`, or `transactionReference`.
