Deployment
CrabStack is two deployable units that talk to each other over HTTP:
- Backend (
backend/): a long-running NestJS process. It needs a Postgres database and a host that keeps a Node process alive, because the cron workers run inside the process, not as external scheduled functions. - Frontend (
frontend/): Next.js 16. Runs as a Node server or on a serverless platform.
Nothing here is tied to a particular host. If it runs a persistent Node process and can reach a Postgres, it works. The fastest path is the deploy kit in deploy/: one VPS from any provider, Docker Compose, and Caddy for automatic HTTPS. This guide leads with that; the generic requirements for running anywhere else follow.
The 10-minute VPS path
What you need: a VPS from any provider (2 GB RAM is comfortable; the Next.js image build is the hungriest step), a domain, and an SMTP provider if you want email sign-in.
The kit is three files in deploy/:
docker-compose.prod.yml- Postgres, backend, frontend, and Caddy. Only Caddy binds host ports (80/443); everything else stays on the compose-internal network.Caddyfile- reverse proxy plus automatic HTTPS via ACME..env.prod.example- every variable the stack needs, in one place.
1. Provision the box
Any Linux VPS with Docker Engine and Compose v2 installed, ports 80 and 443 open, root or sudo access.
2. Point DNS at it
Two A records to the box's IP: yourapp.com and api.yourapp.com. The API gets its own subdomain (see One domain, two origins). Wait for both to resolve before starting the stack: certificate issuance needs working DNS.
3. Clone and configure
git clone <your-repo-url> app && cd app
cp deploy/.env.prod.example deploy/.env.prod
Fill in deploy/.env.prod. The file documents every variable; the short version:
DOMAINandACME_EMAIL: your domain, and the email the certificate authority uses for expiry notices.POSTGRES_PASSWORD, plus the same password insideDATABASE_URL.AUTH_SECRET,INTERNAL_API_TOKEN: generate each withopenssl rand -base64 32. Boot-time validation rejects the placeholders, so a half-filled file fails loudly instead of running insecure.- SMTP credentials and/or OAuth client credentials: at least one sign-in method.
Every compose command takes the same two flags, so alias them once:
alias dcp='docker compose --env-file deploy/.env.prod -f deploy/docker-compose.prod.yml'
3b. If you are upgrading, read the changelog
Read CHANGELOG.md from your last merge forward, starting with each release's Breaking / action required section. Those sections are the only warning you get about changes that merge and compile cleanly and then behave differently, such as a new Stripe webhook event to subscribe to or an env var that stopped being checked at boot.
4. Build, migrate, start
dcp build
dcp run --rm backend npm run migrate
dcp up -d
Migrations are an explicit step on purpose: nothing auto-migrates on boot. The run --rm line starts Postgres (waiting for its healthcheck), runs the Knex migrations in a one-off container, and exits. Re-running an applied migration is a no-op.
Updating uses the same three commands: git pull, then build, migrate, up. When deploy/Caddyfile changed, also run dcp restart caddy: up -d does not reload a bind-mounted Caddyfile.
Caddy requests certificates as soon as it starts. Give it a few seconds, then open https://yourapp.com.
5. Make yourself the first admin
There is no default admin account, so /backoffice answers 404 until you grant the first admin from a shell, the same as it does for anyone who is not an admin. Sign in once on the live site so your user row exists, then:
dcp exec backend npm run admin:grant -- [email protected]
It says so if no user has that email yet; sign in first. The flag is read from the database on every request, so /backoffice opens on your next page load, without signing out. The command needs only DATABASE_URL, so on another host run it wherever the backend runs (a platform's console for the backend service, say).
After that, grant or revoke admin for anyone else from Users in /backoffice. It will not change your own row, so the last admin cannot remove themselves and lock everyone out.
One domain, two origins
Caddy serves two origins from the one box:
| Origin | Upstream |
|---|---|
https://yourapp.com |
frontend (frontend:3000) |
https://api.yourapp.com |
backend (backend:4000) |
The backend gets a subdomain rather than a path prefix because its routes live at the root of its own origin: /openapi.json, /admin/mcp/oauth, and the MCP OAuth discovery documents under /.well-known/ all assume no prefix, and BACKEND_URL bakes absolute URLs into the discovery metadata. Serving it under a path prefix would mean rewriting all of that. The browser calls the API cross-origin via NEXT_PUBLIC_API_URL, and the backend's ALLOWED_ORIGINS CORS allowlist is what permits those calls.
The compose file derives all the public URLs from DOMAIN, so the origins, CORS allowlist, and OAuth discovery URLs cannot drift apart.
Managed Postgres instead
If you would rather not run the database yourself, any managed Postgres 13+ works. Set DATABASE_URL in deploy/.env.prod to the provider's connection string, then delete the postgres service and the backend's depends_on block from docker-compose.prod.yml. POSTGRES_PASSWORD goes unused. Set DATABASE_CA_CERT in deploy/.env.prod (double-quoted, since the PEM spans several lines; the compose file passes it to the backend) to the provider's CA certificate (the PEM text, which DigitalOcean App Platform injects as ${db.CA_CERT}) and use sslmode=verify-full or verify-ca in the URL, so the backend authenticates the database instead of only encrypting. See Database TLS for what each sslmode does. See Database for the notes that apply either way.
Running it anywhere else
The kit is optional. What each piece needs:
Both halves need Node 24.15.0+ on the Node 24 line, or Node 26; the provided images ship Node 26.
| Piece | Requirement |
|---|---|
| Backend | A persistent process (node dist/main.js), not a serverless function: the email worker runs every 30 seconds, the deletion worker every minute, session cleanup hourly. Outbound network for SMTP. |
| Frontend | next start behind a TLS-terminating proxy, or a serverless Next.js host. Env vars settable at build and runtime. |
| Postgres | Any Postgres 13+ (the migrations use only gen_random_uuid() from pgcrypto, default-on in 13+). Self-hosted or managed. |
| SMTP | Any SMTP provider. |
Backend. Build with npm ci && npm run build; start with npm run migrate && node dist/main.js under something that keeps it alive and restarts it (systemd, a Docker restart policy, pm2). The in-process cron is why you want a supervised, always-on process, not a scale-to-zero one. Run migrations as part of the deploy, before the process accepts traffic. Set TRUST_PROXY to the number of proxies in front of it; without it, per-IP rate limits collapse into the proxy's single IP. If the last proxy hop is an ingress address many clients share, as behind some CDN and platform chains, also set CLIENT_IP_HEADER on both backend and frontend to the header your platform sets to the client address and overwrites on every request (cf-connecting-ip behind Cloudflare). Set it only when the origin accepts connections solely from that proxy. Behind Cloudflare, firewall the origin to Cloudflare's published IP ranges or use Authenticated Origin Pulls. Otherwise anyone who reaches the origin directly sends the header themselves, every client picks its own address, and every per-IP limit is bypassed. The same happens on a platform that does not overwrite the header. The deploy kit passes CLIENT_IP_HEADER through from deploy/.env.prod, empty by default.
Keep /internal/* private. Those routes carry session tokens and email addresses behind nothing but INTERNAL_API_TOKEN. Point the frontend's INTERNAL_API_URL at a private address, and make any public proxy in front of the backend answer /internal/* with 404, matching the raw request URI as well as the cleaned path, as deploy/Caddyfile does. With CLIENT_IP_HEADER set, the backend also answers 404 to any /internal/* request that carries that header, in any letter case, so a request the edge forwarded never reaches those routes even where the edge's own path rule cannot match the way Express routes. Keep the proxy rule as well.
MCP OAuth, rate limits and multiple replicas. Registered MCP OAuth clients are stored in Postgres, but the five-minute auth codes (mcp-shared/mcp-oauth.internals.ts) live in an in-process Map, so the handshake breaks nondeterministically behind more than one backend replica (a code issued on one replica can't be redeemed on another). The stateless MCP transport itself has no such limit. Stay on a single backend replica until auth codes are persisted too. The per-IP limits (the global throttler and the MCP limiters) also live in process memory: each replica counts separately, so a client spread across N replicas gets up to N times the limit, and a restart resets the counts.
Frontend. npm run build, then npm run start. NEXT_PUBLIC_* is baked in at build time while NextAuth reads its own vars at runtime, so set both. The Dockerfile takes NEXT_PUBLIC_API_URL and NEXT_PUBLIC_SITE_URL as build args for exactly this reason, and a value supplied only at runtime leaves the built bundle pointing at localhost. proxy.ts runs as edge middleware for the CSP nonce and works either way.
Five frontend vars are required in production: NEXT_PUBLIC_API_URL, NEXT_PUBLIC_SITE_URL, AUTH_URL, INTERNAL_API_TOKEN and AUTH_SECRET (at least 32 characters, not a template placeholder). Set the two NEXT_PUBLIC_* vars as Docker build args (see above), not only at runtime. What refuses boot says which of these stop boot, and when. Also set INTERNAL_API_URL, and make INTERNAL_API_TOKEN match the backend's. Full descriptions: Environment Variables.
Set NODE_ENV=production on both halves. The frontend's boot checks run only under it. The backend refuses short or placeholder secrets unless NODE_ENV is exactly development or test, so an unset or misspelled value is enforced like production and a misconfigured deploy fails loudly instead of coming up insecure. Both provided images already set it.
Database
Run migrations on every deploy (npm run migrate in backend/). Knex is idempotent: re-running an applied migration is a no-op.
Any Postgres 13+ works, on the same box or a separate instance. Two notes:
- Keep the database close to the backend (same host or same region); the app makes many small queries.
- If your Postgres sits behind a connection pooler, use the pooled connection string (managed providers usually hand you one, often with
sslmode=require, which encrypts but does not verify the server; addDATABASE_CA_CERTas above). A single box rarely needs a pooler, but you can put PgBouncer in front if you ever do.
SMTP
The frontend sends magic-link emails (synchronous, via NextAuth). The backend sends bulk and transactional emails (queue plus worker). Both take the same kind of SMTP credentials, so point them at one provider: SMTP_* on the backend, EMAIL_SERVER_* plus EMAIL_FROM on the frontend. Verify your sending domain (SPF and DKIM) before sending to real addresses.
Health checks
Backend (API origin). Two public probe routes. GET / is liveness: it answers { ok: true } without touching the database. GET /health/ready is readiness: it runs select 1 and answers { ok: true }, or 503 when the query fails or runs past 2 seconds. Waiting for a pool connection is not covered by that bound, so give the probe its own timeout. Both count against the global rate limit. The compose files probe Postgres only.
Frontend (site origin). Point any platform or load-balancer health probe at /robots.txt, not /. The / route renders dynamically (it reads the session, and Next applies the CSP nonce from the header proxy.ts sets, per request), so every probe would trigger a full server render. /robots.txt is statically prerendered (see frontend/app/robots.ts), so it is the cheapest "is the process up?" answer.
A process missing AUTH_URL, INTERNAL_API_TOKEN or a valid AUTH_SECRET exits at startup, so the probe never sees it. A build that shipped without NEXT_PUBLIC_API_URL or NEXT_PUBLIC_SITE_URL still starts and answers /robots.txt; only the routes that import auth.ts 500 (What refuses boot). next build does not fail on it. Supply both as Docker build args every time (see above), and if you want it caught before users do, add your own check to the deploy pipeline (grep the built output for the URL you expect, or a post-deploy smoke test that hits / and /api/auth/session) rather than relying on /robots.txt.
OAuth callback URLs
When you set up GitHub or Google OAuth apps, the redirect URI is:
- GitHub:
https://yourapp.com/api/auth/callback/github - Google:
https://yourapp.com/api/auth/callback/google
Add both your production URL and http://localhost:3000/api/auth/callback/... for local development. Some providers (Google) reject localhost on a production OAuth client, so create a separate dev client for local work.
Pre-launch checklist
Before pointing real users at the deployment:
-
NODE_ENV=productionset on backend and frontend (the kit sets it). -
AUTH_URLset.NEXT_PUBLIC_SITE_URLandNEXT_PUBLIC_API_URLalso set, as Docker build args, not only at runtime: a missing one does not stop boot (see Health checks), so check them by hand. All three otherwise fall back tolocalhost. The kit derives all three fromDOMAIN. -
AUTH_SECRET,INTERNAL_API_TOKENboth rotated from.envplaceholders. -
INTERNAL_API_TOKENmatches between frontend and backend. It also signs the visitor address the frontend forwards for the backend's rate limits. -
ALLOWED_ORIGINSon backend lists your frontend origin only (no wildcards; the kit derives it fromDOMAIN). -
TRUST_PROXYset to the number of proxies in front of the backend (the kit sets1for Caddy), andCLIENT_IP_HEADERon both apps if the last hop is a shared ingress address and the origin is locked to that proxy (how). - OAuth apps have production callback URLs configured.
-
FRONTEND_URLset to the frontend's origin: the backend refuses to boot without it, and invite emails, Stripe return URLs and the admin MCP consent page link there. - If billing is enabled: production webhook endpoint subscribed to the eight events listed in Billing, Customer Portal enabled in the Stripe dashboard.
- If billing is enabled: Stripe's failed-payment setting done in live mode, as in Billing setup step 5.
- Sending domain verified with the SMTP provider (SPF and DKIM).
-
npm run migrateruns as part of the deploy step. - Test magic-link sign-in end-to-end on the live deployment before announcing.
- Your own account is an admin (step 5), so
/backofficeopens for you.
Related
- Environment Variables: full env-var reference.
- Auth Flow: how OAuth and magic-link sign-in work.
- Architecture: what each process owns.