logo
Published on

DevBlog 1. Running Code and Adding Comments

Authors
  • avatar
    Name
    seren-wib
    Twitter
Contents

0. Introduction

I wanted this static site to do more than get read: a Playground that runs code, a visualizer that shows how a sort works, and comments on every post. I decided not to build a server to receive code or a database for comments.

In restaurant terms, this blog is a shop that sells only pre-made lunch boxes and has no kitchen. When a customer orders a dish, the shop cooks it on the spot, sends what it cannot cook to the shop next door, and borrows the neighbor's ledger as a guest book. The lunch-box shop is a static site, cooking in the shop is running in the browser (Web Worker, Pyodide), the shop next door is the Compiler Explorer API, and the neighbor's ledger is GitHub Discussions.

On Vercel I built runners for SQL, HTML, JavaScript, Python, C and C++ without a server, put a sort visualizer on top of them, and added a comment box with giscus.

System architecture diagram. An author opens a PR with mdx to GitHub main, GitHub Actions checks it and Vercel builds it with contentlayer2 and Next.js into static /kr and /en pages; the visitor's browser gets them through middleware, runs code with Pyodide, sql.js and Web Workers, and calls giscus (GitHub Discussions), Compiler Explorer, Umami and AdSense directly

1. Choosing where each language runs

The question shrinks to one: "where can this language run?"

LanguageRuns inWhy
SQLBrowser (sql.js, SQLite WASM)Reuses the one built for Database Systems chapter 3
JavaScriptBrowser (Web Worker)The browser's own language
HTMLBrowser (sandboxed iframe)The browser's own format
PythonBrowser (Pyodide)CPython compiled to WebAssembly. About 10 MB
C, C++External server (Compiler Explorer)A compiler in the browser is tens of MB, so a public API compiles and runs the code
  • The public Piston API now answers 401 without a key, so I dropped it. Compiler Explorer (godbolt.org) compiles and runs with one API call and sends Access-Control-Allow-Origin: *, so CORS does not block other sites
  • The trade-off: C/C++ code is sent to godbolt and there are rate limits. Fine for a practice blog
  • The language list lives in one place, data/playground.ts; the header menu, the card page, the practice-page URLs and the sitemap all read that array. generateStaticParams builds 6 languages × 2 locales = 12 pages at build time
  • The header dropdown uses CSS only, no JavaScript (group-hover, group-focus-within, so Tab opens it too). The pt-2 gap between link and list sits on the list side so hover does not break while the mouse moves down. The existing menu sits in an overflow-x-auto box that would clip the list, so Playground goes outside that box

2. The editor and the JavaScript Worker

  • Syntax highlighting (Syntax highlighting), line numbers, bracket matching and Tab indentation are needed, so CodeMirror 6 replaces a textarea. The highlight style lives in a Compartment and only that slot is swapped when dark mode changes, so the cursor and content stay
  • Prec.highest makes Ctrl/⌘+Enter run before the default keymap. godbolt errors carry line and column numbers, and passing them to setDiagnostics of @codemirror/lint draws a red underline on that line. Code and stdin are saved in localStorage
  • Calling eval in the page freezes the whole tab on while (true) {}. Each run creates a new Web Worker and worker.terminate() throws it away. console.log is overridden to send output with postMessage, and the code is wrapped in an AsyncFunction to allow top-level await
public/static/playground/js-worker.js
console.log = function () { send('out', arguments) }

const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
self.onmessage = (e) => {
  new AsyncFunction(e.data.code)().then(
    () => self.postMessage({ type: 'done' }),
    (err) => { self.postMessage({ type: 'err', text: errorText(err) }); self.postMessage({ type: 'done' }) }
  )
}
  • After 15 seconds the Worker is killed and a "time limit" line is printed. It is not killed the moment the body ends, to catch output printed later by setTimeout

3. HTML in a sandboxed iframe

  • <iframe srcdoc> with sandbox="allow-scripts allow-modals allow-forms allow-popups". allow-same-origin is left out on purpose, so the iframe gets an opaque origin and its scripts cannot touch the blog page or storage
  • A small script right after <head> sends console.* and errors with parent.postMessage. The page accepts messages only from that iframe. The preview redraws 0.6 seconds after typing stops
  • Bug: changing only srcdoc sometimes left the first view blank (the same HTML in a new iframe rendered fine). Changing the React key on every update to recreate the iframe made it disappear

