> For the complete documentation index, see [llms.txt](https://spice.docs.medtroniclabs.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/admin-portal.md).

# Web Applications

SPICE has two browser-based applications. Both are single-page React applications that compile to static files, so in production they are served by any web server and talk to the backend through the public API address.

| Application               | Purpose                                                                                                                 | Source directory | Build tool                         |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------------------------------- |
| Admin web portal          | Sign-in, user, organisation, location, form and programme administration, and the entry point to the other applications | `spice_web`      | Vite                               |
| Reporting web application | Dashboards, registers and reports; reached from the admin portal                                                        | `report_web`     | Create React App (`react-scripts`) |

Deploy the [backend services](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/server.md) first. Both applications need a working backend, and sign-in always happens in the admin portal.

## Prerequisites

| Requirement | Admin web portal                                      | Reporting web application |
| ----------- | ----------------------------------------------------- | ------------------------- |
| Node.js     | 22.x (Vite 8 needs 20.19 or later, or 22.12 or later) | 16.x LTS                  |
| npm         | 8 or later                                            | 8 or later                |
| Web server  | Any static file server; nginx is used below           | Same                      |
| HTTPS       | Required (the sign-in cookie is `Secure`)             | Required                  |

## Get the source

```bash
git clone <your-spice-web-repository-url> spice_web
git clone <your-report-web-repository-url> report_web
```

## Configuration

Both applications are configured with environment variables whose names start with `REACT_APP_`. **The values are compiled into the JavaScript bundle at build time**, so they must be set when you run `npm run build`, and changing a value means building again. Provide them in a `.env` file next to `package.json` (copy `env.example` to `.env`) or as shell environment variables. Shell variables take precedence over the file.

Never put secrets that must stay private in these variables: anything set here is visible to every browser that loads the application.

### Admin web portal

| Variable                           | Required                                | Description                                                                                                                                                                                     |
| ---------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REACT_APP_BASE_URL`               | Yes                                     | Public base URL of the backend gateway, with scheme and no trailing path, for example `https://<api-host>`. The portal calls `/<service-name>/...` paths on it, such as `/auth-service/session` |
| `REACT_APP_PASSWORD_HASH_KEY`      | Yes                                     | Key used to hash the password in the browser (HMAC-SHA512) before it is sent. Choose your own value; it must be the same value that the password hashes in your database and the mobile app use |
| `REACT_APP_CRYPTR_SECRET_KEY`      | Yes                                     | Key used to encrypt values the portal keeps in the browser. Choose your own value                                                                                                               |
| `REACT_APP_CFR_WEB_URL`            | If you deploy the reporting application | Public URL of the reporting web application; the portal links to it                                                                                                                             |
| `REACT_APP_INSIGHT_WEB_URL`        | Optional                                | URL of an analytics dashboard application to link to, if you run one                                                                                                                            |
| `REACT_APP_GA_TRACKING_ID`         | Optional                                | Web analytics measurement ID. Leave empty to disable                                                                                                                                            |
| `REACT_APP_ORG_SUCCESS_DELAY_TIME` | Optional                                | Delay in milliseconds before the portal leaves the "organisation created" confirmation; defaults to 1000                                                                                        |
| `REACT_APP_VERSION`                | Optional                                | Version label                                                                                                                                                                                   |

### Reporting web application

| Variable                      | Required | Description                                                                                                                                         |
| ----------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REACT_APP_BASE_URL`          | Yes      | Same backend gateway URL as above                                                                                                                   |
| `REACT_APP_SPICE_WEB_URL`     | Yes      | Public URL of the admin web portal. Users who are not signed in are sent there to sign in, and are returned to the reporting application afterwards |
| `REACT_APP_CRYPTR_SECRET_KEY` | Yes      | Key used to encrypt values kept in the browser. Choose your own value                                                                               |
| `REACT_APP_GA4_TRACKING_CODE` | Optional | Web analytics measurement ID. Leave empty to disable                                                                                                |

`env.example` in `report_web` also lists code-quality scanner variables (`REACT_APP_SONAR_*`) and `SKIP_PREFLIGHT_CHECK`; they are not needed to deploy.

## Install and build

Run these steps in each application's directory. Example for the admin web portal:

1. Install dependencies from the lock file:

   ```bash
   npm ci
   ```
2. Create the environment file and edit the values:

   ```bash
   cp env.example .env
   ```
3. Build:

   ```bash
   npm run build
   ```

   The `prebuild` script first writes `public/build-info.json` (the commit of the source tree, or `unknown` if the folder is not a git checkout), then the bundler writes the static site to the `build/` directory. For `spice_web` you can choose another output directory with the `BUILD_PATH` environment variable.

The reporting web application uses the same three steps. Its build writes to `build/`, and `npm run winBuild` is the equivalent for Windows shells (it also disables source maps).

To try the application locally before deploying, run `npm start`. The admin portal's development server listens on port 3000 and, when `REACT_APP_BASE_URL` is a bare `http://localhost` or `http://127.0.0.1` address, proxies the `/<service-name>` paths to the default local backend ports.

## Serve the static build

Copy the contents of each `build/` directory to your web server's document root and configure single-page-application fallback so that deep links such as `/users` return `index.html`. Both applications use browser (history) routing.

```nginx
server {
    listen 443 ssl;
    server_name <web-host>;

    # ssl_certificate and ssl_certificate_key go here

    root /var/www/spice-web;
    index index.html;

    location / {
        try_files $uri /index.html;
    }

    # Do not cache the entry document, so new releases are picked up
    location = /index.html {
        add_header Cache-Control "no-cache";
    }

    # Built assets have hashed file names and can be cached
    location /assets/ {
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}
```

For the reporting application (Create React App) the hashed assets are in `/static/` rather than `/assets/`.

Serve the two applications from separate host names (for example `admin.<your-domain>` and `reports.<your-domain>`), each with its own `root`.

In a container platform, build one image per application from an `nginx` base that holds the `build/` output and a configuration like the one above.

## Connect the applications to the backend

The browser sends requests to `REACT_APP_BASE_URL` and includes credentials (cookies) on every call. Sign-in sets an `HttpOnly`, `Secure` cookie named `AuthCookie`. Configure the backend and proxy to match:

1. **Single public API host.** Expose the backend through the reverse proxy described in [Backend Services](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/server.md#reverse-proxy-cors-and-cookies), under the path prefixes `/auth-service/`, `/user-service/`, `/spice-service/`, and so on.
2. **CORS.** Add the origin of each web application, exactly as typed in the browser (scheme, host, port, no trailing slash), to `ALLOWED_ORIGINS` on the backend services. For example `https://admin.example.org,https://reports.example.org`. Do not use `*` in production, because the requests are credentialed.
3. **Cookie domain.** Set `DOMAIN_NAME` on the backend to the parent domain shared by the web applications and the API (for example `example.org`). The cookie uses `SameSite=Strict`, so the web applications and the API must be on the same site. Set `ENVIRONMENT` to any value other than `dev` in a real deployment.
4. **HTTPS everywhere.** The cookie is `Secure`, so sign-in fails over plain HTTP.
5. **Same-host alternative.** If you serve a web application and the API from the same host name, set `REACT_APP_BASE_URL` to that host's public URL and add the `/<service-name>/` proxy locations to the same nginx server. This avoids cross-origin requests altogether.

If sign-in appears to succeed but the next screen returns "unauthorised", the cause is almost always a cookie that the browser rejected: check the `DOMAIN_NAME`, HTTPS and `ALLOWED_ORIGINS` settings above.

## Verify the deployment

1. Open the admin portal URL. The sign-in page loads without errors in the browser console.
2. Request the build information file and check that it returns JSON with a commit value:

   ```bash
   curl -s https://<web-host>/build-info.json
   ```
3. Open a deep link directly, such as `https://<web-host>/<any-route>`. You should get the application (not a `404`), which confirms the fallback rule.
4. In the browser developer tools, confirm that the sign-in request goes to `https://<api-host>/auth-service/session` and returns a successful response.
5. Sign in with the administrator account you prepared during the [backend setup](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/server.md#database-migrations-and-initial-data). The landing page lists the modules for your role.
6. If you deployed the reporting application, follow the link from the landing page. It should open without asking you to sign in again; if you are sent back to the admin portal, check `REACT_APP_SPICE_WEB_URL`, `REACT_APP_CFR_WEB_URL` and the cookie settings above.
7. Confirm the reporting application can reach `cfr-service`: its pages load data without network errors for `/cfr-service/...` requests.
