<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[All about OSS, software, productivity]]></title><description><![CDATA[All about OSS, software, productivity. Sharing my work in software development, best practices, farming, experiences]]></description><link>https://ashwin31.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/69a424aca7428b958daf4819/311e14f5-735d-4b7f-9ee2-61e9ab62b082.png</url><title>All about OSS, software, productivity</title><link>https://ashwin31.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 20:17:48 GMT</lastBuildDate><atom:link href="https://ashwin31.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Runnable code examples in MkDocs and Material for MkDocs, in 46 languages]]></title><description><![CDATA[Add one word to an MkDocs code block and readers can edit and run it in the page, in Python, C++, Go, SQL and 46 languages. Free plugin.]]></description><link>https://ashwin31.hashnode.dev/runnable-code-examples-in-mkdocs-and-material-for-mkdocs-in-46-languages</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/runnable-code-examples-in-mkdocs-and-material-for-mkdocs-in-46-languages</guid><category><![CDATA[mkdocs]]></category><category><![CDATA[Python]]></category><category><![CDATA[documentation]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Sun, 15 Nov 2026 08:44:20 GMT</pubDate><content:encoded><![CDATA[<p>If you write docs with MkDocs, you've probably wanted readers to try an example instead of only reading it. The options I found all had a catch:</p>
<ul>
<li><strong>markdown-exec</strong> runs code when the site is built and puts the output in the page. Great for output that never changes, but readers can't edit the code and run it again.</li>
<li><strong>Python in the browser</strong> (mkdocs-pyscript, pyodide-mkdocs-theme, Pyodide blocks) lets readers run code, but only Python, and the browser downloads a Python runtime first.</li>
</ul>
<p>So I built <a href="https://github.com/onlinecompiler-io/mkdocs-onlinecompiler">mkdocs-onlinecompiler</a>. You add one word to an ordinary code block, and readers get an editor with a Run button in the page, in Python, C++, Java, Go, Rust, SQL or any of 46 languages.</p>
<p><img src="https://raw.githubusercontent.com/onlinecompiler-io/mkdocs-onlinecompiler/main/.github/screenshot.png" alt="A Material for MkDocs page with a runnable Python example and its output after Run" /></p>
<p>The code runs on <a href="https://onlinecompiler.io">OnlineCompiler.io</a> (I build it), in a fresh sandbox for each run with no network access. Your site stays static: GitHub Pages, Read the Docs or any static host works, and nothing runs on it.</p>
<h2>Install it</h2>
<pre><code class="language-bash">pip install mkdocs-onlinecompiler
</code></pre>
<p>Add it to <code>mkdocs.yml</code> with a widget key:</p>
<pre><code class="language-yaml">plugins:
  - search
  - onlinecompiler:
      key: YOUR_WIDGET_KEY
</code></pre>
<p>Keep <code>search</code> in the list if your site has search: listing <code>plugins</code> replaces MkDocs' defaults. Also add the package to the requirements file your docs build installs from.</p>
<p>The widget key is free, from the Widgets page of the OnlineCompiler.io dashboard. It's made to sit in public pages: it can run code in the widget but can't call the REST API. Set its allowed domain to your docs domain, and make a second key for <code>mkdocs serve</code> on <code>localhost</code>. To keep it out of the file, read it from the environment:</p>
<pre><code class="language-yaml">plugins:
  - search
  - onlinecompiler:
      key: !ENV [ONLINECOMPILER_WIDGET_KEY, ""]
</code></pre>
<h2>Write <code>runnable</code></h2>
<p>Add <code>runnable</code> after the language of any fenced code block:</p>
<pre><code class="language-markdown">```python runnable
for n in range(1, 4):
    print(n, "squared is", n * n)
```
</code></pre>
<p>After Run:</p>
<pre><code class="language-text">1 squared is 1
2 squared is 4
3 squared is 9
</code></pre>
<p>Code blocks without the word stay exactly as they are. The code comes through as written, <code>&lt;</code>, <code>&amp;</code> and quotes included:</p>
<pre><code class="language-markdown">```cpp runnable
#include &lt;iostream&gt;

int main() {
    std::cout &lt;&lt; "a &amp; b " &lt;&lt; (1 &lt; 2) &lt;&lt; "\n";
}
```
</code></pre>
<p>That printed <code>a &amp; b 1</code>.</p>
<p>The block's language picks the compiler (<code>python</code> is Python 3.14, <code>cpp</code> is G++ 15, <code>js</code> is Node.js 24, <code>sql</code> is SQLite), and <code>lang=</code> names another one when you need it. The attribute style works too, and so do your other options:</p>
<pre><code class="language-markdown">```python title="frame.py" runnable lang=python-3.14-pandas2
import pandas as pd
print(pd.__version__)
```

``` {.py .runnable}
print("attribute style")
```
</code></pre>
<h2>Inside admonitions, content tabs and snippets</h2>
<p>This is where Material sites put most of their examples, so it had to work there. With <code>pymdownx.superfences</code> (which Material sites usually have on), runnable blocks work inside admonitions and content tabs:</p>
<pre><code class="language-markdown">!!! tip "In an admonition"

    ```rust runnable
    fn main() {
        println!("hi from Rust");
    }
    ```

=== "Go"

    ```go runnable
    package main

    import "fmt"

    func main() { fmt.Println("hi from Go") }
    ```

=== "Plain"

    ```python
    print("plain in a tab")
    ```
