JAlcocerTech E-books

The Fully Self-Hosted Version: PocketBase Behind Traefik

This is the exit from chapter 6, built out: the same engine on one server you control. Static sites served by nginx, the forms backend and the lead inbox in PocketBase, and Traefik in front, handling HTTPS certificates automatically.

I’ve used PocketBase before: my audit tool stored its leads in it before the lead hub existed. It’s a single binary with SQLite, an admin UI, and JavaScript hooks, which makes it a natural replacement for “a Worker plus KV”.

Everything below was run and tested before it went into this chapter, with PocketBase 0.40.5 and Traefik 3.7: the 404 page, the admin UI and PocketBase’s own API not reachable from outside, JSON and no-JavaScript submissions, the honeypot, the Origin check, consent rules, retention, and the security headers.

flowchart LR
  V([Visitor]) -->|"443"| T["Traefik<br/>Let's Encrypt · headers"]
  T -->|"Host(example.com)"| S["nginx<br/>static dist/"]
  T -->|"Host(example.com) && /api/forms/"| PB["PocketBase<br/>hooks · SQLite"]
  PB -.->|alert| N["ntfy"]
  A(["You, via SSH tunnel"]) -->|"127.0.0.1:8090/_/"| PB

The layout

selfhosted/
├── docker-compose.yml
├── .env                      # DOMAIN, ACME_EMAIL, NTFY_URL, NTFY_TOKEN
├── pocketbase/Dockerfile
├── pb_migrations/1760000000_create_leads.js
├── pb_hooks/config.js        # site registry + retention (data, not code)
├── pb_hooks/forms.pb.js      # POST /api/forms/submit + nightly retention
├── pb_data/                  # created on first run: the SQLite database
├── site/dist/                # your static build (Astro, Hugo…)
├── site/nginx.conf
└── letsencrypt/              # Traefik's certificates

Traefik, nginx and PocketBase

# Self-hosted lead engine: static site + PocketBase forms, behind Traefik
# with automatic HTTPS (Let's Encrypt). Set DOMAIN, ACME_EMAIL, NTFY_URL and
# NTFY_TOKEN in .env next to this file.
services:
  traefik:
    image: traefik:v3.7
    command:
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
      - --entrypoints.web.http.redirections.entrypoint.to=websecure
      - --entrypoints.web.http.redirections.entrypoint.scheme=https
      - --entrypoints.websecure.address=:443
      - --certificatesresolvers.le.acme.email=${ACME_EMAIL}
      - --certificatesresolvers.le.acme.storage=/letsencrypt/acme.json
      - --certificatesresolvers.le.acme.httpchallenge.entrypoint=web
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./letsencrypt:/letsencrypt
    restart: unless-stopped

  site:
    image: nginx:1.29-alpine
    volumes:
      - ./site/dist:/usr/share/nginx/html:ro
      - ./site/nginx.conf:/etc/nginx/conf.d/default.conf:ro
    labels:
      - traefik.enable=true
      - traefik.http.routers.site.rule=Host(`${DOMAIN}`)
      - traefik.http.routers.site.entrypoints=websecure
      - traefik.http.routers.site.tls.certresolver=le
      - traefik.http.routers.site.middlewares=secure-headers
      # The _headers file, as a Traefik middleware.
      - traefik.http.middlewares.secure-headers.headers.stsSeconds=31536000
      - traefik.http.middlewares.secure-headers.headers.stsIncludeSubdomains=true
      - traefik.http.middlewares.secure-headers.headers.frameDeny=true
      - traefik.http.middlewares.secure-headers.headers.contentTypeNosniff=true
      - traefik.http.middlewares.secure-headers.headers.referrerPolicy=strict-origin-when-cross-origin
      - traefik.http.middlewares.secure-headers.headers.permissionsPolicy=camera=(), microphone=(), geolocation=()
      - traefik.http.middlewares.secure-headers.headers.contentSecurityPolicy=default-src 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'
    restart: unless-stopped

  pocketbase:
    build: ./pocketbase
    command: ["serve", "--http=0.0.0.0:8090", "--dir=/pb/pb_data", "--hooksDir=/pb/pb_hooks", "--migrationsDir=/pb/pb_migrations"]
    environment:
      - NTFY_URL=${NTFY_URL:-}
      - NTFY_TOKEN=${NTFY_TOKEN:-}
    volumes:
      - ./pb_data:/pb/pb_data
      - ./pb_hooks:/pb/pb_hooks:ro
      - ./pb_migrations:/pb/pb_migrations:ro
    # The admin UI (/_/) is not routed publicly: reach it through an SSH tunnel.
    ports:
      - "127.0.0.1:8090:8090"
    labels:
      - traefik.enable=true
      # Only the forms path is public, on the site's own domain (same-origin).
      - traefik.http.routers.forms.rule=Host(`${DOMAIN}`) && PathPrefix(`/api/forms/`)
      - traefik.http.routers.forms.entrypoints=websecure
      - traefik.http.routers.forms.tls.certresolver=le
      - traefik.http.routers.forms.middlewares=secure-headers
      - traefik.http.services.forms.loadbalancer.server.port=8090
    restart: unless-stopped

