{"slug": "i-built-a-forum-with-no-framework-on-cloudflare-workers", "title": "I built a forum with no framework on Cloudflare Workers", "summary": "A developer built a framework-free forum for the Polytoria game community, running as a single Cloudflare Worker with a D1 SQLite database and plain ES-module JavaScript in the browser, covering boards, threads, polls, chat, DMs, profiles, two-factor sign-in and 41 interface languages. The design routes all visibility decisions through one module and backs it with a test that seeds hidden posts, banned authors, blocked pairs and deleted records, then sweeps every route, the MCP agent tool server and page heads to confirm none of that text leaks. That sweep caught a real bug in the last release, where a thread page's structured data counted replies from a blocked user while the feed did not.", "body_md": "I run a small forum for the [Polytoria](https://polytoria.com) game\n\ncommunity: [wempos-forum.com](https://wempos-forum.com). It has boards,\n\nthreads, polls, a chat lobby, DMs, profiles, two-factor sign-in and 41\n\ninterface languages. The whole thing is one Cloudflare Worker, one D1\n\ndatabase, and plain JavaScript modules in the browser. No React, no\n\nbundler, no build step for the front end.\n\nThis post is about the decisions that made that work, the parts that bit\n\nme, and some code you can steal. The project is free software\n\n(AGPL-3.0-or-later), so all of it is in\n\n[the repo](https://github.com/Wempo-s-Silly-Projects/wempos-forum).\n\n```\nbrowser ──► Worker (worker.mjs)\n              ├── /api/*        JSON routes, one handler module per area\n              ├── /mcp          a tool server for AI agents\n              ├── discovery     /openapi.json, sitemap, markdown versions\n              └── everything else → static files in public/, with a\n                  per-page <head> injected on the way out\n            D1 (SQLite)  ◄── every route, through bound statements\n```\n\nThe router is a list of handlers. Each one answers the paths it owns and\n\nreturns `null` for everything else, so the next handler gets a turn:\n\n``` js\nconst API_HANDLERS = [handleAuthRoutes, handlePostRoutes, handleProfileRoutes,\n  /* …30 more… */ handleBrandingRoutes, handleAnalyticsRoutes];\n```\n\nAdding a feature means adding one module and one entry. There's no\n\nframework to learn, and every route is a plain function you can call\n\nfrom a test.\n\nThe browser loads `public/js/*.js` exactly as written, as ES modules.\n\nThat sounded like a constraint at first. In practice it means:\n\n`public/js/router.js` the browser uses, so a URL the\nclient can't route gets a real `404` from the server too. One list of\npage routes, no drift.`eval`, `script-src 'self'`. There's nothing to whitelist because\nthere's nothing generated.\nThe cost is that I write a bit more DOM code by hand. The rule that keeps\n\nit safe: user text goes in with `textContent`, never `innerHTML`, and a\n\ntest fails the build if a new HTML sink shows up.\n\nForums leak in boring ways. A post gets hidden by a moderator, but it\n\nstill shows in search. A member blocks someone, but that person's replies\n\nstill appear in a notification. A banned account's posts vanish from the\n\nfeed but not from the sitemap.\n\nSo there's exactly one module that decides \"can this viewer see this\n\npost?\", covering hidden posts, active bans and block pairs in both\n\ndirections. Every route that returns post text or member names goes\n\nthrough it. Then there's a test that seeds one of each forbidden thing\n\n(a hidden post, a banned author, a blocked pair, a deleted post, a\n\nstaff-only record) and sweeps **every** route, the agent tool server and\n\nthe page heads, asserting none of that text ever comes back.\n\nThat sweep has paid for itself. In the last release it caught a subtle\n\none: the structured data on a thread page counted replies from someone the\n\nviewer had blocked, while the feed (correctly) didn't. Same SQL, one\n\nmissing filter. Without the sweep, nobody would have noticed for months.\n\nWhen someone pastes a thread link into Discord, it should show the\n\nthread's title and first lines. When the thread is hidden, it must show\n\n*nothing* about it, and it must not even reveal whether the thread\n\nexists.\n\nThe Worker rewrites the HTML shell's `<head>` per request. The important\n\npart is the order: the visibility check runs first, as an ordinary\n\nmember, even for staff, so a moderator's session can't leak a hidden post\n\ninto a cached preview:\n\n``` js\nconst row = await env.FORUM_DB.prepare(POST_ROW_SQL).bind(id).first();\nif (!row || !(await canViewPost(env, row, viewer))) return null; // → generic head\n```\n\nHidden, banned, blocked, deleted and missing all fall back to the same\n\ngeneric head with `noindex`, and a test asserts the bytes are identical.\n\nThe structured data for search engines goes in a\n\n`<script type=\"application/ld+json\">` block. That's a trap, because a\n\npost body containing `</script>` would close the tag early. The fix is to\n\nescape after serializing:\n\n``` js\nexport function jsonLdBlock(data) {\n  const text = JSON.stringify(data)\n    .replace(/</g, \"\\\\u003c\").replace(/>/g, \"\\\\u003e\").replace(/&/g, \"\\\\u0026\")\n    .replace(/\\u2028/g, \"\\\\u2028\").replace(/\\u2029/g, \"\\\\u2029\");\n  return `<script type=\"application/ld+json\">${text}</script>`;\n}\n```\n\nIt's still valid JSON (`\\u003c` is just `<` to a JSON parser), but an\n\nHTML parser never sees a `<`. There's a test that posts\n\n`</script><script>alert(1)</script>` and checks every block still parses\n\nand nothing gets injected.\n\nI wanted to know which pages people use, without tracking people. The\n\nanswer was to store **counts, not visits**:\n\n```\nCREATE TABLE page_view_counts (\n  day TEXT NOT NULL, route TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0,\n  PRIMARY KEY (day, route)\n);\n```\n\n`route` is the router's page *name*: `home`, `post`, `profile`. It's\n\nnever the path, so no post id, username or search query ever lands in a\n\nrow. There's no IP, user agent, cookie or per-visit row. The decision to\n\ncount is one small function:\n\n```\nexport function pageViewPlan(request, env, url, response) {\n  if (!analyticsEnabled(env) || !env.FORUM_DB) return null;\n  if (request.method.toUpperCase() !== \"GET\" || isPrefetch(request)) return null;\n  if (optedOut(request) || looksLikeBot(request)) return null; // DNT / Sec-GPC\n  if (!response || response.status !== 200) return null;\n  if (!(response.headers.get(\"Content-Type\") || \"\").includes(\"text/html\")) return null;\n  const route = routeForPath(url.pathname, url.search).name;\n  if (!route || route === \"not-found\") return null;\n  return { day: utcDay(), route, referrer: referrerHost(request, url, env) };\n}\n```\n\nA few details I'm happy with:\n\n`reddit.com`, never the full\nURL), and only when it's someone else's site. The number of distinct\nhosts per day is capped, so a flood of junk referrers can't bloat the\ntable.`ctx.waitUntil` after the\nresponse is built, and any error becomes a log line, not a broken page.\nThe staff view is a plain table of daily totals, top page types and top\n\nreferring sites. That's enough to see whether a Reddit post worked, and\n\nit holds nothing worth stealing.\n\nD1 is SQLite, and mostly it's lovely. A few things cost me real time:\n\n`DROP`, or worse, silently cascade-delete rows\nin tables that reference it. For schema changes I now add a new column,\nbackfill it, and switch reads over, instead of rebuilding tables.`prepare(...).bind(...)`, every `LIMIT` is a bound number, and list\nsizes stay under D1's bound-parameter cap.\nEvery deploy stamps the commit hash into the HTML and into\n\n`/api/version`:\n\n``` js\nwrangler deploy --keep-vars --var COMMIT_SHA:$(git rev-parse --short HEAD)\n```\n\nThe browser compares its own build against `/api/version` and shows a\n\n\"new version available\" banner when they differ, and the stamp doubles as\n\na cache-buster for scripts. It also caught a nasty problem: a git push can\n\ntrigger a hosted build that deploys *without* the stamp. So the rule is\n\nthat the stamped deploy always runs last, from a checkout at the pushed\n\ncommit, and I probe `/api/version` until it reports that commit.\n\nThe suite (about 1,200 tests) runs with Node's built-in test runner. Routes\n\nrun against an in-memory SQLite that behaves like D1, and front-end\n\nmodules run against a small fake DOM. No headless browser, so the whole\n\nsuite takes seconds and runs on every push. Fuzz tests (fast-check)\n\nthrow thousands of malformed inputs at sign-in, search and posting.\n\nNew features land red-first: the test commit goes in failing, then the\n\ncode that makes it pass. When a change touches visibility, I break the\n\nfix on purpose to confirm the test notices. If removing the check doesn't\n\nfail a test, the test is wrong.\n\nThe forum is at [wempos-forum.com](https://wempos-forum.com). If you play\n\nPolytoria or build games, come say hi. The code, self-hosting guide and\n\nsecurity docs are on\n\n[GitHub](https://github.com/Wempo-s-Silly-Projects/wempos-forum). I'd love\n\nfeedback on any of the above.", "url": "https://wpnews.pro/news/i-built-a-forum-with-no-framework-on-cloudflare-workers", "canonical_source": "https://dev.to/itswempo/i-built-a-forum-with-no-framework-on-cloudflare-workers-o8d", "published_at": "2026-11-22 04:05:16+00:00", "updated_at": "2026-11-22 04:12:22.239158+00:00", "lang": "en", "topics": ["developer-tools", "ai-agents", "agent-protocols", "structured-data"], "entities": ["Cloudflare Workers", "Cloudflare D1", "Polytoria", "wempos-forum.com", "Wempo's Silly Projects"], "also_reported_by": [], "takeaway": "Routing every read through a single canViewPost check and sweeping all routes, the MCP tool server and page heads with seeded hidden, banned, blocked and deleted records caught a structured-data leak that a feed-only test would have missed.", "recommendation": {"advice": "Centralize visibility checks in one module and run a seeded sweep across every route, agent tool endpoint and page head to catch leaks like blocked-user replies appearing in structured data.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/i-built-a-forum-with-no-framework-on-cloudflare-workers", "markdown": "https://wpnews.pro/news/i-built-a-forum-with-no-framework-on-cloudflare-workers.md", "text": "https://wpnews.pro/news/i-built-a-forum-with-no-framework-on-cloudflare-workers.txt", "jsonld": "https://wpnews.pro/news/i-built-a-forum-with-no-framework-on-cloudflare-workers.jsonld"}}