</code></pre>
<p>The Rust runner printed <code>hi from Rust</code>, the Go one <code>hi from Go</code>, and the last tab stayed a plain code block. Blocks pulled in with <code>pymdownx.snippets</code> (<code>--8&lt;--</code>) work too.</p>
<h2>How it works</h2>
<p>Three details, if you want to know what the plugin does to your build.</p>
<p><strong>It's a Markdown preprocessor, placed carefully.</strong> The plugin registers a Python-Markdown preprocessor at priority 28. That's after snippets (32) have been pulled in and whitespace normalised (30), and before fenced code (25) sees anything. It finds the runnable blocks, including ones nested in admonitions and tabs, and stashes the widget's markup in their place. So no other extension can reformat the code, and a page that documents the syntax itself (a runnable block inside a four-backtick block) is left alone.</p>
<p><strong>The code is in the HTML.</strong> Each runner is a <code>&lt;div&gt;</code> with the code in a <code>&lt;pre&gt;</code>. Search engines and MkDocs' own search index your examples, and readers see the code before the editor loads.</p>
<p><strong>The script loads only on pages with runners.</strong> The plugin appends the widget script to the content of those pages only. Material's instant navigation runs scripts in the content it swaps in, so runners start as readers move between pages without a reload. Runners follow Material's palette toggle (and MkDocs' own theme's dark mode) as the reader switches it.</p>
<p>Mistakes show up in the build: a runnable block in a language the service doesn't run stays a normal code block, and MkDocs prints a warning with the page and the language. With <code>mkdocs build --strict</code>, that stops the build, which is what you want in CI.</p>
<h2>What it costs</h2>
<p>The plugin is free and MIT licensed. Each press of Run is one run on your OnlineCompiler.io account, and the free plan has 100,000 runs a month with no credit card. You can give the widget key its own monthly limit to cap what a public page can use.</p>
<h2>Links</h2>
<ul>
<li>The full guide, with options and troubleshooting: <a href="https://onlinecompiler.io/guides/add-runnable-code-examples-to-mkdocs">https://onlinecompiler.io/guides/add-runnable-code-examples-to-mkdocs</a></li>
<li>PyPI: <a href="https://pypi.org/project/mkdocs-onlinecompiler/">https://pypi.org/project/mkdocs-onlinecompiler/</a></li>
<li>Source: <a href="https://github.com/onlinecompiler-io/mkdocs-onlinecompiler">https://github.com/onlinecompiler-io/mkdocs-onlinecompiler</a></li>
</ul>
<p>If you use Docusaurus, there's a plugin for that too: <a href="https://github.com/onlinecompiler-io/docusaurus-plugin-onlinecompiler">docusaurus-plugin-onlinecompiler</a>. And if your docs run on something else, tell me which. We build integrations for other platforms free of charge.</p>
]]></content:encoded></item><item><title><![CDATA[How to auto-grade SQL exercises against a real SQLite database]]></title><description><![CDATA[Grade students' SQL queries by running each one on the same SQLite database and comparing rows: a 40-line Python grader and five traps to avoid.]]></description><link>https://ashwin31.hashnode.dev/how-to-auto-grade-sql-exercises-against-a-real-sqlite-database</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/how-to-auto-grade-sql-exercises-against-a-real-sqlite-database</guid><category><![CDATA[SQL]]></category><category><![CDATA[SQLite]]></category><category><![CDATA[education]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Sat, 14 Nov 2026 17:06:39 GMT</pubDate><content:encoded><![CDATA[<p>If you teach SQL, you've probably tried grading by comparing a student's query with your own. It doesn't work, because two correct queries rarely look alike. All three of these answer the same question, and all three pass the grader in this post:</p>
<pre><code class="language-sql">SELECT member, SUM(days) FROM loans GROUP BY member HAVING SUM(days) &gt;= CAST(readfile('input') AS INTEGER);
</code></pre>
<pre><code class="language-sql">SELECT member, total FROM (SELECT member, SUM(days) AS total FROM loans GROUP BY member)
WHERE total &gt;= CAST(readfile('input') AS INTEGER);
</code></pre>
<pre><code class="language-sql">WITH totals AS (SELECT member, SUM(days) AS total FROM loans GROUP BY member)
SELECT * FROM totals WHERE total &gt;= 0 + readfile('input') ORDER BY total DESC;
</code></pre>
<p>What does work is running each query against the same database and comparing the rows it returns. This post builds that grader in about 40 lines of Python. It also covers the traps I hit while testing it: a wrong query that passed my first tests, row order, students who hard-code the answer, and a student who runs <code>DELETE FROM loans</code>.</p>
<h2>The exercise</h2>
<p>A small library database: which member borrowed which book, and for how many days.</p>
<table>
<thead>
<tr>
<th>member</th>
<th>book</th>
<th>days</th>
</tr>
</thead>
<tbody><tr>
<td>ada</td>
<td>Dune</td>
<td>12</td>
</tr>
<tr>
<td>ada</td>
<td>Emma</td>
<td>8</td>
</tr>
<tr>
<td>bob</td>
<td>Dune</td>
<td>20</td>
</tr>
<tr>
<td>cy</td>
<td>Emma</td>
<td>5</td>
</tr>
<tr>
<td>ada</td>
<td>Ulysses</td>
<td>15</td>
</tr>
<tr>
<td>bob</td>
<td>Ulysses</td>
<td>3</td>
</tr>
</tbody></table>
<p><strong>The question:</strong> print each member whose loans add up to at least N days, with that total.</p>
<p>N is the test's input, so one question can check several cases. Each test gives a different N and the rows it expects: N = 30 expects only <code>ada|35</code>, N = 20 expects <code>ada|35</code> and <code>bob|23</code>, and N = 100 expects nothing.</p>
<p>Build the database with the <code>sqlite3</code> command-line tool from a script:</p>
<pre><code class="language-sql">-- library.sql
CREATE TABLE loans (member TEXT, book TEXT, days INTEGER);
INSERT INTO loans VALUES
  ('ada', 'Dune', 12),
  ('ada', 'Emma', 8),
  ('bob', 'Dune', 20),
  ('cy', 'Emma', 5),
  ('ada', 'Ulysses', 15),
  ('bob', 'Ulysses', 3);
</code></pre>
<pre><code class="language-bash">sqlite3 library.db &lt; library.sql
</code></pre>
<h2>The grader</h2>
<p>Each query has to run somewhere safe, because it's code a student wrote. I send it to a code execution API that runs it in a sandbox with no network access. That's <a href="https://onlinecompiler.io">OnlineCompiler.io</a>'s run-tests endpoint, which I build. Its <code>sqlite-3</code> compiler runs the SQLite shell, so the program is the SQL itself, and the student writes only a query.</p>
<p>One request carries everything: the query, the database file, the tests and how to compare. The answer comes back with a verdict for each test.</p>
<pre><code class="language-python"># grade.py: grade one student's query. Run it in the folder that holds library.db.
import base64
import os
import sys
from pathlib import Path

import requests

query = Path(sys.argv[1]).read_text()  # the student's answer, such as answer.sql

response = requests.post(
    "https://api.onlinecompiler.io/api/run-tests/",
    headers={"Authorization": os.environ["ONLINECOMPILER_API_KEY"]},
    json={
        "compiler": "sqlite-3",
        # Open the database read-only on the line before the student's query.
        "code": ".open --readonly library.db\n" + query,
        "files": [
            {
                "name": "library.db",
                "content": base64.b64encode(Path("library.db").read_bytes()).decode(),
                "encoding": "base64",
            }
        ],
        "checker": "rows",  # same rows in any order
        "tests": [
            {"input": "30\n", "expected_output": "ada|35\n"},
            {"input": "20\n", "expected_output": "bob|23\nada|35\n"},
            {"input": "23\n", "expected_output": "bob|23\nada|35\n"},  # exactly on bob's total
            {"input": "100\n", "expected_output": ""},
        ],
    },
    timeout=60,
)
if not response.ok:
    sys.exit(f"HTTP {response.status_code}: {response.text}")
result = response.json()
print(result["verdict"], result["passed"], "of", result["total"])
for test in result["tests"]:
    first_error_line = (test.get("error") or "").split("\n")[0]
    print(" ", test["verdict"], repr(test.get("output", "")), first_error_line)
</code></pre>
<p>How each part works:</p>
<ul>
<li><code>.open --readonly library.db</code> is a SQLite shell command. Your grader puts it in front of the query, so the student never sees it.</li>
<li><strong>The database travels with the request</strong> as base64, since it's a binary file in a JSON body, and every test reads it.</li>
<li><code>readfile('input')</code> is how the query reads the test's input in SQLite. The sandbox saves each test's input as a file named <code>input</code> beside the database.</li>
<li><strong>The SQLite shell prints rows as</strong> <code>member|total</code>, one per line, and that's what the tests expect.</li>
</ul>
<p>Get a free key at <a href="https://api.onlinecompiler.io/compilers/api-keys/">onlinecompiler.io</a>, then:</p>
<pre><code class="language-bash">pip install requests
export ONLINECOMPILER_API_KEY=your_api_key
python grade.py answer.sql
</code></pre>
<p>With the first query from the top of the post in <code>answer.sql</code>:</p>
<pre><code class="language-text">accepted 4 of 4
  accepted 'ada|35\n'
  accepted 'ada|35\nbob|23\n'
  accepted 'ada|35\nbob|23\n'
  accepted ''
</code></pre>
<p>The other two correct queries give the same four <code>accepted</code> lines. Look at the second and third tests: they expect <code>bob|23</code> first, the query printed <code>ada|35</code> first, and they still pass. That's the checker, next.</p>
<h2>Trap 1: row order</h2>
<p>A query without <code>ORDER BY</code> may return its rows in any order, and a student who writes the query differently shouldn't lose marks for it. That's what <code>"checker": "rows"</code> is for. It compares the lines as an unordered set, so <code>ada|35</code> then <code>bob|23</code> matches <code>bob|23</code> then <code>ada|35</code>. Duplicates still count: a row printed twice must be expected twice. Numbers match within a small tolerance, so <code>35</code> and <code>35.0</code> are the same.</p>
<p>If the question <em>is</em> about order ("sort by total, highest first"), use <code>"checker": "exact"</code> instead, which compares the output byte for byte.</p>
<h2>Trap 2: a wrong query passed my first tests</h2>
<p>My first version had only the tests for 30, 20 and 100. Then I tried a query with <code>&gt;</code> where it should say <code>&gt;=</code>:</p>
<pre><code class="language-sql">SELECT member, SUM(days) FROM loans GROUP BY member HAVING SUM(days) &gt; CAST(readfile('input') AS INTEGER);
</code></pre>
<p>It passed all three. No test had N equal to a member's total, so <code>&gt;</code> and <code>&gt;=</code> always gave the same rows. That's why the grader above has a fourth test with N = 23, exactly bob's total. Now the same query gets:</p>
<pre><code class="language-text">wrong_answer 3 of 4
  accepted 'ada|35\n'
  accepted 'ada|35\nbob|23\n'
  wrong_answer 'ada|35\n'
  accepted ''
</code></pre>
<p>The lesson applies to any autograder: write at least one test on each boundary the question has. Your reference query passing every test proves the tests agree with your query. It doesn't prove they would catch a wrong one, so try a few wrong queries yourself before giving the exercise to students.</p>
<h2>Trap 3: the query that forgot the filter</h2>
<pre><code class="language-sql">SELECT member, SUM(days) FROM loans GROUP BY member;
</code></pre>
<pre><code class="language-text">wrong_answer 0 of 4
  wrong_answer 'ada|35\nbob|23\ncy|5\n'
  wrong_answer 'ada|35\nbob|23\ncy|5\n'
  wrong_answer 'ada|35\nbob|23\ncy|5\n'
  wrong_answer 'ada|35\nbob|23\ncy|5\n'
</code></pre>
<p>Every test shows what the query printed, so you can show it to the student next to what was expected.</p>
<h2>Trap 4: hard-coding the answer</h2>
<p>Students who can see a sample test sometimes print its answer:</p>
<pre><code class="language-sql">SELECT 'ada', 35;
</code></pre>
<pre><code class="language-text">wrong_answer 1 of 4
  accepted 'ada|35\n'
  wrong_answer 'ada|35\n'
  wrong_answer 'ada|35\n'
  wrong_answer 'ada|35\n'
</code></pre>
<p>It passes the one test whose answer it copied and fails the others. This is where hidden tests come in: show students one sample and grade on several they never see. In run-tests, mark a test <code>"hidden": true</code> and its result carries only the verdict, never its input or output:</p>
<pre><code class="language-json">{"verdict": "wrong_answer", "hidden": true}
</code></pre>
<p>That makes the whole result safe to pass straight to a student.</p>
<h2>Trap 5: syntax errors and <code>DELETE FROM loans</code></h2>
<p>A typo comes back as SQLite's own message, which is the clearest thing to show a student:</p>
<pre><code class="language-text">runtime_error 0 of 4
  runtime_error '' Parse error near line 2: near "SELEC": syntax error
  runtime_error '' Parse error near line 2: near "SELEC": syntax error
  runtime_error '' Parse error near line 2: near "SELEC": syntax error
  runtime_error '' Parse error near line 2: near "SELEC": syntax error
</code></pre>
<p>It says line 2 because the grader's <code>.open</code> line is line 1.</p>
<p>Then there's the student who tries to change the data:</p>
<pre><code class="language-sql">DELETE FROM loans;
SELECT member, SUM(days) FROM loans GROUP BY member HAVING SUM(days) &gt;= CAST(readfile('input') AS INTEGER);
</code></pre>
<pre><code class="language-text">runtime_error 0 of 4
  runtime_error '' Runtime error near line 2: attempt to write a readonly database (8)
  runtime_error '' Runtime error near line 2: attempt to write a readonly database (8)
  runtime_error '' Runtime error near line 2: attempt to write a readonly database (8)
  runtime_error '' Runtime error near line 2: attempt to write a readonly database (8)
</code></pre>
<p>Because the database is opened read-only, <code>DELETE</code>, <code>INSERT</code>, <code>UPDATE</code> and <code>DROP</code> stop with an error, and the file stays exactly as you sent it. A query can still create a temporary table, which is gone when the run ends.</p>
<p>One thing read-only doesn't do is hide the data. A query can read every table and print it, so keep the expected answers out of the database and only in the tests.</p>
<h2>Partial credit</h2>
<p>The default scoring is all or nothing: the score is 100 only if every test passes. For coursework, <code>"scoring": "percent"</code> gives the share of tests passed, and it runs every test even after one fails. The <code>&gt;</code> query above, which fails one test of four, scores <code>75.0</code> with it.</p>
<h2>CSV instead of a database</h2>
<p>If your exercise starts from a CSV file, use DuckDB, which reads CSV directly, so there's no database to build. Send the CSV as a file, set <code>"compiler": "duckdb-1.5"</code>, and the student queries it with <code>read_csv</code>. DuckDB has no <code>readfile</code>, so the test's input is read with <code>read_text</code>:</p>
<pre><code class="language-sql">SELECT member, sum(days) FROM read_csv('loans.csv') GROUP BY member
HAVING sum(days) &gt;= (SELECT CAST(content AS INTEGER) FROM read_text('input'));
</code></pre>
<pre><code class="language-python">"files": [{"name": "loans.csv", "content": Path("loans.csv").read_text()}],
</code></pre>
<p>With tests for N = 23 and N = 100, both pass. DuckDB prints rows the same way as SQLite (<code>ada|35</code>, no header). The rows checker matters even more here, because DuckDB doesn't promise any row order without <code>ORDER BY</code>.</p>
<h2>Storing the exercise instead of sending it each time</h2>
<p>With run-tests, the database and the expected outputs travel with every request, so your grading script is the only place that holds them. You can also store the exercise once as a problem, with the database as a data file and hidden tests. Then a student's submission is just the query, and every result comes with a signed receipt you can keep for the record. A widget can also put the problem on your course page, so students write and test their query in the browser. The full guide walks through that setup with real responses: <a href="https://onlinecompiler.io/guides/auto-grade-sql-exercises">How to auto-grade SQL exercises</a>.</p>
<h2>Limits, honestly</h2>
<ul>
<li>This post's grader runs SQLite and DuckDB, on every plan. For questions in PostgreSQL's own dialect, a test suite can start a fresh PostgreSQL server in the sandbox for each student, on Pro and above: <a href="https://onlinecompiler.io/guides/auto-grade-postgresql-exercises">How to auto-grade PostgreSQL exercises</a>. There's no MySQL server, so MySQL-only syntax can't be graded.</li>
<li>Each test counts as one run. The free plan has 100,000 runs a month (no credit card) and 60 a minute. A class of 40 students submitting a four-test exercise is 160 runs. If they all submit in the same minute, some requests get a 429 (not counted), so have your script wait a few seconds and retry.</li>
<li>A request carries up to 20 files and 1 MB in total. A stored problem takes up to 8 data files, 5 MB each and 10 MB in all.</li>
</ul>
<p><em>Disclosure: I build</em> <a href="https://onlinecompiler.io"><em>OnlineCompiler.io</em></a><em>. The idea itself (same database, compare rows, test the boundaries) works with any sandbox that can run the SQLite shell.</em></p>
]]></content:encoded></item><item><title><![CDATA[Make the code examples in your Docusaurus docs runnable, in 46 languages]]></title><description><![CDATA[Add one word to a Docusaurus code block and readers can edit and run it in the page, in Python, C++, Go, SQL and 46 languages. Free plugin.]]></description><link>https://ashwin31.hashnode.dev/make-the-code-examples-in-your-docusaurus-docs-runnable-in-46-languages</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/make-the-code-examples-in-your-docusaurus-docs-runnable-in-46-languages</guid><category><![CDATA[docusaurus]]></category><category><![CDATA[documentation]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Thu, 12 Nov 2026 15:57:29 GMT</pubDate><content:encoded><![CDATA[<p>Most docs have the same problem with code examples. The reader copies the snippet, opens a terminal or a playground in another tab, pastes it, fixes the indentation, and only then finds out what it does. Many give up before that.</p>
<p>Docusaurus has a fix for React: <code>@docusaurus/theme-live-codeblock</code> turns a <code>jsx live</code> block into a live editor. But it only renders JSX in the browser. If your docs show Python, Go, C++, SQL or anything that isn't a React component, you're back to copy and paste.</p>
<p>So I built a small plugin for that: <a href="https://github.com/onlinecompiler-io/docusaurus-plugin-onlinecompiler">docusaurus-plugin-onlinecompiler</a>. You add one word to an ordinary code block, and readers get an editor with a Run button right in the page.</p>
<p><img src="https://raw.githubusercontent.com/onlinecompiler-io/docusaurus-plugin-onlinecompiler/main/.github/screenshot.png" alt="A Docusaurus docs page with a runnable Python example and its output after Run" /></p>
<p>The code runs on <a href="https://onlinecompiler.io">OnlineCompiler.io</a> (I build it), in a fresh sandbox for each run with no network access. Nothing runs in the reader's browser or on your server, which is why the same docs can run Python, C++ or SQL as easily as JavaScript.</p>
<h2>Install it</h2>
<pre><code class="language-bash">npm install docusaurus-plugin-onlinecompiler
</code></pre>
<p>Add it to <code>docusaurus.config.js</code> with a widget key:</p>
<pre><code class="language-js">export default {
  // ...the rest of your config
  plugins: [['docusaurus-plugin-onlinecompiler', { key: 'YOUR_WIDGET_KEY' }]],
};
</code></pre>
<p>The widget key is free, from the Widgets page of the OnlineCompiler.io dashboard. It's made to sit in public pages: it can run code in the widget but can't call the REST API. Set its allowed domain to your docs domain so other sites can't use it, and make a second key for <code>localhost</code> previews.</p>
<p>If you'd rather keep the key out of the config file, read it from the environment: <code>{ key: process.env.ONLINECOMPILER_WIDGET_KEY }</code>.</p>
<h2>Write <code>runnable</code></h2>
<p>Any fenced code block, in a <code>.md</code> or <code>.mdx</code> page, becomes a runner when you add <code>runnable</code> after its language:</p>
<pre><code class="language-markdown">```python runnable
for n in range(1, 4):
    print(n, "squared is", n * n)
```
</code></pre>
<p>After Run, the output panel shows:</p>
<pre><code class="language-text">1 squared is 1
2 squared is 4
3 squared is 9
</code></pre>
<p>Readers can change the range and run it again, and the Input tab holds whatever the program reads from standard input.</p>
<p>Code blocks without the word stay exactly as they are, so you can make one example runnable and leave the rest alone.</p>
<p>The code comes through as written, <code>&lt;</code>, <code>&amp;</code> and quotes included, because it goes into the page as text and the editor reads it from there:</p>
<pre><code class="language-markdown">```cpp runnable
#include &lt;iostream&gt;
#include &lt;vector&gt;

int main() {
    std::vector&lt;int&gt; v{1, 2, 3};
    int sum = 0;
    for (int x : v) sum += x;
    std::cout &lt;&lt; "sum &amp; done: " &lt;&lt; (sum &lt; 10 ? "&lt;10" : "&gt;=10") &lt;&lt; "\n";
}
```
</code></pre>
<p>That one printed <code>sum &amp; done: &lt;10</code>.</p>
<h2>Picking the compiler</h2>
<p>The block's language picks the compiler: <code>python</code> runs Python 3.14, <code>cpp</code> runs C++ with G++ 15, <code>js</code> runs Node.js 24, <code>sql</code> runs SQLite, and full compiler ids like <code>openjdk-25</code> work too. When the language alone isn't enough, <code>lang=</code> names another compiler, and the other options on the line still work:</p>
<pre><code class="language-markdown">```python title="frame.py" runnable lang=python-3.14-pandas2
import pandas as pd
print(pd.__version__)
```
</code></pre>
<p>That prints <code>2.3.3</code>, from the Python build that ships pandas 2.</p>
<p>If a block names a language the service doesn't run, it stays a normal code block, and the build prints a warning naming the language, so a typo doesn't fail silently.</p>
<h2>Inside Tabs and admonitions</h2>
<p>Runnable blocks work anywhere Docusaurus renders a code block, including Tabs and admonitions:</p>
<pre><code class="language-mdx">import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