What each part replaces:

  • HTTPS. Traefik redirects port 80 to 443 and requests a Let’s Encrypt certificate for DOMAIN on first use, renewing it automatically. The HTTP-01 challenge needs ports 80 and 443 reachable and the DNS record pointing at this server. If the domain stays behind Cloudflare’s proxy, use Traefik’s DNS-01 challenge with a Cloudflare API token instead.
  • _headers. The secure-headers middleware sends the same headers. HSTS is only sent over HTTPS, so don’t expect it when testing on plain HTTP.
  • The zone route. The forms router matches the same host and the /api/forms/ prefix. Traefik ranks longer rules first, so it wins over the site router. Sites keep posting to /api/forms/submit, same-origin, and nothing in the HTML changes.
  • Only the forms are public. PocketBase’s own REST API and its admin UI are not routed. The admin is published on 127.0.0.1 only: reach it with ssh -L 8090:127.0.0.1:8090 your-server and open http://localhost:8090/_/.

PocketBase in a container

PocketBase ships as a single binary, so the image is just Alpine plus the release:

FROM alpine:3.22
ARG PB_VERSION=0.40.5
RUN apk add --no-cache ca-certificates unzip wget \
 && wget -q "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_amd64.zip" -O /tmp/pb.zip \
 && unzip /tmp/pb.zip pocketbase -d /usr/local/bin \
 && rm /tmp/pb.zip \
 && adduser -D -H pb
USER pb
EXPOSE 8090
ENTRYPOINT ["/usr/local/bin/pocketbase"]

Create pb_data/ yourself before the first start (mkdir pb_data), so it belongs to your user rather than root, then create the first admin:

docker compose up -d --build
docker compose exec pocketbase pocketbase superuser upsert [email protected] 'a-long-password' --dir=/pb/pb_data

The lead inbox, as a migration

The collection is created by a migration file, so a fresh server gets exactly the same schema. All API rules are null: nothing can read or write leads through PocketBase’s API except an admin.

/// <reference path="../pb_data/types.d.ts" />
// The lead inbox. No API rules: nothing is public. The only way in is the
// /api/forms/submit route in pb_hooks, which validates first.
migrate((app) => {
  const leads = new Collection({
    type: "base",
    name: "leads",
    listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null,
    fields: [
      { name: "site", type: "text", required: true },
      { name: "kind", type: "text", required: true },
      { name: "email", type: "email", required: true },
      { name: "name", type: "text" },
      { name: "details", type: "text", max: 5000 },
      { name: "consent", type: "json" },
      { name: "attribution", type: "json" },
      { name: "expires_at", type: "date" },
      { name: "created", type: "autodate", onCreate: true },
    ],
    indexes: ["CREATE INDEX idx_leads_expires ON leads (expires_at)"],
  });
  app.save(leads);
}, (app) => {
  app.delete(app.findCollectionByNameOrId("leads"));
});

