# Deploying Hatch

Hatch isn't launched yet. This is how to run it when it is. Everything here is ready, but the Docker images haven't been built on a real host yet, so expect small fixes the first time.

## What runs where

| Address | What it is |
|---|---|
| `app.example.com` | The web app. Static files served by Caddy. |
| `api.example.com` | The Hatch server: accounts, sync, publishing, mail. |
| `<slug>.sites.example.com` | Published sites. Each gets its own origin. |
| `blog.someone.com` | A site on its owner's own domain. |

Caddy sits in front of everything and gets every certificate itself. Sites get theirs on first visit (on-demand TLS). Caddy asks the server first (`/tls/ask`), so only real sites get one.

For a real launch, put sites on a domain of their own, like `<slug>.example-sites.com`, rather than under the app's domain. A published site runs its owner's scripts, and a script on `x.sites.example.com` can set cookies for all of `example.com`. Nothing in Hatch relies on such cookies today (the apps sign in with tokens), but a separate domain keeps it that way. The `sites.example.com` layout above is fine for trying Hatch out.

## One machine with Docker

You need a small Linux server with Docker and a domain.

1. Point DNS at the server: `app`, `api` and a wildcard `*.sites`, all as A (and AAAA) records.
2. Copy `deploy/.env.example` to `deploy/.env` and fill it in. Make the secret with `openssl rand -base64 32`.
3. From the repo root: `docker compose -f deploy/docker-compose.yml --env-file deploy/.env up -d --build`
4. Open `https://app.example.com` and create an account.

The wildcard also covers `cname.sites.example.com`, the name people point their own domains at (see below).

Data lives in Docker volumes: `hatch-data` (the SQLite database and every vault) and `caddy-data` (certificates).

A third volume, `hatch-assets`, keeps earlier builds' code. A tab opened before a deploy (or the copy of the app the service worker serves first) still asks for its own build's files when it opens a canvas, a collection or settings. Each start of the web container copies the new build in beside the old ones (`deploy/web-start.sh`), and a retired build's files are removed 30 days after the deploy that replaced it. Caddy serves the current build from the image first, so losing the volume is harmless: the next start fills it again, and only tabs from before that deploy would need a reload.

## Only on a tailnet

To try Hatch on a machine that already runs something else, without opening it to the internet, run it on your Tailscale network. Caddy and the server listen on localhost only, and `tailscale serve` gives them HTTPS on the machine's tailnet name. Published sites need a public domain, so they don't work this way.

1. In `deploy/.env`, use the machine's tailnet name with two free HTTPS ports Tailscale allows (443, 8443 or 10000): `APP_DOMAIN=box.tailnet.ts.net:8443`, `API_DOMAIN=box.tailnet.ts.net:10000`. Set `SITES_DOMAIN=sites.invalid`. `ACME_EMAIL` isn't used.
2. Start it: `docker compose -f deploy/docker-compose.yml -f deploy/tailnet/compose.yml --env-file deploy/.env up -d --build`. The app listens on `127.0.0.1:8791` and the server on `127.0.0.1:8790`. Change them with `HATCH_APP_PORT` and `HATCH_API_PORT` if something else uses them.
3. Serve them on the tailnet. This adds two ports and leaves whatever Tailscale already serves alone:
   `tailscale serve --bg --https=8443 http://127.0.0.1:8791` and `tailscale serve --bg --https=10000 http://127.0.0.1:8790`.
4. Open `https://box.tailnet.ts.net:8443` from a device on the tailnet and create an account.

The server is capped at 512 MB of memory (`HATCH_SERVER_MEMORY`) so it can share a small machine. Backups work the same as below. If the bucket also holds another server's backups, give this one its own `HATCH_BACKUP_PATH`, such as `staging/hatch.db`, so the two never mix. To build on a faster computer instead, build the images there for `linux/amd64` and copy them over with `docker save` and `docker load`.

## Coolify