&lt;Tabs&gt;
&lt;TabItem value="js" label="JavaScript"&gt;

```js runnable
console.log([1, 2, 3].map((x) =&gt; x * 2));
```

&lt;/TabItem&gt;
&lt;TabItem value="go" label="Go"&gt;

```go runnable
package main

import "fmt"

func main() { fmt.Println("hi from Go") }
```

&lt;/TabItem&gt;
&lt;/Tabs&gt;
</code></pre>
<p>The JavaScript tab printed <code>[ 2, 4, 6 ]</code> and the Go tab <code>hi from Go</code>.</p>
<h2>How it works</h2>
<p>The plugin is small, and the source is on GitHub, but three choices are worth knowing about if you care what ends up in your docs.</p>
<p><strong>It wraps Docusaurus's own <code>CodeBlock</code>.</strong> The plugin provides a theme component that wraps the original one. A block without <code>runnable</code> goes straight to the normal <code>CodeBlock</code>, so your syntax highlighting, titles and line numbers don't change. A runnable block renders a plain <code>&lt;div&gt;</code> with the code in a <code>&lt;pre&gt;</code>, and the widget turns that into the editor.</p>
<p><strong>The code is in the HTML.</strong> Because the server render puts the code in the page as text, search engines index your examples and readers see them before the editor loads. If the service can't be reached, the code is still there; only the Run button needs it.</p>
<p><strong>The widget script loads only where it's needed.</strong> The script is added the first time a page with a runnable block mounts, not on every page of your site. Each runner connects only when it scrolls into view. As readers move between pages without a reload, new runners start and the ones that left the page close their connection. Runners also follow your site's light and dark mode as the reader switches it.</p>
<p>One limitation to know: <code>@docusaurus/theme-live-codeblock</code> also replaces the code block component, and a Docusaurus site can only have one such wrapper. If you list both, the one listed last in <code>themes</code> wins. Use the live code block for React component demos and this plugin for programs in other languages, not both on one site.</p>
<h2>What it costs</h2>
<p>The plugin is free and MIT licensed. Each press of Run is one run on your OnlineCompiler.io account, and the free plan has 100,000 runs a month with no credit card. You can give the widget key its own monthly limit to cap what a public page can use.</p>
<h2>Links</h2>
<ul>
<li>The full guide, with options and troubleshooting: <a href="https://onlinecompiler.io/guides/add-runnable-code-examples-to-docusaurus">https://onlinecompiler.io/guides/add-runnable-code-examples-to-docusaurus</a></li>
<li>npm: <a href="https://www.npmjs.com/package/docusaurus-plugin-onlinecompiler">https://www.npmjs.com/package/docusaurus-plugin-onlinecompiler</a></li>
<li>Source: <a href="https://github.com/onlinecompiler-io/docusaurus-plugin-onlinecompiler">https://github.com/onlinecompiler-io/docusaurus-plugin-onlinecompiler</a></li>
</ul>
<p>If you use MkDocs instead, there's a plugin for that too: <a href="https://github.com/onlinecompiler-io/mkdocs-onlinecompiler">mkdocs-onlinecompiler</a>. And if your docs run on something else, tell me which. We build integrations for other platforms free of charge.</p>
]]></content:encoded></item><item><title><![CDATA[Build an online code editor in React with a Run button (and keep your API key off the browser)]]></title><description><![CDATA[A React code editor with a language menu and a Run button, and an Express or Next.js route that keeps the API key on the server.]]></description><link>https://ashwin31.hashnode.dev/build-an-online-code-editor-in-react-with-a-run-button-and-keep-your-api-key-off-the-browser</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/build-an-online-code-editor-in-react-with-a-run-button-and-keep-your-api-key-off-the-browser</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Mon, 09 Nov 2026 10:33:59 GMT</pubDate><content:encoded><![CDATA[<p>You've seen the demo: a code editor in the browser, a language menu, a Run button, and the program's output underneath. Most tutorials for it take one of two shortcuts. Some call Judge0 on RapidAPI straight from React, with the key in a <code>REACT_APP_</code> variable. Others post the code to the public Piston API. Both break:</p>
<ul>
<li>A key in a <code>REACT_APP_</code> or <code>VITE_</code> variable is built into the JavaScript your visitors download. Anyone can copy it from the page and spend your runs.</li>
<li>The public Piston API has been whitelist only since 15 February 2026. When I tried it today:</li>
</ul>
<pre><code class="language-text">HTTP 401
{"message":"Public Piston API is now whitelist only as of 2/15/2026. ..."}
</code></pre>
<p>This post builds the editor the safe way: a React component for the editor, and a 30-line server route that holds the key. I built and ran everything below, and the finished app is on GitHub.</p>
<img src="https://raw.githubusercontent.com/onlinecompiler-io/react-code-editor/main/screenshot.png" alt="The finished editor: a language menu, a Run button, the code, an input box and the output" style="display:block;margin:0 auto" />