The forms endpoint, as a hook

The site registry and retention rules stay data, as they were in the Worker:

// Site registry and retention: the same rules the Worker had, as data.
module.exports = {
  SITES: {
    "www.example.com": { profile: "growth", kinds: ["enquiry", "newsletter"], consentTextVersion: "2026-10-01" },
  },
  // Days to keep each kind; 0 = until deleted (newsletter: until unsubscribe).
  RETENTION_DAYS: { enquiry: 730, qualifier: 90, newsletter: 0 },
};

And the endpoint itself. It’s the Worker’s logic, translated: which site, the Origin check, the honeypot, validation, consent rules, store first, then a best-effort alert with the email domain only, and a nightly retention job.

/// <reference path="../pb_data/types.d.ts" />

// POST /api/forms/submit: the self-hosted twin of the forms Worker.
// Same path, same form fields, same answers (202 JSON, or 303 for no-JS forms).
routerAdd("POST", "/api/forms/submit", (e) => {
  // Each handler runs in its own context: load shared config inside it.
  const { SITES, RETENTION_DAYS } = require(`${__hooks}/config.js`);

  const host = (e.request.host || "").toLowerCase().replace(/:\d+$/, "");
  const site = SITES[host];
  if (!site) return e.json(404, { ok: false, error: "unknown_site" });

  // Browsers send Origin on POST; it must be this site.
  const origin = e.request.header.get("Origin");
  if (origin && origin.replace(/^https?:\/\//, "").replace(/:\d+$/, "").toLowerCase() !== host) {
    return e.json(403, { ok: false, error: "bad_origin" });
  }

  const body = e.requestInfo().body || {};
  const str = (key, max) => String(body[key] || "").trim().slice(0, max);
  const wantsJson = (e.request.header.get("Content-Type") || "").includes("application/json");
  const back = str("page", 300) || "/";
  const done = (status, data) =>
    wantsJson ? e.json(status, data) : e.redirect(303, back + (data.ok ? "?form=sent" : "?form=error"));

  // Honeypot: answer like a success, store nothing.
  if (str("company_website", 200)) return done(202, { ok: true });

  const kind = str("kind", 40);
  const email = str("email", 254).toLowerCase();
  if (!site.kinds.includes(kind)) return done(422, { ok: false, error: "unknown_kind" });
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return done(422, { ok: false, error: "invalid_email" });

  const consent = { text_version: site.consentTextVersion, at: new Date().toISOString() };
  const truthy = (v) => v === true || v === "on" || v === "true";
  if (kind === "newsletter") {
    if (!truthy(body.consent_newsletter)) return done(422, { ok: false, error: "consent_required" });
    consent.newsletter = true;
  }
  if (site.profile === "growth" && truthy(body.consent_marketing)) consent.marketing = true;

  const record = new Record($app.findCollectionByNameOrId("leads"));
  record.set("site", host);
  record.set("kind", kind);
  record.set("email", email);
  record.set("name", str("name", 200));
  record.set("details", str("details", 5000));
  record.set("consent", consent.newsletter || consent.marketing ? consent : null);
  record.set("attribution", { page: back, referrer: e.request.header.get("Referer") || "" });
  const days = RETENTION_DAYS[kind] || 0;
  if (days) record.set("expires_at", new Date(Date.now() + days * 86400000).toISOString());

  // Store first: if this fails, the visitor gets an error, never a fake "sent".
  try {
    $app.save(record);
  } catch (err) {
    console.log("lead save failed:", err);
    return done(500, { ok: false, error: "store_failed" });
  }

  // Then alert, best-effort, with the email domain only.
  const ntfy = $os.getenv("NTFY_URL");
  if (ntfy) {
    try {
      $http.send({
        url: ntfy,
        method: "POST",
        body: `${kind} from @${email.split("@")[1]} on ${host}`,
        headers: { Authorization: `Bearer ${$os.getenv("NTFY_TOKEN")}`, Title: "New lead" },
        timeout: 5,
      });
    } catch (err) {
      console.log("ntfy alert failed:", err);
    }
  }

  return done(202, { ok: true });
});

// Retention: delete expired leads every night at 03:00.
cronAdd("leads-retention", "0 3 * * *", () => {
  const expired = $app.findRecordsByFilter("leads", "expires_at != '' && expires_at < @now", "", 1000, 0);
  for (const record of expired) $app.delete(record);
  if (expired.length) console.log(`retention: deleted ${expired.length} expired leads`);
});

Two PocketBase details worth knowing:

  • Each handler runs in its own context. Variables defined at the top of the file aren’t visible inside routerAdd; shared config is loaded with require(`${__hooks}/config.js`) inside the handler.
  • Retention isn’t automatic like a KV TTL. The expires_at field plus the nightly cronAdd job does the same thing. I tested it by running the job every minute against a record that had expired.

The static site

server {
  listen 80;
  root /usr/share/nginx/html;
  # A real 404 page with a 404 status (no "soft 404s").
  error_page 404 /404.html;
  location / { try_files $uri $uri/ $uri.html =404; }
  # Hashed build assets never change.
  location /_astro/ { expires 1y; add_header Cache-Control "public, immutable"; }
}

try_files … =404 plus error_page gives real 404s, the lesson from chapter 5.

Testing it

The same checks I ran, against your domain:

B=https://example.com
curl -s -o /dev/null -w "%{http_code}\n" $B/nope                 # 404
curl -s -o /dev/null -w "%{http_code}\n" $B/_/                   # 404: admin not public
curl -s -o /dev/null -w "%{http_code}\n" $B/api/collections/leads/records   # 404

curl -s -X POST $B/api/forms/submit -H 'Content-Type: application/json' \
  -d '{"kind":"enquiry","email":"[email protected]","page":"/pricing"}'      # {"ok":true}

curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" -X POST $B/api/forms/submit \
  -d 'kind=newsletter&[email protected]&consent_newsletter=on&page=/blog'   # 303 …/blog?form=sent

curl -s -X POST $B/api/forms/submit -H 'Content-Type: application/json' \
  -H 'Origin: https://evil.example' -d '{"kind":"enquiry","email":"[email protected]"}'  # bad_origin

What’s left to port

This chapter covers capture, storage, alerts and retention. The rest of the engine moves the same way:

  • Double opt-in. PocketBase hooks have $security.hs256(text, secret) and $security.equal(a, b) for signed links, and $app.newMailClient().send(new MailerMessage({…})) sends through the SMTP settings in the admin UI. Same design as chapter 3: a stateless signed token, GET shows a page, POST acts.
  • The suppression list. A suppressions collection keyed by the SHA-256 of the address ($security.sha256), checked before every send.
  • Sequences. The homelab engine can read from PocketBase instead of KV; it’s SQLite either way.
  • Backups. Copy pb_data/ (or use PocketBase’s built-in backups to S3-compatible storage, R2 included) every night, and test a restore.
  • Moving the data. Export the existing leads from the SQLite mirror and create them through PocketBase’s API as the admin, keeping receivedAt and the computed expires_at.

What you give up

Be honest about the trade:

  • Availability. If this server is down, forms fail. The edge version kept taking leads while my homelab was off. Use a small VPS rather than a home connection for this, and monitor it.
  • The edge. One location, no global cache, no DDoS absorption. Fine for most small businesses; not for a site that might get hammered.
  • Operations. OS updates, Docker updates, PocketBase updates, disk space, backups. Small, but yours.

What you gain: every byte on hardware you choose, one bill you understand, and no platform that can change its terms under you. The point of chapters 6 and 7 together is that this is a decision you can make at any time, not a rewrite you’re locked out of.

Next: lessons, as a checklist.