I run a small forum for the Polytoria game
community: wempos-forum.com. It has boards,
threads, polls, a chat lobby, DMs, profiles, two-factor sign-in and 41
interface languages. The whole thing is one Cloudflare Worker, one D1
database, and plain JavaScript modules in the browser. No React, no
bundler, no build step for the front end.
This post is about the decisions that made that work, the parts that bit
me, and some code you can steal. The project is free software
(AGPL-3.0-or-later), so all of it is in
browser βββΊ Worker (worker.mjs)
βββ /api/* JSON routes, one handler module per area
βββ /mcp a tool server for AI agents
βββ discovery /openapi.json, sitemap, markdown versions
βββ everything else β static files in public/, with a
per-page <head> injected on the way out
D1 (SQLite) βββ every route, through bound statements
The router is a list of handlers. Each one answers the paths it owns and
returns null for everything else, so the next handler gets a turn:
const API_HANDLERS = [handleAuthRoutes, handlePostRoutes, handleProfileRoutes,
/* β¦30 moreβ¦ */ handleBrandingRoutes, handleAnalyticsRoutes];
Adding a feature means adding one module and one entry. There's no
framework to learn, and every route is a plain function you can call
from a test.
The browser loads public/js/*.js exactly as written, as ES modules.
That sounded like a constraint at first. In practice it means:
public/js/router.js the browser uses, so a URL the
client can't route gets a real 404 from the server too. One list of
page routes, no drift.eval, script-src 'self'. There's nothing to whitelist because
there's nothing generated.
The cost is that I write a bit more DOM code by hand. The rule that keeps
it safe: user text goes in with textContent, never innerHTML, and a
test fails the build if a new HTML sink shows up.
Forums leak in boring ways. A post gets hidden by a moderator, but it
still shows in search. A member blocks someone, but that person's replies
still appear in a notification. A banned account's posts vanish from the
feed but not from the sitemap.
So there's exactly one module that decides "can this viewer see this
post?", covering hidden posts, active bans and block pairs in both
directions. Every route that returns post text or member names goes
through it. Then there's a test that seeds one of each forbidden thing
(a hidden post, a banned author, a blocked pair, a deleted post, a
staff-only record) and sweeps every route, the agent tool server and
the page heads, asserting none of that text ever comes back.
That sweep has paid for itself. In the last release it caught a subtle
one: the structured data on a thread page counted replies from someone the
viewer had blocked, while the feed (correctly) didn't. Same SQL, one
missing filter. Without the sweep, nobody would have noticed for months.
When someone pastes a thread link into Discord, it should show the
thread's title and first lines. When the thread is hidden, it must show
nothing about it, and it must not even reveal whether the thread
exists.
The Worker rewrites the HTML shell's <head> per request. The important
part is the order: the visibility check runs first, as an ordinary
member, even for staff, so a moderator's session can't leak a hidden post
into a cached preview:
const row = await env.FORUM_DB.prepare(POST_ROW_SQL).bind(id).first();
if (!row || !(await canViewPost(env, row, viewer))) return null; // β generic head
Hidden, banned, blocked, deleted and missing all fall back to the same
generic head with noindex, and a test asserts the bytes are identical.
The structured data for search engines goes in a
<script type="application/ld+json"> block. That's a trap, because a
post body containing </script> would close the tag early. The fix is to
escape after serializing:
export function jsonLdBlock(data) {
const text = JSON.stringify(data)
.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026")
.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
return `<script type="application/ld+json">${text}</script>`;
}
It's still valid JSON (\u003c is just < to a JSON parser), but an
HTML parser never sees a <. There's a test that posts
</script><script>alert(1)</script> and checks every block still parses
and nothing gets injected.
I wanted to know which pages people use, without tracking people. The
answer was to store counts, not visits:
CREATE TABLE page_view_counts (
day TEXT NOT NULL, route TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (day, route)
);
route is the router's page name: home, post, profile. It's
never the path, so no post id, username or search query ever lands in a
row. There's no IP, user agent, cookie or per-visit row. The decision to
count is one small function:
export function pageViewPlan(request, env, url, response) {
if (!analyticsEnabled(env) || !env.FORUM_DB) return null;
if (request.method.toUpperCase() !== "GET" || isPrefetch(request)) return null;
if (optedOut(request) || looksLikeBot(request)) return null; // DNT / Sec-GPC
if (!response || response.status !== 200) return null;
if (!(response.headers.get("Content-Type") || "").includes("text/html")) return null;
const route = routeForPath(url.pathname, url.search).name;
if (!route || route === "not-found") return null;
return { day: utcDay(), route, referrer: referrerHost(request, url, env) };
}
A few details I'm happy with:
reddit.com, never the full
URL), and only when it's someone else's site. The number of distinct
hosts per day is capped, so a flood of junk referrers can't bloat the
table.ctx.waitUntil after the
response is built, and any error becomes a log line, not a broken page.
The staff view is a plain table of daily totals, top page types and top
referring sites. That's enough to see whether a Reddit post worked, and
it holds nothing worth stealing.
D1 is SQLite, and mostly it's lovely. A few things cost me real time:
DROP, or worse, silently cascade-delete rows
in tables that reference it. For schema changes I now add a new column,
backfill it, and switch reads over, instead of rebuilding tables.prepare(...).bind(...), every LIMIT is a bound number, and list
sizes stay under D1's bound-parameter cap.
Every deploy stamps the commit hash into the HTML and into
/api/version:
wrangler deploy --keep-vars --var COMMIT_SHA:$(git rev-parse --short HEAD)
The browser compares its own build against /api/version and shows a
"new version available" banner when they differ, and the stamp doubles as
a cache-buster for scripts. It also caught a nasty problem: a git push can
trigger a hosted build that deploys without the stamp. So the rule is
that the stamped deploy always runs last, from a checkout at the pushed
commit, and I probe /api/version until it reports that commit.
The suite (about 1,200 tests) runs with Node's built-in test runner. Routes
run against an in-memory SQLite that behaves like D1, and front-end
modules run against a small fake DOM. No headless browser, so the whole
suite takes seconds and runs on every push. Fuzz tests (fast-check)
throw thousands of malformed inputs at sign-in, search and posting.
New features land red-first: the test commit goes in failing, then the
code that makes it pass. When a change touches visibility, I break the
fix on purpose to confirm the test notices. If removing the check doesn't
fail a test, the test is wrong.
The forum is at wempos-forum.com. If you play
Polytoria or build games, come say hi. The code, self-hosting guide and
security docs are on
GitHub. I'd love
feedback on any of the above.