# Frontend vs backend guide

> Understand what runs in your visitor's browser versus on ExaSpark servers, why secrets and permissions stay server-side, and how ExaSpark splits both automatically.

- Canonical: https://exaspark.ai/docs/frontend-vs-backend/

## The two halves of every real app

Every web or mobile app runs on two separate computers at once: the **frontend** inside your visitor's browser or phone, and the **backend** on secure cloud servers managed by ExaSpark.

Think of a restaurant. The **frontend** is the dining room — the menu, lighting, and table controls customers see and touch. The **backend** is the locked kitchen and register — where inventory is verified, cards are charged, and staff enforce who may enter restricted areas.

```text
VISITOR'S BROWSER (FRONTEND — UNTRUSTED)
  • Pages, buttons, forms, animations, design tokens
  • Sends HTTPS requests (GET /api/classes, POST /api/bookings)
                         │
              Encrypted HTTPS + Session Cookie
                         ▼
EXASPARK CLOUD SERVER (BACKEND — TRUSTED AUTHORITY)
  • Verifies identity & role (member vs admin)
  • Enforces row-level privacy & server-side pricing
  • Holds private secrets (Stripe keys, API keys, SMTP)
  • Reads & writes Managed Relational Database + Storage
  • Receives verified webhooks from Stripe & external APIs
```

Grasping this boundary explains almost every production security rule, checkout pattern, and database bug you will meet while launching software.

## Frontend vs backend at a glance

Although ExaSpark writes and wires both sides from one conversation, each layer carries a strict trust boundary.

| Dimension | Frontend (Browser / Client) | Backend (ExaSpark Server / Cloud) |
| --- | --- | --- |
| **Where code executes** | Inside the visitor's browser or phone | Inside ExaSpark's managed cloud runtime |
| **Who can inspect or alter it** | Anyone via browser DevTools or modified HTTP requests | Server only — visitors never see server code or secrets |
| **Primary responsibility** | Fast UI rendering, responsive layouts, inline form hints | Auth sessions, RBAC, database reads/writes, payments, emails |
| **Concrete examples** | Dark mode toggle, calendar picker, loading skeletons | Verifying admin role, charging `$25`, checking webhooks |
| **Trust rule** | Treat every client payload as **untrusted input** | Treat server logic and **Cloud** DB as source of truth |

## Why secrets, pricing, and permissions never belong in UI code

The biggest security trap in AI-built demos is assuming that hiding something visually protects it. Because browser code runs on the visitor's own machine, anyone can inspect network calls and send altered requests straight to your endpoints.

### API keys and credentials

Any secret placed inside frontend code — such as a Stripe secret key (`sk_live_...`) or third-party AI API key — becomes public the moment a page loads. Someone can copy it in seconds and bill your account.