<h2>How the Run button works</h2>
<p>Three parts pass the code along:</p>
<ol>
<li>The React component holds the code, the language and the input. Run posts them to <code>/api/run</code> on your own server.</li>
<li>That route adds your API key and forwards those three fields to a code execution API. I use <a href="http://OnlineCompiler.io">OnlineCompiler.io</a>'s <code>run-code-sync</code> endpoint (I build it), which runs the program in a fresh sandbox with no network access and answers with its output, errors, exit code, run time and memory.</li>
<li>The route passes the answer back, and the component shows it.</li>
</ol>
<p>The route isn't optional. Besides keeping the key secret, it's the only way the call works at all: the API sends no CORS headers, so a browser refuses to call it from your page.</p>
<h2>Setup</h2>
<pre><code class="language-bash">npm create vite@latest code-editor -- --template react
cd code-editor
npm install
npm install @uiw/react-codemirror express \
  @codemirror/lang-python @codemirror/lang-javascript @codemirror/lang-cpp @codemirror/lang-java
</code></pre>
<p>Get a free API key at <a href="https://api.onlinecompiler.io/compilers/api-keys/">onlinecompiler.io</a> (100,000 runs a month, no credit card) and put it in <code>.env.local</code> in the project folder:</p>
<pre><code class="language-bash">ONLINECOMPILER_API_KEY=your_api_key
</code></pre>
<p>Vite's <code>.gitignore</code> already leaves <code>*.local</code> files out of git. Don't call it <code>VITE_ONLINECOMPILER_API_KEY</code>: Vite builds every <code>VITE_</code> variable into the browser code, which is exactly the leak we're avoiding.</p>
<p>I use CodeMirror 6 through <code>@uiw/react-codemirror</code> because it bundles into your app with no extra setup. Monaco works too; see the end.</p>
<h2>The editor component</h2>
<p>Replace <code>src/App.jsx</code> with this:</p>
<pre><code class="language-jsx">import { useState } from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { python } from '@codemirror/lang-python';
import { javascript } from '@codemirror/lang-javascript';
import { cpp } from '@codemirror/lang-cpp';
import { java } from '@codemirror/lang-java';
import './App.css';

// Compiler ids from GET https://api.onlinecompiler.io/api/compilers/
const LANGUAGES = [
  {
    id: 'python-3.14',
    label: 'Python (3.14)',
    extension: python(),
    starter: 'name = input()\nprint(f"Hello, {name}!")\n',
  },
  {
    id: 'nodejs-24',
    label: 'JavaScript (Node.js 24)',
    extension: javascript(),
    starter: "const name = require('fs').readFileSync(0, 'utf8').trim();\nconsole.log(`Hello, ${name}!`);\n",
  },
  {
    id: 'g++-15',
    label: 'C++ (G++ 15)',
    extension: cpp(),
    starter: '#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nint main() {\n    std::string name;\n    std::getline(std::cin, name);\n    std::cout &lt;&lt; "Hello, " &lt;&lt; name &lt;&lt; "!\\n";\n}\n',
  },
  {
    id: 'openjdk-25',
    label: 'Java (OpenJDK 25)',
    extension: java(),
    starter: 'import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        String name = new Scanner(System.in).nextLine();\n        System.out.println("Hello, " + name + "!");\n    }\n}\n',
  },
];