4. Python with Pyodide

  • The five runtime files (about 12 MB) of the npm pyodide package (314.0.7, Python 3.14) are copied to public/static/pyodide/ and served from this site. To keep 12 MB out of git the copy is in .gitignore, and the predev and prebuild scripts copy it from node_modules. Vercel runs npm run build, so it happens there too
package.json
"predev": "node ./scripts/copy-pyodide.mjs",
"prebuild": "node ./scripts/copy-pyodide.mjs",
  • It runs inside a Worker so an infinite loop can be killed. Loading takes a few seconds, so the Worker is reused between runs with a fresh globals dict each time, so no variables leak. After Stop or the time limit kills it, the next run starts a new one. Opening the Python page starts loading right away
  • input(): the stdin box is handed over line by line before the run (setStdin). For packages like numpy, loadPackagesFromImports reads the imports and fetches only what is needed from jsDelivr

5. C and C++ through the Compiler Explorer API

components/playground/runners.ts
fetch(`https://godbolt.org/api/compiler/${compiler.id}/compile`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({
    source: code,
    options: {
      userArguments: '-O2 -Wall -std=c++20 -fdiagnostics-color=never',
      executeParameters: { stdin },
      compilerOptions: { executorRequest: true },
      filters: { execute: true },
    },
  }),
})
  • Compiler ids come from the /api/compilers/c list: cg152 (GCC 15.2) for C and g152 for C++. Without -fdiagnostics-color=never errors contain terminal color codes
  • The response fields used are buildResult (errors, warnings, line numbers), stdout/stderr, code, execTime and timedOut. godbolt kills an infinite loop after about 20 seconds with timedOut: true. Input is typed into the stdin box before the run, so it cannot be exchanged interactively

6. Keeping the CSP and surviving output floods

  • The CSP stays unchanged. Worker and Pyodide files come from 'self', WebAssembly compilation is allowed by the existing 'unsafe-eval', and godbolt and jsDelivr are fetch calls covered by the already open connect-src. srcdoc inherits the parent CSP, so inline scripts work and external ones are blocked, which is why the preview notice says external scripts are not loaded
  • while True: print(1) sends tens of thousands of lines per second, and updating React state per line freezes the page. Lines go into a buffer that is flushed once in requestAnimationFrame; past 2000 lines the rest is dropped with a one-line notice

7. Sort visualizer: letting the program keep a diary

The visualizer at the top of the heap sort post actually runs the C and Python implementations and animates bars sized by value while they sort, with a random input every time. It reuses the Playground runners above.

ApproachProblem
Rewrite the sort in JavaScript and draw itThe screen is not the C/Python result
Peek at the running program's memoryNo way to see the array from outside godbolt or Pyodide
Print what the program did, line by lineA few more printf lines, but screen = real run

I took the third. The program writes one line per compare or swap, and the page reads that output (Execution trace) and replays it from the start. The format works for any sort.

LineMeaning
INIT v0 v1 …Input array
PHASE namePhase start (shown in a caption)
CMP i jCompared a[i] and a[j]
SWAP i jSwapped a[i] and a[j]
SORTED ia[i] is in its final place
DONE v0 v1 …Result array
  • With size 16 the output is about 150 lines
  • The random input is made by the page and passed through stdin (values 5 to 99, size 8 to 32), not by srand inside the program. C rand() and Python random give different numbers even with the same seed, and the page wants to give both the same array. The input is in the request body, so every request differs, and the input array can be shown on screen
components/visualizer/SortVisualizer.tsx
const input = randomInput(size)            // 5 ~ 99, size 8 ~ 32
const stdin = `${size}\n${input.join(' ')}\n`
  • trace.ts reads the output line by line, applies each swap to its own copy of the array and stores the whole array at that moment as one frame. With at most 32 values and a few hundred steps, copying whole arrays is cheap, so the slider jumps to any step
  • Check: the array the page rebuilt must equal DONE and be ascending. A forgotten printf makes the picture disagree with the real array, and that is reported under the bars, as are out-of-range indices and a missing INIT or DONE
components/visualizer/trace.ts
} else if (cmd === 'CMP' || cmd === 'SWAP') {
  const [i, j] = nums
  if (cmd === 'SWAP') [values[i], values[j]] = [values[j], values[i]]
  push({ kind: cmd === 'CMP' ? 'cmp' : 'swap', i, j })
}