ExaSpark keeps private keys strictly as **server-side secrets** injected at runtime. Your UI calls your own backend route (`POST /api/ai/summarize`), and your server attaches the secret safely before calling external providers. See [Secrets & environment variables](https://exaspark.ai/docs/secrets-and-env-vars/).

### Price and discount math

Never trust a price sent from the browser. Imagine a tampered checkout request sent directly from DevTools:

```http
POST /api/checkout HTTP/1.1
Content-Type: application/json

{
  "pass_id": "dropin-reformer",
  "client_calculated_price_cents": 1
}
```

A secure backend ignores `client_calculated_price_cents`, looks up `"dropin-reformer"` inside **Cloud** (`2500` cents), validates coupons on the server, and opens Stripe Checkout for `$25.00`.

### Role and ownership checks

Hiding an **Admin** button from the navigation bar does not secure admin endpoints. Anyone can still call `/api/admin/users` or swap `booking_id=42` for `booking_id=43`:

```json
{
  "status": 403,
  "error": "FORBIDDEN",
  "message": "You do not have permission to modify this booking."
}
```

Every protected endpoint must verify **who is calling** (valid server session) and **what they may access** (admin role or row ownership `booking.user_id === session.user.id`). See [Row-level data privacy](https://exaspark.ai/docs/row-level-data-privacy/).

## How ExaSpark coordinates both layers in one turn

When tools build frontend screens separately from external backends, contracts break constantly: a new UI field never reaches the database, or a dashboard leaks rows because server rules lag behind.

In **App** or **Web** mode, ExaSpark updates every layer together on each turn:

- **Frontend UI.** Generates responsive pages, form controls, inline formatting hints, and clear loading or error states.
- **Backend APIs.** Creates typed endpoints that re-validate inputs, check sessions and roles, and compute authoritative totals.
- **Managed Cloud database.** Updates relational tables, foreign keys, and constraints matching the exact API schema.
- **Server integrations.** Wires Stripe Checkout, webhook signature verification, private uploads, and branded emails strictly server-side.

### Prompting clearly across the boundary

You never need to write server code manually, yet naming what must happen **on the server** keeps every financial and permission rule airtight on turn one:

> **Example prompt (App):** Add a promo code field to checkout. Provide quick formatting hints in the UI as users type, but validate codes strictly on the server against our Cloud coupons table: enforce active dates, one-use-per-user rules, and redemption caps, compute discounted totals in integer cents on the server, and return clear 400 errors for invalid codes.

## Deciding where each feature belongs

| Feature or behavior | Frontend | Backend | Why |
| --- | --- | --- | --- |
| **Dark mode, tabs & drawer animations** | Yes | No | Pure presentation with zero security impact |
| **Inline email or phone format hints** | Yes (UX speed) | **Also Yes** (enforcement) | Browser feels snappy; server blocks bypassed payloads |
| **Order totals, taxes & refund math** | Display only | **Required** | Prevents tampered `$0.01` checkout requests |
| **Seat capacity & double-booking locks** | Show status | **Required** | Server checks prevent two buyers claiming the last spot |
| **Paid AI or third-party API calls** | Trigger & render | **Required** | Keeps API keys hidden and enforces rate limits |
| **Sending receipts & login emails** | Trigger action | **Required** | Protects sending credentials and records delivery logs |
| **Admin approvals & deleting records** | Admin controls | **Required** | Verifies server session and `admin` role on every call |

## Verifying the boundary before you publish

Run this quick five-minute boundary check inside **Preview** before launching any app with accounts or payments.

1. **Use two test accounts** — Sign in as a regular `member` in one browser window and an `admin` in a separate incognito window.
2. **Visit restricted routes directly** — As the regular member, type `/admin` directly into the route bar and confirm the app blocks access without flashing private rows.
3. **Test cross-user record URLs** — Copy a private URL (like `/orders/<id>`) from Account A and open it under Account B. Confirm the server refuses access with a `403` or `404` error.
4. **Run an Agent security review** — Inspect `server/` handlers in the **Code** tab or prompt `"Audit every backend route for missing auth, role checks, server-side pricing, and secret handling."`

> **Note:** You do not need to read server code alone to verify safety. Ask ExaSpark to audit every endpoint against [Pre-launch security audit](https://exaspark.ai/docs/pre-launch-security-audit/) before clicking **Publish**.

## Common architecture mistakes and fixes

| Symptom | Root cause | Fastest fix |
| --- | --- | --- |
| **Admin link hidden, yet `/admin` loads data** | Check lived only on the navbar, not the route or API | Prompt ExaSpark to enforce server `admin` role checks on every admin route and endpoint |
| **Prompt asked to paste an API key in UI** | External call was wired in browser JavaScript | Ask the Agent to move the request to a backend route reading from server secrets |
| **Refresh loses a newly saved form field** | Input was added to UI without updating the API and DB column | Prompt ExaSpark to add the **Cloud** column and map it in the save handler |
| **Checkout succeeds, yet plan stays Free** | Access unlocked only on the Thank You page instead of webhook | Move fulfillment inside the verified Stripe webhook route on the server |

## Next steps

- [Authentication & roles](https://exaspark.ai/docs/authentication-and-roles/) — Configure 19+ sign-in providers and server-enforced member, staff, and admin roles.
- [Row-level data privacy](https://exaspark.ai/docs/row-level-data-privacy/) — Isolate every user's private records reliably on the server.
- [Secrets & environment variables](https://exaspark.ai/docs/secrets-and-env-vars/) — Store third-party API keys and webhook secrets safely out of browser code.

## From the blog

- [Frontend vs backend explained](https://exaspark.ai/blog/frontend-vs-backend/) — Visual primer on how browsers, servers, and databases cooperate.
- [What is an API?](https://exaspark.ai/blog/what-is-an-api/) — Plain-English guide to endpoints, HTTP methods, and JSON payloads.
- [App security checklist](https://exaspark.ai/blog/app-security-checklist/) — Essential pre-launch protections for every founder shipping live software.
