- Published on
DevBlog 1. Running Code and Adding Comments
- Authors

- Name
- seren-wib
Contents
- 0. Introduction
- 1. Choosing where each language runs
- 2. The editor and the JavaScript Worker
- 3. HTML in a sandboxed iframe
- 4. Python with Pyodide
- 5. C and C++ through the Compiler Explorer API
- 6. Keeping the CSP and surviving output floods
- 7. Sort visualizer: letting the program keep a diary
- 8. Playback and lazy loading
- 9. Comments with giscus
- 10. Environment variables and loading
- 11. Reflection
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.
1. Choosing where each language runs
The question shrinks to one: "where can this language run?"
| Language | Runs in | Why |
|---|---|---|
| SQL | Browser (sql.js, SQLite WASM) | Reuses the one built for Database Systems chapter 3 |
| JavaScript | Browser (Web Worker) | The browser's own language |
| HTML | Browser (sandboxed iframe) | The browser's own format |
| Python | Browser (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
401without a key, so I dropped it. Compiler Explorer (godbolt.org) compiles and runs with one API call and sendsAccess-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.generateStaticParamsbuilds 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). Thept-2gap between link and list sits on the list side so hover does not break while the mouse moves down. The existing menu sits in anoverflow-x-autobox 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
Compartmentand only that slot is swapped when dark mode changes, so the cursor and content stay Prec.highestmakes Ctrl/⌘+Enter run before the default keymap. godbolt errors carry line and column numbers, and passing them tosetDiagnosticsof@codemirror/lintdraws 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 andworker.terminate()throws it away.console.logis overridden to send output with postMessage, and the code is wrapped in anAsyncFunctionto allow top-levelawait
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>withsandbox="allow-scripts allow-modals allow-forms allow-popups".allow-same-originis 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>sendsconsole.*and errors withparent.postMessage. The page accepts messages only from that iframe. The preview redraws 0.6 seconds after typing stops - Bug: changing only
srcdocsometimes left the first view blank (the same HTML in a new iframe rendered fine). Changing the Reactkeyon every update to recreate the iframe made it disappear
4. Python with Pyodide
- The five runtime files (about 12 MB) of the npm
pyodidepackage (314.0.7, Python 3.14) are copied topublic/static/pyodide/and served from this site. To keep 12 MB out of git the copy is in.gitignore, and thepredevandprebuildscripts copy it fromnode_modules. Vercel runsnpm run build, so it happens there too
"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,loadPackagesFromImportsreads the imports and fetches only what is needed from jsDelivr
5. C and C++ through the Compiler Explorer API
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/clist:cg152(GCC 15.2) for C andg152for C++. Without-fdiagnostics-color=nevererrors contain terminal color codes - The response fields used are
buildResult(errors, warnings, line numbers),stdout/stderr,code,execTimeandtimedOut. godbolt kills an infinite loop after about 20 seconds withtimedOut: 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 arefetchcalls covered by the already openconnect-src.srcdocinherits 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.
| Approach | Problem |
|---|---|
| Rewrite the sort in JavaScript and draw it | The screen is not the C/Python result |
| Peek at the running program's memory | No way to see the array from outside godbolt or Pyodide |
| Print what the program did, line by line | A 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.
| Line | Meaning |
|---|---|
INIT v0 v1 … | Input array |
PHASE name | Phase start (shown in a caption) |
CMP i j | Compared a[i] and a[j] |
SWAP i j | Swapped a[i] and a[j] |
SORTED i | a[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
srandinside the program. Crand()and Pythonrandomgive 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
const input = randomInput(size) // 5 ~ 99, size 8 ~ 32
const stdin = `${size}\n${input.join(' ')}\n`
trace.tsreads 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
DONEand be ascending. A forgottenprintfmakes the picture disagree with the real array, and that is reported under the bars, as are out-of-range indices and a missingINITorDONE
} 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
indexincremented by setTimeout (default 420 ms, 0.5× to 4×). Bar height isvalue / max × 100%with atransition. 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 aSET i vline
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.
| Option | Stored in | Problem |
|---|---|---|
| Disqus | Disqus servers | Ads and tracking scripts. The data is theirs |
| utterances | GitHub Issues | Comments mix into the issue list. No replies (threads) |
| giscus | GitHub Discussions | Visitors 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.jsalready hadprovider: 'giscus'with four environment-variable slots, and the CSP already allowedgiscus.app. But the values were empty and Discussions was off, so nothing showed
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.
idis the repo ID (R_...) and each category has aDIC_...
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
| Name | Value |
|---|---|
NEXT_PUBLIC_GISCUS_REPO | seren-wib/vercel-blog |
NEXT_PUBLIC_GISCUS_REPOSITORY_ID | R_... |
NEXT_PUBLIC_GISCUS_CATEGORY | General |
NEXT_PUBLIC_GISCUS_CATEGORY_ID | DIC_... |
- 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
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 likekr/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 aspecificmapping that passes atermwithout 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.