# Backend

The backend is one JavaScript ES module whose default export has a `fetch` method. It runs on Cloudflare Workers, isolated from every other app.

## Template without dependencies

Copy this when you have no build step. It is complete and can be deployed as it is.

```js
const json = (data, status = 200) => Response.json(data, { status });

const getUser = (request) => ({
  id: request.headers.get("x-boringcloud-user-id"),
  name: decodeURIComponent(request.headers.get("x-boringcloud-user-name") ?? ""),
  role: request.headers.get("x-boringcloud-role"), // "manager" or "viewer"
  kind: request.headers.get("x-boringcloud-user-kind") ?? "member", // "member" or "guest"
});

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname === "/__boringcloud/health") return json({ ok: true });
    const user = getUser(request);
    if (!user.id) return json({ error: "Sign in first." }, 401);
    try {
      if (url.pathname === "/api/me" && request.method === "GET")
        return json({ name: user.name, role: user.role });
      return json({ error: "Not found." }, 404);
    } catch (e) {
      console.error(e instanceof Error ? e.message : e);
      return json({ error: "Something went wrong." }, 500);
    }
  },
};
```

## Template with a build step

Starters made by `boringcloud init` contain `src/boringcloud.ts`, a small file without dependencies:

```ts
import { defineApp, error, json } from "./boringcloud";

export default defineApp(async (request, env, ctx) => {
  const { pathname } = new URL(request.url);
  if (pathname === "/api/me") return json({ name: ctx.user.name, role: ctx.user.role });
  return error(404, "Not found.");
});
```

| Helper                                       | What it does                                                            |
| -------------------------------------------- | ----------------------------------------------------------------------- |
| `defineApp(handler)`                         | answers the health check, reads the user, turns an exception into a 500 |
| `getContext(request)`                        | `{ appId, requestId, user: { id, name, role, kind } }`                  |
| `json(data, init)`, `error(status, message)` | build answers. Errors have the form `{ "error": "…" }`                  |
| `readJson(request, maxBytes)`                | reads a JSON body, or returns `null` when it is invalid or over 256 KiB |
| `callApi(api, path, init)`                   | calls an [external API](https://boring-cloud.app/docs/external-apis.md) approved by IT            |
| `files.put`, `get`, `list`, `delete`         | private [files](https://boring-cloud.app/docs/files.md)                                           |

Bundle everything into one file, for example with `esbuild src/worker.ts --bundle --format=esm --platform=neutral --target=es2022 --outfile=dist/worker.mjs`.

## Which requests arrive

- Only paths under `/api/`. All other paths serve the [frontend](https://boring-cloud.app/docs/frontend.md).
- Only from people who are signed in and may open the app. The gateway checks this on every request, before your code runs.
- `POST`, `PUT`, `PATCH` and `DELETE` only from the app's own pages. Other sites are refused, so you need no CSRF token.
- One exception: the platform calls `GET /__boringcloud/health` on each new release, without a user. Any answer below 500 passes. Code that throws at the top level of the module makes the deployment fail.

## The signed-in user

The gateway sets these headers and removes any copy sent by a browser. They are the only trustworthy source of identity.

| Header                     | Value                                                            |
| -------------------------- | ---------------------------------------------------------------- |
| `x-boringcloud-user-id`    | stable id of the person in this app. Another app sees another id |
| `x-boringcloud-user-name`  | display name, URI-encoded: use `decodeURIComponent`              |
| `x-boringcloud-role`       | `manager` or `viewer`                                            |
| `x-boringcloud-user-kind`  | `member` of the workspace, or `guest` invited from outside       |
| `x-boringcloud-app-id`     | id of the app                                                    |
| `x-boringcloud-request-id` | id to quote when reporting a problem                             |

The email address is not provided. Store the user id as the author of a record, and the name next to it for display.

A `guest` is a person from another organization invited to this app only, always as a `viewer` (see [People and access](https://boring-cloud.app/docs/users-and-access.md#people-outside-the-workspace)). Show guests only what they need: hide other people's records, internal notes and member lists unless the app is meant to share them.

```js
if (user.kind === "guest") return json({ items: await listItemsOf(user.id) });
```

## What the runtime offers

- Web standard APIs: `fetch`, `Request`, `Response`, `URL`, `crypto.subtle`, `crypto.randomUUID()`, `TextEncoder`, `Intl`, `FormData`.
- `env.APP_DB` when the manifest has `"database": true`. See [Database](https://boring-cloud.app/docs/database.md). `env` contains nothing else.
- Outside access to two places only: [approved APIs](https://boring-cloud.app/docs/external-apis.md) and the app's own [files](https://boring-cloud.app/docs/files.md).

## What it refuses

| You cannot use                                             | Instead                                                                   |
| ---------------------------------------------------------- | ------------------------------------------------------------------------- |
| `fetch` to any other address: answers `403 egress_blocked` | ask IT to approve the API                                                 |
| Node.js modules such as `fs`, `path`, `http`, `Buffer`     | web standard APIs                                                         |
| `import` of a package at run time                          | bundle it, or write the few lines you need                                |
| `eval`, `new Function`                                     | ordinary code                                                             |
| environment variables and secrets                          | approved APIs, whose key the platform adds                                |
| cookies and the `Authorization` header, both removed       | the identity headers above                                                |
| WebSockets, streaming from external APIs                   | load again from the page at an interval                                   |
| long work, retries, work at fixed times, email, PDF, AI    | the [platform services](https://boring-cloud.app/docs/platform-services.md)                         |
| variables kept in memory between requests                  | the database. A module can restart at any time, and run in several places |

## Answers

- The gateway sets `Cache-Control: private, no-store` and its own security headers. It removes `Set-Cookie`, CORS headers and any `Content-Security-Policy` you set.
- Redirects must stay in the app. Others become a `502`.
- To offer a download, set `Content-Type` and `Content-Disposition: attachment; filename="report.csv"`.

## Budget per request

50 ms of CPU time and 50 outside calls, where each database query counts as one. Waiting for a database or an API does not use CPU time. Beyond the budget, the request fails, usually with `502`. Use `batch` for several queries, and page through long lists. See [Limits](https://boring-cloud.app/docs/limits.md).