[Coolify](https://coolify.io) runs Hatch from this repository on your own server, with HTTPS from its proxy.

1. In Coolify, add a resource from your Git repository with the **Docker Compose** build pack. Set Base Directory to `/` and Docker Compose Location to `/deploy/coolify/docker-compose.yml`.
2. Give the two services a domain each: `web` (the app, like `app.example.com`) and `server` (like `api.example.com`). Coolify passes them to Hatch, and makes and keeps the sign-in secret (`SERVICE_PASSWORD_64_AUTH`).
3. Deploy, open the app's address and create an account.

Mail, backups and error reports take the same settings as above (`HATCH_MAIL`, `HATCH_BACKUP_*`, `HATCH_ERROR_DSN`); set them in the resource's environment. The web service uses the `web-plain` image, which serves files on plain HTTP and leaves HTTPS to Coolify.

Published sites are off here (`SITES_DOMAIN` is unset). They need a wildcard domain and a certificate for each site on its first visit, which Coolify's proxy doesn't do. To publish, run the Caddy setup above instead, or point a wildcard domain at the server service and set `SITES_DOMAIN`.

## Sites on their own domains

Owners can move a site to a domain they own, like `blog.someone.com`, from Publish in the app. Nothing to set up beyond the DNS above. The app shows them two records to add:

| Type | Name | Value |
|---|---|---|
| CNAME | `blog.someone.com` | `cname.sites.example.com` |
| TXT | `_hatch.blog.someone.com` | `hatch-verify=<a token for that site>` |

- The TXT record proves the domain is theirs. Pointing a domain at the server isn't enough, or anyone could claim a domain someone else already points here.
- A root domain like `someone.com` can't have a CNAME. The app shows the server's addresses for an A or AAAA record instead, or they can use their DNS provider's ALIAS or flattening.
- Once the record is seen, Caddy gets a certificate for the domain on its first visit (on-demand TLS asks the server's `/tls/ask` first, which only says yes to proven domains). The site's `<slug>.sites.example.com` address then redirects there.
- `HATCH_DOMAINS_TARGET` changes the CNAME target if `cname.<sites domain>` doesn't suit.

With Cloudflare in front (below), keep the `cname` record **DNS only** (grey cloud) and pointed straight at the server. Cloudflare refuses a CNAME from someone else's Cloudflare zone to a proxied name in yours, and Caddy needs to answer the certificate challenge itself. Proxying custom domains through Cloudflare too needs Cloudflare for SaaS.

## Backups

Accounts and every table are in one SQLite file, `/data/hatch.db` in the server container. Litestream, built into the server image, sends every change to an R2 bucket within 10 seconds. If the machine or its disk is lost, a new machine restores the database from the bucket by itself before the server starts.

What you get:

- At most the last 10 seconds of changes can be lost. On a normal stop or redeploy, nothing is lost: the last changes upload before the container exits.
- 7 days of history. You can restore the database as it was at any moment in that week.
- An alert when backups stop, if you set a heartbeat URL.

With R2 file storage on, file bytes live in the R2 files bucket, not in the database, so this backup covers rows and the files bucket covers itself. Without R2 file storage, files are in the database and this backup covers them too.

### Turn them on

1. In Cloudflare, make a second R2 bucket just for backups, for example `hatch-backups`. Keep it private.
2. Make an R2 API token with Object Read and Write on that bucket only.
3. Optional: make a check on [healthchecks.io](https://healthchecks.io) (free) with a 10 minute period and copy its ping URL. Litestream pings it every 5 minutes, but only while backups are getting through, so you get an email when they stop.
4. Set these in `deploy/.env` and run `docker compose ... up -d` again:

| Variable | Value |
|---|---|
| `HATCH_BACKUP_BUCKET` | The backup bucket's name |
| `HATCH_BACKUP_ACCOUNT` | Your Cloudflare account id. Can be left out when `HATCH_R2_ACCOUNT` is set. |
| `HATCH_BACKUP_KEY_ID` | The token's access key id |
| `HATCH_BACKUP_SECRET` | The token's secret |
| `HATCH_BACKUP_HEARTBEAT_URL` | Optional, the ping URL from step 3 |
| `HATCH_BACKUP_ENDPOINT` | Optional, for any S3 compatible store instead of R2 |

The server log starts with `litestream` lines when backups are on, and with `backups are off` when they aren't. The server never sees the backup keys.

Keep `HATCH_AUTH_SECRET` somewhere safe too, like a password manager. The backup holds the database, and sessions need the same secret to work after a restore.

### Restore on a new machine

Set up the new machine with the same `deploy/.env` and start it. With an empty `hatch-data` volume, Litestream restores the latest backup first, then starts the server. The log says `restore completed`.

A machine that already has a database never restores over it.

### Go back to an earlier moment

To undo a mistake, like a bad migration or a deleted account, restore a copy from before it and swap it in:

```sh
cd deploy
# A copy of the database as it was at that moment (UTC), checked by SQLite
docker compose run --rm --no-deps server /app/start.sh restore \
  -timestamp 2026-12-01T09:30:00Z -integrity-check full -o /data/restored.db
# Swap it in while the server is stopped. Removing the old WAL files matters.
docker compose stop server
docker compose run --rm --no-deps --entrypoint sh server -c \
  'mv /data/hatch.db /data/hatch.db.old && rm -f /data/hatch.db-wal /data/hatch.db-shm && mv /data/restored.db /data/hatch.db'
docker compose start server
```

Leave out `-timestamp` to get the latest copy. Delete `hatch.db.old` once you're happy.

### Check that it works

Once a month the Restore drill workflow restores the newest backup into a scratch file and checks it (`scripts/restore-drill.sh`, which you can also run by hand). Turn it on with a `HATCH_BACKUP_BUCKET` repository variable and `HATCH_BACKUP_ACCOUNT`, `HATCH_BACKUP_KEY_ID` and `HATCH_BACKUP_SECRET` secrets (a read-only R2 token is enough), plus `HATCH_RESTORE_HEARTBEAT_URL` for a monitor that alerts when a month passes without a good restore.

`scripts/backup-check.sh` runs the whole thing against a local S3 server: it starts the server under Litestream the way the image does, makes an account, deletes the data folder, starts again and checks the account was restored, then restores by hand to the latest moment and to a moment before the account existed. Run it after changing anything in `deploy/` or how the server opens its database.

## Files on Cloudflare R2

The database keeps rows. File bytes (published sites, synced vaults, resumes) live in a blob store. Without settings that's a table in the database, which is fine for one small machine. For anything real, use R2: storage is cheap and downloads are free.

1. In Cloudflare, make an R2 bucket, for example `hatch`. Keep it private.
2. Make an R2 API token with Object Read and Write on that bucket.
3. Set these and restart:

| Variable | Value |
|---|---|
| `HATCH_R2_BUCKET` | The bucket name |
| `HATCH_R2_ACCOUNT` | Your Cloudflare account id |
| `HATCH_R2_KEY_ID` | The token's access key id |
| `HATCH_R2_SECRET` | The token's secret |

Switching is safe on a running server. On start it moves files already in the database to R2 in the background, and reads fall back to the database until that's done. The log says how many moved.

Files are named by their content (`site/<id>/<sha256>`), so a republish only uploads what changed, and anything no longer used is deleted.

## Cloudflare in front

Put the app, the API and the sites behind Cloudflare's proxy. It caches what's safe to cache and absorbs traffic spikes for free.

- Use a separate domain for sites, like `example-sites.com`, with sites at `<slug>.example-sites.com`. Cloudflare's free certificate covers one level of subdomain only, so `<slug>.sites.example.com` would need a paid certificate. A separate domain also keeps site cookies away from the app.
- Proxy `app`, `api` and the wildcard `*` record on the sites domain.
- SSL mode Full (strict). Give Caddy a Cloudflare Origin Certificate for each domain instead of on-demand certificates.
- No cache rules needed. The server already says what to cache:
  - Files with a content hash in their name (`site.3f2a9c1e0b.css`, `assets/photo-960.8b1c2d3e4f.webp`) are cached for a year, at the edge and in browsers.
  - Pages are revalidated on every visit. The ETag turns that into a tiny 304, and a new publish shows at once with no purging.
  - Private sites are never cached by Cloudflare.

### Cloudflare with Alchemy

`infra/alchemy.run.ts` describes the whole Cloudflare side in TypeScript with [Alchemy](https://alchemy.run), all on the free plan:

- The web app on Workers static assets at your app domain, with the same headers and skew protection as the Caddy setup (`infra/build-web.sh` keeps the last 30 days of builds' files in `infra/.web-archive`, so deploy from the same machine or cache that folder).
- `api` and the wildcard on the sites domain proxied to the server's IP.
- On both zones: SSL Full (strict), TLS 1.2 or newer, Cloudflare's Free Managed Ruleset, two custom rules (scanner paths like `/.env` and `/wp-admin`, and methods Hatch never uses), and a rate limit on sign-in (20 requests per 10 seconds from one address to sign-in, sign-up, password reset and the second sign-in step). Plain HTTP still reaches Caddy, which renews its certificates over it and sends everything else to HTTPS.
- Each ruleset owns its whole phase on its zone, so custom rules, rate limits or managed rules added there by hand are replaced. On the app zone the custom rules apply only to the app and API hosts. Move any rules you need into `infra/alchemy.run.ts`.
- The two private R2 buckets for files and backups. Existing ones are taken over and kept if the stack is ever destroyed.

The zones must already be on Cloudflare, and the sites domain must be its own zone. The Worker doesn't use Workers Logs, so visitors' requests to the web app aren't kept. Custom site domains stay DNS only (above); proxying them needs Cloudflare for SaaS, a later step.

1. Make a Cloudflare API token with Zone Read, Zone Settings Edit, DNS Edit, Zone WAF Edit, Workers Scripts Edit, Workers Routes Edit and R2 Edit, for your account and the two zones.
2. In `infra/`, run `pnpm install --ignore-workspace` (it has its own lockfile, outside the app's workspace).
3. Set these, in your shell or `infra/.env`:

| Variable | What |
|---|---|
| `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | The token and your account |
| `HATCH_ZONE` | The app's zone, like `example.com` |
| `HATCH_APP_HOST`, `HATCH_API_HOST` | Like `app.example.com` and `api.example.com` |
| `HATCH_SITES_ZONE` | The sites domain, like `example-sites.com` |
| `HATCH_ORIGIN_IPV4`, `HATCH_ORIGIN_IPV6` | The server's addresses (IPv6 optional) |
| `HATCH_ERROR_DSN`, `HATCH_RELEASE` | Optional, built into the web app as with Docker |
| `HATCH_R2_BUCKET`, `HATCH_BACKUP_BUCKET` | Bucket names, `hatch` and `hatch-backups` by default |

4. The web app moves from Caddy to the Worker. Delete the DNS record for the app's host first (Cloudflare won't put a Worker on a name that already has one), Caddy's block for `APP_DOMAIN` then goes unused: its certificate stops renewing, and Caddy logs a retry now and then, which does no harm. Records for the API and the sites wildcard are taken over as they are.
5. `pnpm run plan` shows what would change. `pnpm run apply` builds the web app and applies it. Both turn off Alchemy's usage reporting (`DO_NOT_TRACK=1`). State is kept in `infra/.alchemy`, so keep that folder too.
6. Before applying, make sure Caddy already has certificates for the API and the sites wildcard: strict TLS refuses an origin without a valid one. Caddy keeps renewing them through the proxy over plain HTTP.
7. On the server, set `TRUSTED_PROXIES` for Caddy to Cloudflare's IP ranges (https://www.cloudflare.com/ips-v4 and https://www.cloudflare.com/ips-v6, space-separated). Caddy then takes the visitor's address from `CF-Connecting-IP`, only from those ranges, so rate limits and the sign-in log see real visitors and nobody can fake one. Unset, Caddy trusts no proxy, so behind Cloudflare every visitor would share Cloudflare's addresses. If no site uses its owner's own domain (those reach the server directly), also let only Cloudflare reach ports 80 and 443 in the server's firewall, so the WAF can't be gone around.

Images are sized when publishing: the app makes WebP copies at 480, 960 and 1440 pixels wide, and every image gets `srcset`, `width` and `height`. Phones download phone-sized images, and pages don't jump while they load. There's no image service to pay for.

## Spam checks on public forms

Rate limits and a hidden field stop most spam. To also check that a person sent a public form, turn on Cloudflare Turnstile. It's free.

1. In Cloudflare, open Turnstile and add a widget. Mode Managed. Hostnames: your sites domain (it covers every site's subdomain) and the API's domain (for the report page).
2. Set `HATCH_TURNSTILE_SITE_KEY` and `HATCH_TURNSTILE_SECRET`.

Pages with a site's form, a job application, an email signup or a follow form then get the widget when they're served, with nothing to republish. It shows only when Cloudflare can't tell on its own. Sites on an owner's own domain keep the rate limits only, since Turnstile accepts only the hostnames you listed. If Cloudflare can't be reached, those forms wait and say to try again.

## Mail

Leave `HATCH_MAIL` empty until mail is set up. Without mail, new accounts don't need to confirm their email, password resets and newsletters can't send. `HATCH_MAIL=log` prints each email to the server's output for trying things out on your own machine. It counts as no mail when `NODE_ENV=production`, because it would print password reset and sign-in links to the logs. The server says so when it starts. Without mail, an invite to an address goes to whoever signs up with that address, so set up mail before inviting people you don't know.

To turn it on, set `HATCH_MAIL` to `resend` or `postmark`, plus `HATCH_MAIL_KEY` and `HATCH_MAIL_FROM`. The sender's domain needs SPF, DKIM and DMARC records from your provider.

## Server settings

The server checks these when it starts and stops with a list of anything wrong. To check them without starting it, run `pnpm --filter @hatch/server check-config` with the same environment.

| Variable | What it does |
|---|---|
| `HATCH_URL` | The server's own address |
| `HATCH_ORIGINS` | Web app addresses allowed to call it, comma separated. Single sign-on returns people to the web address they started from, or the first one listed, so list the main web app first and leave development addresses out in production. |
| `HATCH_SITES_HOST` | The domain sites live under. Must differ from the API's. |
| `HATCH_DOMAINS_TARGET` | Where owners point their own domains. `cname.<HATCH_SITES_HOST>` by default. |
| `HATCH_AUTH_SECRET` | Signs sessions. Keep it secret, never change it. |
| `HATCH_TRUST_PROXY` | `1` behind Caddy, so rate limits see the real visitor |
| `HATCH_DB` | Where the database file lives |
| `HATCH_R2_*` | File storage on R2 (see above) |
| `HATCH_BACKUP_*` | Continuous database backups (see above) |
| `HATCH_BLOB_CACHE` | Bytes of recently read files kept in memory, 64 MB by default |
| `HATCH_MAX_*` | Limits per account (see `apps/server/src`) |
| `HATCH_ABUSE_EMAIL` | Where abuse reports about hosted sites go, each with a link to take the site down |
| `HATCH_ACCESS_LOG` | `0` turns off the JSON line per request on stdout (route pattern, status, time, account id, never content). On by default. |
| `HATCH_SECURITY_EMAIL` | Where security researchers report problems, listed in `/.well-known/security.txt` (see `.github/SECURITY.md`). Without it that file isn't served. |
| `STRIPE_SECRET_KEY` | Turns on plans and billing. Without it every account gets every feature. |
| `STRIPE_WEBHOOK_SECRET` | Signing secret of the Stripe webhook at `https://<API_DOMAIN>/api/billing/webhook` (see `docs/development.md`) |
| `HATCH_ERROR_DSN` | Crash reports from the server and web app (see `docs/errors.md`) |
| `HATCH_OTEL_ENDPOINT`, `HATCH_OTEL_HEADERS` | Performance traces to an OpenTelemetry collector (see `docs/tracing.md`) |
| `HATCH_TURNSTILE_SITE_KEY`, `HATCH_TURNSTILE_SECRET` | Cloudflare Turnstile on public forms (see "Spam checks on public forms") |
| `HATCH_RELEASE` | The version being deployed, shown on crash reports |
| `HATCH_STARTER` | `showcase` starts new visitors in a fuller example vault (`fixtures/showcase-vault`: work notes, a journal, a collection, a canvas), for showing Hatch to people. Unset, they get the usual starter |

## Abuse reports and takedowns

Anyone can report a hosted site at `/report` on the server. Hosted sites link to it from their footer (`Report`), and `<site>/__report` goes there too.

- With `HATCH_ABUSE_EMAIL` and mail set up, each report is emailed there with a review link. The link works for 14 days and needs no sign-in, so don't forward it.
- The review page takes the site down or brings it back. A site that's down shows a 451 page at every address and can't be published again. Its owner gets an email saying why (if their address is confirmed) and sees it in the app.
- From the server's shell, with the same env as the server:

```sh
pnpm --filter @hatch/server admin reports
pnpm --filter @hatch/server admin takedown <site> "Reason the owner sees"
pnpm --filter @hatch/server admin restore <site>
```

In Docker: `docker compose -f deploy/docker-compose.yml exec server node admin.mjs reports` (same commands).

An owner can't delete or send email from a site that's down, so the takedown and its reports stay until you restore it.

## Without Docker

```sh
pnpm install
pnpm --filter @hatch/server build          # apps/server/dist/server.mjs
cd apps/web && VITE_HATCH_SERVER=https://api.example.com npx vite build
```

Run `node apps/server/dist/server.mjs` next to a `node_modules` with `better-sqlite3`, and serve `apps/web/dist` with any static file server. Use `deploy/Caddyfile` as the model for headers and caching. `index.html` and `sw.js` must never be cached long, or people won't get updates.

## Desktop apps

Build on the platform you're building for:

```sh
pnpm --filter @hatch/desktop dist       # installers in apps/desktop/release
pnpm --filter @hatch/desktop dist:dir   # just the unpacked app, for a quick try
```

Pushing a tag like `v0.1.0` runs `.github/workflows/desktop.yml`, which builds macOS, Windows and Linux and publishes a release.

Auto-update:

- Installed apps check for a new version at start and every 6 hours. It downloads in the background and installs when the app quits.
- Updates come from GitHub releases in `alexwhitmore/hatch-releases`. It must be public, because installed apps read it without signing in. Change it in `apps/desktop/electron-builder.yml`.
- macOS only updates signed apps. Add the Apple certificate and notarizing secrets the workflow lists.
- People can turn checks off with `"autoUpdate": false` in the app's `hatch.json`.

Crash reports: add a `HATCH_ERROR_DSN` repository secret and the workflow builds it in (see `docs/errors.md`).

## Before launch

- Build both images on a real host and run through sign up, sync, publish, and a site on a domain of its own (the CNAME and TXT records above).
- Set up mail and test that confirmation emails land in the inbox.
- Make an Apple Developer account for signing, and a Windows signing certificate if SmartScreen warnings matter.
- Set up R2 and Litestream, and try a restore once.
- Delete a test account and check its sites and files are gone.
- Make a Sentry (or GlitchTip) project, set `HATCH_ERROR_DSN`, and check a test error arrives with no note content in it.