8. Playback and lazy loading

  • Playback is just index incremented by setTimeout (default 420 ms, 0.5× to 4×). Bar height is value / max × 100% with a transition. Compare is blue, swap is red, final place is black, the rest gray. Controls: play/pause, one step, slider, speed
  • The MDX component map is shared by every post, so importing the visualizer directly would ship CodeMirror (hundreds of KB) to posts without one. Only a small wrapper, SortVisualizerLazy, wrapped with next/dynamic, is registered, so the real code is lazy loaded only on posts that use it. A post needs one line, <SortVisualizer algorithm="heap-sort" />. Loading Pyodide starts the moment the Python tab is clicked, so someone only reading never downloads 10 MB
  • Checked: with the same input [42, 7, 93, 15, 61, 28, 77, 3, 50, 66], C (godbolt) and Python produced 75 lines of output with no differing line; two runs in a row gave different inputs; at 390 px width nothing scrolled horizontally
  • A new algorithm only needs its C and Python code and phase names in components/visualizer/algorithms.ts, as long as it follows the same output format. For merge sort, which copies values, I plan to add a SET i v line

9. Comments with giscus

One post = one discussion. The blog started from the tailwind-nextjs-starter-blog template, and the comment code was there from day one. Only the settings were missing.

OptionStored inProblem
DisqusDisqus serversAds and tracking scripts. The data is theirs
utterancesGitHub IssuesComments mix into the issue list. No replies (threads)
giscusGitHub DiscussionsVisitors need a GitHub account

Most readers are developers, so the GitHub login is no problem, and giscus borrows Discussions as storage without a server or database (Disqus, utterances).

  • The template's data/siteMetadata.js already had provider: 'giscus' with four environment-variable slots, and the CSP already allowed giscus.app. But the values were empty and Discussions was off, so nothing showed
data/siteMetadata.js
comments: {
  provider: 'giscus',
  giscusConfig: {
    repo: process.env.NEXT_PUBLIC_GISCUS_REPO,
    repositoryId: process.env.NEXT_PUBLIC_GISCUS_REPOSITORY_ID,
    category: process.env.NEXT_PUBLIC_GISCUS_CATEGORY,
    categoryId: process.env.NEXT_PUBLIC_GISCUS_CATEGORY_ID,
    mapping: 'pathname',
    // ...
  },
},
  • In the repo Settings → Features I turned on Discussions (default categories appear at once). The giscus app is installed on Only select repositories with just the blog repo; All would open private repos too
  • The IDs come from giscus.app or one GraphQL call with gh. id is the repo ID (R_...) and each category has a DIC_...
gh api graphql -f query='{
  repository(owner: "seren-wib", name: "vercel-blog") {
    id
    discussionCategories(first: 10) { nodes { name id } }
  }
}'
  • I first used Announcements as recommended (only admins and the app can open discussions), but the welcome notice and per-post comment discussions got mixed, so I moved to General. The cost is that visitors can open discussions too, which I accept at this scale. Changing the category means moving existing discussions as well: giscus looks only inside the configured category, so otherwise that post's comments vanish and an empty discussion is created (Change category or updateDiscussion)

10. Environment variables and loading

NameValue
NEXT_PUBLIC_GISCUS_REPOseren-wib/vercel-blog
NEXT_PUBLIC_GISCUS_REPOSITORY_IDR_...
NEXT_PUBLIC_GISCUS_CATEGORYGeneral
NEXT_PUBLIC_GISCUS_CATEGORY_IDDIC_...
  • All four reach the browser anyway, so they are not secrets and go in as plain. NEXT_PUBLIC_ values are baked in at build time, so saving the environment variables alone changes nothing and a Redeploy is required
  • The template loaded giscus only after a "Load Comments" click, but the pliny giscus component already makes a loading: "lazy" iframe that loads only when scrolled near. Removing the button and state and rendering directly keeps the first load the same. The "Discuss on Twitter" and "View on GitHub" links under posts are gone too. On a long post the floating bubble at the bottom right jumps to #comment
components/Comments.tsx
export default function Comments({ slug }: { slug: string }) {
  if (!siteMetadata.comments?.provider) {
    return null
  }
  return <CommentsComponent commentsConfig={siteMetadata.comments} slug={slug} />
}
  • With mapping: 'pathname' a discussion title is a path like kr/blog/side-projects/devblog/.... /kr/ and /en/ are different paths, so Korean and English posts get separate comments; I kept it because the readers differ (merging needs a specific mapping that passes a term without the prefix). Changing a slug breaks the link to existing comments, so the discussion title must be edited in Discussions too

11. Reflection

Even a serverless blog works once you decide separately where code runs and where comments live.