export default function App() {
  const [language, setLanguage] = useState(LANGUAGES[0]);
  const [code, setCode] = useState(LANGUAGES[0].starter);
  const [input, setInput] = useState('World');
  const [result, setResult] = useState(null);
  const [running, setRunning] = useState(false);

  function pickLanguage(id) {
    const next = LANGUAGES.find((l) =&gt; l.id === id);
    setLanguage(next);
    setCode(next.starter);
    setResult(null);
  }

  async function run() {
    setRunning(true);
    setResult(null);
    try {
      const response = await fetch('/api/run', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ compiler: language.id, code, input }),
      });
      const data = await response.json().catch(() =&gt; ({}));
      // A refused run (400, 429, ...) has no output, only an error message.
      setResult(response.ok ? data : { refused: data.error || `HTTP ${response.status}` });
    } catch {
      setResult({ refused: 'Could not reach the server. Is it running?' });
    } finally {
      setRunning(false);
    }
  }

  return (
    &lt;main className="editor"&gt;
      &lt;div className="toolbar"&gt;
        &lt;select aria-label="Language" disabled={running} value={language.id} onChange={(e) =&gt; pickLanguage(e.target.value)}&gt;
          {LANGUAGES.map((l) =&gt; (
            &lt;option key={l.id} value={l.id}&gt;{l.label}&lt;/option&gt;
          ))}
        &lt;/select&gt;
        &lt;button onClick={run} disabled={running}&gt;{running ? 'Running...' : 'Run'}&lt;/button&gt;
      &lt;/div&gt;

      &lt;CodeMirror value={code} height="260px" extensions={[language.extension]} onChange={setCode} /&gt;

      &lt;label&gt;
        Input
        &lt;textarea value={input} onChange={(e) =&gt; setInput(e.target.value)} rows={3} /&gt;
      &lt;/label&gt;

      &lt;section className="output" aria-live="polite"&gt;
        {result?.refused &amp;&amp; &lt;pre className="stderr"&gt;{result.refused}&lt;/pre&gt;}
        {result &amp;&amp; !result.refused &amp;&amp; (
          &lt;&gt;
            &lt;pre&gt;{result.output}&lt;/pre&gt;
            {result.error &amp;&amp; &lt;pre className="stderr"&gt;{result.error}&lt;/pre&gt;}
            &lt;p&gt;Exit code {result.exit_code} in {result.time} s{result.truncated ? ' (output cut)' : ''}&lt;/p&gt;
          &lt;/&gt;
        )}
      &lt;/section&gt;
    &lt;/main&gt;
  );
}
</code></pre>
<p>What each part does:</p>
<ul>
<li><strong>The language menu</strong> holds compiler ids. <code>GET https://api.onlinecompiler.io/api/compilers/</code> lists all of them and needs no key. To add a language, add its id and a CodeMirror language package such as <code>@codemirror/lang-rust</code>, or <code>extension: []</code> for plain text.</li>
<li><strong>The input box</strong> is the program's standard input. Each starter reads one line and greets it.</li>
<li><strong>Run</strong> posts the compiler id, the code and the input to <code>/api/run</code>. A refused run (a bad request, a rate limit) has no output, only an error message, so the component keeps the two cases apart.</li>
<li><strong>The output panel</strong> shows what the program printed, then its errors in red (standard error, or the compiler's messages when it didn't compile), then the exit code and run time.</li>
</ul>
<p>For the styles, set <code>src/index.css</code> to <code>body { margin: 0; }</code> and put this in <code>src/App.css</code>:</p>
<pre><code class="language-css">.editor { max-width: 760px; margin: 2rem auto; display: grid; gap: 0.75rem; font-family: system-ui, sans-serif; }
.toolbar { display: flex; gap: 0.5rem; }
.toolbar button { padding: 0.4rem 1.2rem; }
.editor .cm-editor { border: 1px solid #ccc; font-size: 14px; }
.editor label { display: grid; gap: 0.25rem; }
.editor textarea { font-family: ui-monospace, monospace; }
.output { background: #111; color: #eee; padding: 0.75rem; min-height: 4rem; border-radius: 4px; }
.output pre { margin: 0 0 0.5rem; white-space: pre-wrap; }
.output .stderr { color: #ff8a80; }
.output p { margin: 0; color: #aaa; font-size: 0.85rem; }
</code></pre>
<h2>The server route that keeps the key</h2>
<p>Create <code>server.js</code> next to <code>package.json</code>. It's the only file that reads the key:</p>
<pre><code class="language-js">// server.js: the only part of the app that knows the API key.
import express from 'express';

const API_KEY = process.env.ONLINECOMPILER_API_KEY;
if (!API_KEY) throw new Error('Set ONLINECOMPILER_API_KEY');

const app = express();
app.use(express.json({ limit: '300kb' })); // room for the largest code and input the API takes

app.post('/api/run', async (req, res) =&gt; {
  const { compiler, code, input } = req.body ?? {};
  try {
    const response = await fetch('https://api.onlinecompiler.io/api/run-code-sync/', {
      method: 'POST',
      headers: { Authorization: API_KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify({ compiler, code, input }),
      signal: AbortSignal.timeout(60_000),
    });
    // Pass the answer through: 200 with the result, or 400 or 429 with {"error": "..."}.
    res.status(response.status).type('json').send(await response.text());
  } catch {
    res.status(502).json({ error: 'The code runner did not answer. Try again.' });
  }
});

app.use(express.static('dist')); // the built React app, after npm run build

const port = process.env.PORT || 3001;
app.listen(port, (error) =&gt; {
  if (error) throw error;
  console.log(`Listening on http://localhost:${port}`);
});
</code></pre>
<p>Three details that matter:</p>
<ul>
<li>It forwards only <code>compiler</code>, <code>code</code> and <code>input</code>, whatever else a request to <code>/api/run</code> holds, so nobody can use your route to send other options with your key.</li>
<li><code>express.json</code> takes 100 kB by default, which would refuse a big program before it reached the API (the API accepts up to 100 KB of code plus 100 KB of input). Hence <code>300kb</code>.</li>
<li>Express 5 hands a failed <code>listen</code>, such as a port that's already taken, to the callback. Without <code>if (error) throw error</code>, the server prints that it's listening and then quietly exits.</li>
</ul>
<p>During development Vite serves the page itself, so tell it to pass <code>/api</code> requests on to Express in <code>vite.config.js</code>:</p>
<pre><code class="language-js">import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [react()],
  // In development, send /api requests to the Express server.
  server: { proxy: { '/api': 'http://localhost:3001' } },
});
</code></pre>
<p>Start both (<code>--env-file</code> needs Node 20.6 or newer) and open <code>http://localhost:5173</code>:</p>
<pre><code class="language-bash"># Terminal 1: the route, on port 3001
node --env-file=.env.local server.js

# Terminal 2: the React app, on http://localhost:5173
npm run dev
</code></pre>
<p>With the Python starter and <code>World</code> in the input, Run shows:</p>
<pre><code class="language-text">Hello, World!
Exit code 0 in 0.0308 s
</code></pre>
<p>And this is the JSON the route passed back. <code>time</code> is in seconds and <code>memory</code> in KB:</p>
<pre><code class="language-json">{
  "output": "Hello, World!\n",
  "error": "",
  "status": "success",
  "exit_code": 0,
  "signal": null,
  "truncated": false,
  "time": "0.0308",
  "memory": "14400",
  "total": "0.0556",
  "files": [],
  "files_truncated": false,
  "time_limit": 30,
  "memory_limit": 512
}
</code></pre>
<p>For production, run <code>npm run build</code> once; then <code>node --env-file=.env.local server.js</code> serves the built app and the route together on port 3001.</p>
<h2>When the code fails, or a limit is reached</h2>
<p>A program that fails still answers 200. Here's Python with an unclosed bracket, through the same route:</p>
<pre><code class="language-json">{
  "output": "",
  "error": "  File \"code.py\", line 1\n    print(\"hi\"\n         ^\nSyntaxError: '(' was never closed\n",
  "status": "error",
  "exit_code": 1,
  ...
}
</code></pre>
<p>The panel shows <code>error</code> in red. Exit code 124 means the program ran over 30 seconds, and 137 that it went over 512 MB of memory.</p>
<p>A refused run gets an error status and <code>{"error": "..."}</code>. Nothing runs, and it doesn't count against your runs:</p>
<table>
<thead>
<tr>
<th>Status</th>
<th>When</th>
<th>Message, for example</th>
</tr>
</thead>
<tbody><tr>
<td>400</td>
<td>An unknown compiler id, empty code, or code over 100 KB</td>
<td><code>Unsupported or missing compiler</code></td>
</tr>
<tr>
<td>403 or 404</td>
<td>The key is missing, mistyped or turned off</td>
<td><code>Invalid or inactive API key</code></td>
</tr>
<tr>
<td>429</td>
<td>Too many runs a minute, at once, or this month (the message says which)</td>
<td><code>Submission rate limit exceeded. Try again shortly.</code></td>
</tr>
<tr>
<td>502</td>
<td>Sent by your own route when the API didn't answer within 60 seconds</td>
<td><code>The code runner did not answer. Try again.</code></td>
</tr>
</tbody></table>
<p>One thing before you put it online: anyone who can open your page can press Run, and anyone who finds <code>/api/run</code> can call it. On a public site, put the route behind your own sign-in or a rate limit, and give the key a monthly limit of its own in the dashboard so it can't use up the whole account.</p>
<h2>The same thing in Next.js</h2>
<p>In the App Router, the route is a route handler, <code>app/api/run/route.ts</code>:</p>
<pre><code class="language-ts">// app/api/run/route.ts: the only part of the app that knows the API key.
export async function POST(request: Request) {
  const key = process.env.ONLINECOMPILER_API_KEY;
  if (!key) return Response.json({ error: 'Server is missing ONLINECOMPILER_API_KEY' }, { status: 500 });
  const body = await request.json().catch(() =&gt; null);
  const { compiler, code, input } = body ?? {};
  try {
    const response = await fetch('https://api.onlinecompiler.io/api/run-code-sync/', {
      method: 'POST',
      headers: {
        Authorization: key,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ compiler, code, input }),
      signal: AbortSignal.timeout(60_000),
    });
    // Pass the answer through: 200 with the result, or 400 or 429 with {"error": "..."}.
    return new Response(await response.text(), {
      status: response.status,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch {
    return Response.json({ error: 'The code runner did not answer. Try again.' }, { status: 502 });
  }
}
</code></pre>
<p>Put the key in <code>.env.local</code> as before; Next.js loads it, and its <code>.gitignore</code> already skips <code>.env*</code> files. The component works unchanged with <code>'use client';</code> as its first line: save it as <code>app/CodeEditor.jsx</code> with <code>App.css</code> beside it and render <code>&lt;CodeEditor /&gt;</code> from <code>app/page.tsx</code>. No proxy is needed, because the page and the route share one server.</p>
<h2>Coming from Judge0 or Piston?</h2>
<p>This is how their requests map:</p>
<table>
<thead>
<tr>
<th></th>
<th>Judge0 CE on RapidAPI</th>
<th>Public Piston API</th>
<th><a href="http://OnlineCompiler.io">OnlineCompiler.io</a></th>
</tr>
</thead>
<tbody><tr>
<td>Request</td>
<td><code>POST https://judge0-ce.p.rapidapi.com/submissions</code></td>
<td><code>POST https://emkc.org/api/v2/piston/execute</code></td>
<td><code>POST https://api.onlinecompiler.io/api/run-code-sync/</code></td>
</tr>
<tr>
<td>Key</td>
<td><code>X-RapidAPI-Key</code> and <code>X-RapidAPI-Host</code> headers</td>
<td>None; 401 unless whitelisted</td>
<td><code>Authorization: YOUR_API_KEY</code> (no <code>Bearer</code>)</td>
</tr>
<tr>
<td>Language</td>
<td><code>language_id: 71</code></td>
<td><code>language: "python"</code> and <code>version</code></td>
<td><code>compiler: "python-3.14"</code></td>
</tr>
<tr>
<td>Code</td>
<td><code>source_code</code>, base64 with <code>base64_encoded=true</code></td>
<td><code>files: [{ name, content }]</code></td>
<td><code>code</code>, as plain text</td>
</tr>
<tr>
<td>Input</td>
<td><code>stdin</code></td>
<td><code>stdin</code></td>
<td><code>input</code></td>
</tr>
<tr>
<td>Result</td>
<td>A <code>token</code> to poll, or at once with <code>wait=true</code></td>
<td>In the response</td>
<td>In the response</td>
</tr>
<tr>
<td>Output</td>
<td><code>stdout</code>, <code>stderr</code>, <code>compile_output</code></td>
<td><code>run.stdout</code>, <code>run.stderr</code></td>
<td><code>output</code>, <code>error</code> (compiler messages included)</td>
</tr>
</tbody></table>
<p>If you'd rather keep the request code you have, the API answers both shapes too: Judge0 requests at <code>https://api.onlinecompiler.io/api/judge0</code> with the key in <code>X-Auth-Token</code>, and Piston requests at <code>https://api.onlinecompiler.io/api/v2/piston</code> with it in <code>Authorization</code>. Either way, move the call into a server route.</p>
<h2>Don't need your own editor?</h2>
<p>If all you want is an editor with a Run button on a page, the embeddable widget needs no server and no route:</p>
<pre><code class="language-html">&lt;script src="https://onlinecompiler.io/widget.js"&gt;&lt;/script&gt;

&lt;div class="runcode" data-key="YOUR_WIDGET_KEY" data-lang="python-3.14"&gt;
&lt;pre&gt;name = input()
print(f"Hello, {name}!")&lt;/pre&gt;
&lt;pre data-stdin&gt;World&lt;/pre&gt;
&lt;/div&gt;
</code></pre>
<p>A widget key is meant to sit in public HTML: it only works for the editor, can't call the REST API, and can be locked to your domain. Build your own, as above, when the editor is part of your app: your own layout, your own sign-in in front of Run, or the result on your server to save or grade.</p>
<h2>Two more things you can do with it</h2>
<ul>
<li><strong>Use Monaco instead of CodeMirror.</strong> Swap the CodeMirror element for <code>Editor</code> from <code>@monaco-editor/react</code>, use Monaco's language names (<code>python</code>, <code>javascript</code>, <code>cpp</code>, <code>java</code>), and call <code>setCode(value ?? '')</code> in its <code>onChange</code>. By default it downloads Monaco from a CDN when the page opens. The route stays the same.</li>
<li><strong>Grade the code.</strong> Send it to the run-tests endpoint with test cases (inputs and expected outputs) instead of run-code-sync, and you get a verdict for each test and a score. Tests can be hidden, so a student sees the result without the expected output. That turns this editor into a practice-problem page.</li>
</ul>
<p>The finished app, with the Next.js version, is at <a href="https://github.com/onlinecompiler-io/react-code-editor">github.com/onlinecompiler-io/react-code-editor</a> (MIT). The full guide, with the widget running live, is here: <a href="https://onlinecompiler.io/guides/react-code-editor-with-run-button">Build an online code editor in React with a Run button</a>.</p>
<p><em>Disclosure: I build</em> <a href="http://OnlineCompiler.io"><em>OnlineCompiler.io</em></a><em>. The component and the route work the same way with any code execution API that takes code and standard input; only the URL and the field names change.</em></p>
]]></content:encoded></item><item><title><![CDATA[Using .h and .cpp files in an online C++ compiler (and why most of them fail)]]></title><description><![CDATA[Why #include "Student.h" fails in one-file online compilers, three ways to run .h and .cpp files together, and what each linker error means.]]></description><link>https://ashwin31.hashnode.dev/using-h-and-cpp-files-in-an-online-c-compiler-and-why-most-of-them-fail</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/using-h-and-cpp-files-in-an-online-c-compiler-and-why-most-of-them-fail</guid><category><![CDATA[C++]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Mon, 09 Nov 2026 09:00:32 GMT</pubDate><content:encoded><![CDATA[<p>Most online C++ compilers give you one editor, and one editor means one file. That's fine until your course splits a class into <code>Student.h</code> and <code>Student.cpp</code>. Then the second line of <code>main.cpp</code> stops the build:</p>
<pre><code class="language-text">code.cc:2:10: fatal error: Student.h: No such file or directory
    2 | #include "Student.h"
      |          ^~~~~~~~~~~
compilation terminated.
</code></pre>
<p>Here's why that happens, three ways around it, and the linker errors you'll meet on the way.</p>
<h2>Why the include fails</h2>
<p><code>#include "Student.h"</code> tells the compiler to read <code>Student.h</code> from the folder of the file that includes it. A one-file online compiler saves your code on its own in an empty folder, so there is no <code>Student.h</code> to read.</p>
<p>Pasting in just the header doesn't fix it either. The header only <em>declares</em> the class; the member functions are <em>defined</em> in <code>Student.cpp</code>. If that file isn't compiled too, the linker stops instead:</p>
<pre><code class="language-text">/usr/bin/ld: /tmp/ccdg4WQe.o: in function `main':
code.cc:(.text.startup+0x33): undefined reference to `Student::Student(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;, int)'
...
collect2: error: ld returned 1 exit status
</code></pre>
<p>The program needs both files, compiled and linked together.</p>
<h2>The example</h2>
<p>A small class, split the usual way:</p>
<pre><code class="language-cpp">// Student.h
#ifndef STUDENT_H
#define STUDENT_H

#include &lt;string&gt;

class Student {
public:
    Student(const std::string&amp; name, int score);
    std::string name() const;
    bool passed() const;

private:
    std::string name_;
    int score_;
};

#endif
</code></pre>
<pre><code class="language-cpp">// Student.cpp
#include "Student.h"

Student::Student(const std::string&amp; name, int score) : name_(name), score_(score) {}

std::string Student::name() const { return name_; }

bool Student::passed() const { return score_ &gt;= 50; }
</code></pre>
<pre><code class="language-cpp">// main.cpp
#include &lt;iostream&gt;
#include "Student.h"

int main() {
    Student ada("Ada", 91);
    Student tim("Tim", 42);
    std::cout &lt;&lt; ada.name() &lt;&lt; (ada.passed() ? " passed" : " failed") &lt;&lt; "\n";
    std::cout &lt;&lt; tim.name() &lt;&lt; (tim.passed() ? " passed" : " failed") &lt;&lt; "\n";
}
</code></pre>
<p>On your own computer you build both <code>.cpp</code> files into one program:</p>
<pre><code class="language-bash">g++ main.cpp Student.cpp -o main
./main
</code></pre>
<pre><code class="language-text">Ada passed
Tim failed
</code></pre>
<h2>Option 1: paste the class above <code>main</code></h2>
<p>This works in any online compiler. Put the class declaration and its member functions in the same file, above <code>main</code>, and drop the <code>#include "Student.h"</code> line. It's fine for a quick check, but you lose the very structure your course is trying to teach, and it doesn't scale past one or two classes.</p>
<h2>Option 2: use an online IDE with projects</h2>
<p>If you want to click Run in a browser with a tab per file, use a tool that has projects. OnlineGDB lets you add files to a project (and has a debugger), Playcode handles <code>.cpp</code> and <code>.h</code> files in folders, and Replit builds every C++ file in a project into one program. Check each one's current plans and limits yourself.</p>
<h2>Option 3: send the files to a compiler API</h2>
<p>If the code comes from a script, a course platform or an autograder rather than a person typing in a browser, send the files with the program. OnlineCompiler.io's API (which I build) takes <code>main.cpp</code> as the program and every other file in a <code>files</code> list:</p>
<pre><code class="language-bash">curl -X POST https://api.onlinecompiler.io/api/run-code-sync/ \
  -H "Authorization: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "compiler": "g++-15",
    "code": "#include &lt;iostream&gt;\n#include \"Student.h\"\n\nint main() {\n    Student ada(\"Ada\", 91);\n    Student tim(\"Tim\", 42);\n    std::cout &lt;&lt; ada.name() &lt;&lt; (ada.passed() ? \" passed\" : \" failed\") &lt;&lt; \"\\n\";\n    std::cout &lt;&lt; tim.name() &lt;&lt; (tim.passed() ? \" passed\" : \" failed\") &lt;&lt; \"\\n\";\n}\n",
    "files": [
      {"name": "Student.h", "content": "#ifndef STUDENT_H\n#define STUDENT_H\n\n#include &lt;string&gt;\n\nclass Student {\npublic:\n    Student(const std::string&amp; name, int score);\n    std::string name() const;\n    bool passed() const;\n\nprivate:\n    std::string name_;\n    int score_;\n};\n\n#endif\n"},
      {"name": "Student.cpp", "content": "#include \"Student.h\"\n\nStudent::Student(const std::string&amp; name, int score) : name_(name), score_(score) {}\n\nstd::string Student::name() const { return name_; }\n\nbool Student::passed() const { return score_ &gt;= 50; }\n"}
    ]
  }'
</code></pre>
<p>The response's <code>output</code> is <code>Ada passed\nTim failed\n</code> and <code>exit_code</code> is 0. What happens on the server:</p>
<ul>
<li>Every <code>.cpp</code>, <code>.cc</code> and <code>.cxx</code> file you send is compiled and linked with the program, here as <code>g++ -O2 -Wall code.cc Student.cpp -o code.out</code>.</li>
<li>Headers aren't compiled on their own; they're read where a file includes them.</li>
<li>The <code>name</code> must match your <code>#include</code> exactly, capital letters included: <code>student.h</code> is not <code>Student.h</code>.</li>
<li>Folders work (<code>lib/Student.h</code>), up to 20 files and 1 MB besides the program.</li>
<li><code>g++-15</code> is C++17; use <code>g++-15-cpp20</code> for C++20. Add <code>"input"</code> when the program reads from <code>cin</code>.</li>
</ul>
<p>The same thing from Python, reading the files from the folder you run it in:</p>
<pre><code class="language-python">from pathlib import Path
import requests

files = ["Student.h", "Student.cpp"]
response = requests.post(
    "https://api.onlinecompiler.io/api/run-code-sync/",
    headers={"Authorization": "YOUR_API_KEY"},
    json={
        "compiler": "g++-15",
        "code": Path("main.cpp").read_text(),
        "files": [{"name": name, "content": Path(name).read_text()} for name in files],
    },
    timeout=60,
)
result = response.json()
print(result["output"], end="")
print(result["error"], end="")
print("exit code:", result["exit_code"])
</code></pre>
<h2>What if your course says <code>#include "Student.cpp"</code>?</h2>
<p>Some courses have <code>main.cpp</code> include the <code>.cpp</code> file instead of the header, so the class arrives with its code in one step. Change the include and send the same two files: it prints the same output. The rule that makes both styles work is that a file included with <code>#include "..."</code> is compiled only through that include, never again on its own, so each function is compiled exactly once.</p>
<p>On your own computer the two styles need different commands. With the header, build both files (<code>g++ main.cpp Student.cpp</code>). With <code>#include "Student.cpp"</code>, build only <code>g++ main.cpp</code>. Build both in that style and the class is compiled twice, which the linker refuses (shortened):</p>
<pre><code class="language-text">$ g++ main.cpp Student.cpp -o main
/usr/bin/ld: /tmp/cciho97q.o: in function `Student::Student(...)':
Student.cpp:(.text+0x0): multiple definition of `Student::Student(...)'; /tmp/ccteijRb.o:main.cpp:(.text+0xb0): first defined here
collect2: error: ld returned 1 exit status
</code></pre>
<p>An IDE that builds every <code>.cpp</code> file in a project does exactly that, so there, include the header. Headers are how larger C++ programs are built anyway.</p>
<h2>The errors, in one table</h2>
<table>
<thead>
<tr>
<th>Error</th>
<th>What it means</th>
<th>Fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>fatal error: Student.h: No such file or directory</code></td>
<td>The header isn't next to the program, or its name differs (case counts)</td>
<td>Add it under the exact name you include</td>
</tr>
<tr>
<td><code>undefined reference to `Student::Student(...)'</code></td>
<td>The header was found, but nothing defines the functions it declares</td>
<td>Compile and link <code>Student.cpp</code> too</td>
</tr>
<tr>
<td><code>redefinition of 'class Student'</code></td>
<td>One file read the header twice, and it has no include guard</td>
<td>Wrap it in <code>#ifndef STUDENT_H</code> / <code>#define STUDENT_H</code> / <code>#endif</code>, or use <code>#pragma once</code></td>
</tr>
<tr>
<td><code>multiple definition of `passMark()'</code></td>
<td>A function body lives in a header that two <code>.cpp</code> files include</td>
<td>Move the body to the <code>.cpp</code>, or mark it <code>inline</code></td>
</tr>
<tr>
<td><code>multiple definition of `main'</code></td>
<td>A second file (often a <code>.cpp</code> with a leftover test <code>main</code>) defines <code>main</code></td>
<td>Keep one <code>main</code></td>
</tr>
</tbody></table>
<h2>Grading multi-file C++ automatically</h2>
<p>If you teach, the same <code>files</code> list works with the API's run-tests endpoint: send the student's <code>Student.cpp</code>, your own <code>main.cpp</code> that exercises it, and a list of inputs with expected outputs, and you get a verdict for each test and a score. That's how you can auto-grade a class assignment without setting up a judge server. The free plan has 100,000 runs a month, no credit card.</p>
<p>The full guide, with every output and the C, Java and folder variations, is here: <a href="https://onlinecompiler.io/guides/cpp-header-and-source-files-online">C++ header files in an online compiler</a>.</p>
<p><em>Disclosure: I build OnlineCompiler.io. Options 1 and 2 above work without it.</em></p>
]]></content:encoded></item><item><title><![CDATA[I Built a Multi-Tenant CRM with PostgreSQL Row-Level Security, Here's What I Learned]]></title><description><![CDATA[Building Multi-Tenant CRM SaaS with PostgreSQL Row-Level Security]]></description><link>https://ashwin31.hashnode.dev/i-built-a-multi-tenant-crm-with-postgresql-row-level-security-here-s-what-i-learned</link><guid isPermaLink="true">https://ashwin31.hashnode.dev/i-built-a-multi-tenant-crm-with-postgresql-row-level-security-here-s-what-i-learned</guid><dc:creator><![CDATA[Aswani Kumar]]></dc:creator><pubDate>Sun, 01 Mar 2026 12:40:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69a424aca7428b958daf4819/7b4e92b8-015c-4f28-a857-87821fbd0afb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every CRM I've ever used has made me angry.</p>
<p>Not the "this button is in the wrong place" kind of angry. The "I'm paying $65/user/month and I can't even export my own data" kind of angry.</p>
<p>I'm Ashwin Kumar. I ran <a href="https://micropyramid.com">MicroPyramid</a>, a software consulting firm with 100+ engineers and clients across the US, Australia, Israel, and the UK. Over a decade, we built custom CRMs, ERPs, and SaaS platforms for dozens of companies. And every single time, the conversation started the same way:</p>
<p><em>"We're using Salesforce/HubSpot/Zoho, but it's too expensive, too locked-in, and we can't customize it."</em></p>
<p>So we'd build them something custom. Again and again. After the fifth time building essentially the same multi-tenant CRM from scratch, I thought why not build it once, properly, and open-source it?</p>
<p>That became <a href="https://github.com/MicroPyramid/Django-CRM">Django-CRM</a> (now <strong>BottleCRM</strong>). It's got 2,100+ stars on GitHub, it's MIT-licensed, and it runs in production. But the most interesting technical decision the one I want to talk about is how we handle multi-tenancy.</p>
<h2>The Multi-Tenancy Problem</h2>
<p>If you're building any SaaS, you need multi-tenancy. Multiple organizations sharing the same application, each seeing only their own data. There are three common approaches:</p>
<ol>
<li><p><strong>Separate databases per tenant</strong> bulletproof isolation, operational nightmare</p>
</li>
<li><p><strong>Schema-per-tenant</strong> (the <code>django-tenants</code> approach) each tenant gets a PostgreSQL schema, shared database</p>
</li>
<li><p><strong>Shared schema with Row-Level Security</strong> one schema, one set of tables, PostgreSQL enforces isolation at the row level</p>
</li>
</ol>
<p>When I started, <code>django-tenants</code> was the obvious choice. It's mature, well-documented, and the Django community loves it. I almost went with it.</p>
<p>Then I did the math.</p>
<h2>Why Schema-Per-Tenant Broke Down</h2>
<p>With <code>django-tenants</code>, every <code>migrate</code> runs against every schema. Got 500 tenants? That's 500 migration runs. Add a column? Hope you've got time.</p>
<p>Here's what we actually hit in production with schema-per-tenant on a previous project:</p>
<ul>
<li><p><strong>Migration time scaled linearly</strong> with tenant count. 200 tenants meant 45+ minute deploys.</p>
</li>
<li><p><strong>Connection pooling was painful.</strong> PgBouncer doesn't love <code>SET search_path</code> on every request. We burned hours debugging stale connections.</p>
</li>
<li><p><strong>Cross-tenant queries were nearly impossible.</strong> Want to build an admin dashboard showing all tenants? You're writing raw SQL with <code>UNION ALL</code> across schemas.</p>
</li>
<li><p><strong>Django's ORM assumed one schema.</strong> We were constantly fighting the framework instead of using it.</p>
</li>
</ul>
<p>RLS flips the model entirely.</p>
<h2>Row-Level Security: Let PostgreSQL Do the Hard Work</h2>
<p>With RLS, every table has a policy that says: "You can only see rows where <code>org_id</code> matches the current session variable." PostgreSQL enforces this at the engine level — not in your application code, not in your ORM, not in a middleware hack. At the database engine level.</p>
<p>Here's what an actual RLS policy looks like for our <code>leads</code> table:</p>
<pre><code class="language-sql">-- Enable RLS on the table
ALTER TABLE leads_lead ENABLE ROW LEVEL SECURITY;

-- Force RLS even for table owners
ALTER TABLE leads_lead FORCE ROW LEVEL SECURITY;

-- The policy: users can only see rows belonging to their org
CREATE POLICY tenant_isolation_policy ON leads_lead
    USING (org_id = current_setting('app.current_org')::INTEGER);

-- Separate policy for INSERT (ensure users can only create rows for their org)
CREATE POLICY tenant_insert_policy ON leads_lead
    FOR INSERT
    WITH CHECK (org_id = current_setting('app.current_org')::INTEGER);
</code></pre>
<p>That's it. Once this policy exists, PostgreSQL will <strong>never</strong> return a row from another tenant, even if your application code has a bug. Even if someone writes a raw SQL query. Even if a junior developer forgets to add <code>.filter(org=request.org)</code>. The database says no.</p>
<p>This is defense in depth that actually works.</p>
<h2>How Django Talks to RLS</h2>
<p>The magic glue is a middleware that sets the PostgreSQL session variable on every request. Here's the actual pattern:</p>
<pre><code class="language-python"># middleware/tenant.py

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Extract org from the authenticated user's JWT
        org_id = getattr(request, 'org', None)

        if org_id:
            from django.db import connection
            with connection.cursor() as cursor:
                cursor.execute(
                    "SET app.current_org = %s", [str(org_id)]
                )

        response = self.get_response(request)

        # Reset to prevent connection pool leakage
        if org_id:
            with connection.cursor() as cursor:
                cursor.execute("RESET app.current_org")

        return response
</code></pre>
<p>The beauty: <strong>your views and serializers don't need to know about tenancy at all.</strong> The ORM just works. Querysets automatically return only the current tenant's data because PostgreSQL filters at the engine level.</p>
<pre><code class="language-python"># views.py — no tenant filtering needed!

class LeadViewSet(viewsets.ModelViewSet):
    serializer_class = LeadSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # This returns ALL leads — but RLS ensures
        # only the current org's leads come back
        return Lead.objects.all().order_by('-created_at')

    def perform_create(self, serializer):
        # org_id is set automatically, and RLS validates
        # that it matches the session variable
        serializer.save(
            org_id=self.request.org.id,
            created_by=self.request.user
        )
</code></pre>
<p>No <code>.filter(org=request.org)</code> scattered across 200 views. No chance of forgetting it in one place and leaking data. The database is the single source of truth for tenant isolation.</p>
<h2>The Full Stack: Why Django + SvelteKit</h2>
<p>A lot of people ask why not Next.js or React. Short answer: I've shipped production apps with all of them, and for a CRM, SvelteKit wins on three fronts:</p>
<ol>
<li><p><strong>Bundle size.</strong> CRMs have dozens of forms, tables, and modals. Svelte compiles away the framework our JS bundle is ~40% smaller than the React equivalent we prototyped.</p>
</li>
<li><p><strong>Reactivity without boilerplate.</strong> Svelte 5's runes (<code>\(state</code>, <code>\)derived</code>) are cleaner than <code>useState</code> + <code>useEffect</code> + <code>useMemo</code>. For a data-heavy app, this matters.</p>
</li>
<li><p><strong>SvelteKit's routing is file-based and simple.</strong> No fighting with App Router vs Pages Router. No server components confusion. It just works.</p>
</li>
</ol>
<p>The full stack:</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Tech</th>
<th>Why</th>
</tr>
</thead>
<tbody><tr>
<td>Backend</td>
<td>Django 5 + DRF</td>
<td>Battle-tested, ORM is excellent for complex data models</td>
</tr>
<tr>
<td>Frontend</td>
<td>SvelteKit 2 + Svelte 5 + TailwindCSS 4</td>
<td>Fast, small, great DX</td>
</tr>
<tr>
<td>Database</td>
<td>PostgreSQL 14+</td>
<td>RLS, JSONB, full-text search — all in one</td>
</tr>
<tr>
<td>Auth</td>
<td>JWT (access + refresh tokens)</td>
<td>Stateless, works with mobile apps</td>
</tr>
<tr>
<td>Background jobs</td>
<td>Celery + Redis</td>
<td>Email, notifications, data imports</td>
</tr>
<tr>
<td>Deployment</td>
<td>Docker Compose</td>
<td>One command: <code>docker compose up</code></td>
</tr>
</tbody></table>
<h2>Performance: RLS vs Schema-Per-Tenant</h2>
<p>Let's talk numbers. These are from our benchmarks with realistic data (10K-100K rows per tenant):</p>
<p><strong>Query performance:</strong> Virtually identical. PostgreSQL's query planner treats RLS policies like additional <code>WHERE</code> clauses. With a proper index on <code>org_id</code>, there's negligible overhead — we measured &lt;1ms difference on 95th percentile queries.</p>
<p><strong>Migration speed:</strong> This is where RLS dominates. One schema means one migration run, regardless of tenant count. 500 tenants? Same 3-second migration as 1 tenant.</p>
<p><strong>Connection pooling:</strong> Standard PgBouncer works perfectly. No <code>search_path</code> switching, no stale state. Each request just sets a session variable and resets it.</p>
<p><strong>Disk usage:</strong> Shared indexes across all tenants. Schema-per-tenant duplicates every index for every tenant. At 500 tenants with 15 tables, that's 7,500 indexes vs. 15.</p>
<p><strong>The tradeoff?</strong> Schema-per-tenant gives you harder isolation boundaries. If a tenant needs a custom column or a different schema, schema-per-tenant handles that natively. With RLS, every tenant shares the same schema. For a CRM where every tenant uses the same data model, this isn't a limitation it's a feature.</p>
<h2>Why MIT and Not AGPL</h2>
<p>This was a deliberate choice. AGPL would have "protected" the project by forcing anyone who modifies it to open-source their changes. But in practice:</p>
<ul>
<li><p><strong>AGPL scares enterprises.</strong> Legal teams see AGPL and close the tab. We wanted adoption.</p>
</li>
<li><p><strong>MIT builds trust.</strong> You can fork it, modify it, sell it, host it. Use it however you want.</p>
</li>
<li><p><strong>Community over control.</strong> The projects with the healthiest ecosystems Svelte, React, Vue, Django itself are permissively licensed. We wanted contributors, not compliance officers.</p>
</li>
</ul>
<p>Our bet: if the product is good enough, people contribute because they want to, not because a license forces them. So far, that bet is paying off.</p>
<h2>Lessons From Running This With Real Clients</h2>
<p>After years of running multi-tenant CRM deployments, here's what I wish someone had told me:</p>
<p><strong>1. Always reset the session variable.</strong> If you set <code>app.current_org</code> and don't reset it, connection pools will serve the wrong tenant's data to the next request. We learned this the hard way. Always reset in a <code>finally</code> block or middleware teardown.</p>
<p><strong>2. Superuser bypasses RLS by default.</strong> PostgreSQL RLS policies don't apply to superusers or table owners unless you use <code>FORCE ROW LEVEL SECURITY</code>. We missed this initially and wondered why our admin panel showed all data. Add <code>FORCE</code> to every table.</p>
<p><strong>3. Test with multiple tenants from day one.</strong> Write a test that creates two orgs, inserts data for both, and asserts that each org can only see its own. Run it in CI. Never skip it.</p>
<p><strong>4. Audit logging needs the org context too.</strong> Your audit trail should capture which org performed which action. Don't rely on application-level logging alone use PostgreSQL triggers that read <code>current_setting('app.current_org')</code>.</p>
<p><strong>5. Data exports are trivially simple.</strong> Need to export all of tenant 42's data? <code>SET app.current_org = '42'; COPY leads_lead TO '/tmp/leads.csv' CSV HEADER;</code> RLS does the filtering for you.</p>
<h2>Getting Started</h2>
<p>BottleCRM runs with a single command:</p>
<pre><code class="language-yaml"># docker-compose.yml (simplified)
services:
  backend:
    build: ./backend
    environment:
      - DATABASE_URL=postgres://crm:crm@db:5432/bottlecrm
      - REDIS_URL=redis://redis:6379
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      - db
      - redis

  frontend:
    build: ./frontend
    environment:
      - PUBLIC_API_URL=http://backend:8000
    ports:
      - "3000:3000"

  db:
    image: postgres:16
    environment:
      - POSTGRES_DB=bottlecrm
      - POSTGRES_USER=crm
      - POSTGRES_PASSWORD=crm
    volumes:
      - pgdata:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine

  celery:
    build: ./backend
    command: celery -A crm worker -l info
    depends_on:
      - db
      - redis

volumes:
  pgdata:
</code></pre>
<pre><code class="language-bash">git clone https://github.com/MicroPyramid/Django-CRM.git
cd Django-CRM
docker compose up
</code></pre>
<p>That's it. Open <code>localhost:3000</code>, create an account, and you've got a production-grade CRM running locally.</p>
<h2>Ship It</h2>
<p>Building BottleCRM taught me that the best multi-tenancy strategy isn't the most clever one, it's the one that lets PostgreSQL do what it's good at. RLS pushes tenant isolation into the database engine where it belongs. Your application code stays clean, your deployments stay fast, and your data stays safe.</p>
<p>If you're building a multi-tenant Django app, seriously consider RLS before reaching for <code>django-tenants</code>. It's less magical, more explicit, and PostgreSQL has been battle-testing this feature since version 9.5.</p>
<hr />
<p><strong>⭐</strong> <a href="https://github.com/MicroPyramid/Django-CRM"><strong>Star Django-CRM on GitHub</strong></a> — 2,100+ stars and growing</p>
<p><strong>🚀</strong> <a href="https://bottlecrm.io"><strong>Try the live demo at bottlecrm.io</strong></a> — free, no credit card</p>
<p><strong>🤝 Contribute</strong> — we're looking for help with the mobile app (Flutter), analytics dashboard, and documentation. Check the issues tab.</p>
<p>Built with 🐍 Django + ⚡ SvelteKit + 🐘 PostgreSQL. MIT Licensed. Free forever.</p>
]]></content:encoded></item></channel></rss>