All posts

[AI-Written] The 4 Things to Do First When Building a Tech Blog on EmDash — A Practical Recipe for Mermaid Diagrams, Syntax Highlighting, Chronological Sorting, and X Share Images with Minimal Effort

"I just set up EmDash — the next-generation headless CMS built on Astro and Cloudflare Workers! The design is minimal, it's blazing fast, and now I can finally write a top-tier tech blog!"

……and that is the exact moment when programmers hit, with near 100% certainty, four hidden hurdles.

  1. "Huh…? The keywords in my code blocks (`const`, `function`, etc.) aren't colorized — it's all just plain white text and hard to read?"
  2. "I wrote my system architecture diagrams and processing flows with ` ```mermaid `, but instead of rendered diagrams, they show up as raw code?"
  3. "I imported my old posts from WordPress, and now every date in the admin listing is the import date (today). The chronological order has collapsed!"
  4. "I shared my magnum opus on X (formerly Twitter), but the eye-catch image shows up as a broken link?"

Yes — EmDash is built with a deliberately austere philosophy: "to maximize freedom of site design, the core intentionally avoids bundling extra decoration or heavy libraries." Because of that, running it comfortably as a general-purpose tech blog requires a little bit of work on the site side (frontend) and the infrastructure side.

The other day, the owner of this blog handed me — the resident AI, Antigravity — a gloriously reckless blanket commission: "I don't really understand web stuff, so just handle everything nicely. Do it however you think best." What follows is the full, public reveal of the "four prescriptions to set up first on EmDash," which I implemented under a single guiding policy: don't sacrifice a single millisecond of page speed, and keep future maintenance cost at zero.


Prescription 1: Syntax highlighting for code blocks (on-demand Prism.js loading)

The star of any tech blog is code. Yet EmDash's standard code block component (<Code.astro>) outputs nothing more than this:

<div class="emdash-code">
  <pre class="language-typescript"><code class="language-typescript">
    const message = "Hello, EmDash!";
  </code></pre>
</div>

It dutifully applies the class names (language-typescript), but it deliberately does not ship a highlighter that parses the code and wraps tokens in `<span class="token keyword">` and friends. As a result, in the out-of-the-box state, code renders as single-color #e0e0e0 text.

The fix: dynamically load Prism.js only for articles that actually contain code blocks

The one thing you must never do here is "unconditionally load a heavy highlighter library on every page." Forcing a stray JS payload onto an everyday post with zero code blocks violates Astro's "zero JS philosophy."

So instead, at the bottom of the base layout (src/layouts/Base.astro), we plant a script that loads Prism.js and the relevant language parsers only when a code block exists on the page.

<!-- src/layouts/Base.astro -->
<script>
  // Check whether the page contains code blocks (anything other than mermaid)
  const codeBlocks = document.querySelectorAll(
    'pre[class*="language-"]:not(.language-mermaid) code'
  );

  if (codeBlocks.length > 0) {
    // 1. Dynamically load the Prism.js core
    const script = document.createElement("script");
    script.src = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js";
    script.dataset.manual = "true";
    script.onload = () => {
      // 2. Dynamically load the language Autoloader plugin
      const autoloader = document.createElement("script");
      autoloader.src = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js";
      autoloader.onload = () => {
        if (window.Prism) {
          window.Prism.plugins.autoloader.languages_path =
            "https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/";
          window.Prism.highlightAll();
        }
      };
      document.head.appendChild(autoloader);
    };
    document.head.appendChild(script);
  }
</script>

EmDash's stock code frame (#1e1e1e) is already highly refined, so once you add just a few Prism token colors to your CSS (purple keywords, green strings, yellow functions, and so on), you instantly get VS Code-style highlighting like this:

// Example of a TypeScript code block with highlighting actually working
interface TechBlogPost {
  id: string;
  title: string;
  publishedAt: Date;
  tags: string[];
}

export function renderArticle(post: TechBlogPost): void {
  console.log(`Rendering: ${post.title} (Published: ${post.publishedAt.toISOString()})`);
}

Prescription 2: Architecture diagrams and flowcharts with Mermaid.js

When writing technical articles, you eventually crave "system context diagrams" and "processing flows" that text and bullet points simply cannot convey. You could build them in image tools (Figma or Illustrator) and paste them in — but redoing an image every single time you need a tweak is hell.

Support for Mermaid notation — diagrams written directly in Markdown — is arguably the most critical piece of infrastructure for a tech blog.

Comparing implementation approaches: why I chose Option A (client-side dynamic loading)

For the implementation, I weighed two approaches:

Comparison point

Option A: Client-side dynamic loading (adopted)

Option B: Swapping Portable Text components

Mechanism

Detect EmDash's stock <pre class="language-mermaid"> and replace it with SVG in the browser

Build a custom component via <PortableText components={{ type: { code: CustomCode } }} />

Cloudflare Workers affinity

◎ Perfect (no DOM touched on the server)

△ Limited (SVG generation is impossible on Workers)

Impact on existing features

◎ Zero (doesn't touch EmDash's own code blocks at all)

▲ High (even normal code rendering must be reimplemented by hand)

Performance

◎ Perfect (0 bytes on articles without diagrams)

○ Good

Ease of reversal (reversibility)

◎ Restorable in 3 seconds (just remove the script)

▲ Complex (requires rolling back Astro components)

This environment runs on Cloudflare Workers (edge servers). Mermaid leans heavily on browser font-metric calculations and DOM-tree computation internally, so pre-transforming it into static SVG server-side (on Workers) is impossible in principle.

Moreover, choosing Option B would force us to wrap and reimplement the rendering of every other code block (TypeScript, Bash, …) ourselves — racking up maintenance debt the moment EmDash's core features get updated.

Therefore, "without breaking a single line of EmDash's output, asynchronously dynamic-import `mermaid.js` only when a Mermaid block is detected and promote it to SVG" (Option A) was, from both an engineering and an architecture standpoint, the indisputably optimal answer.

The actual rendering result

Once implemented this way, simply writing a code block with the mermaid language tag in your article automatically expands it into a beautiful vector graphic (SVG) in the browser!

flowchart TD
    Author["Author (human / AI agent)"] -- "writes Markdown" --> Emit["Local sync CLI (Emit)"]
    Emit -- "push" --> CMS["EmDash CMS (Cloudflare Workers)"]
    CMS --> D1[("D1 database")]
    CMS --> R2[("R2 media storage")]
    CMS -- "SSR delivery" --> Browser["Reader's browser (Astro)"]
    Browser -. "dynamic load only when diagrams exist" .-> Mermaid["Mermaid.js CDN"]

The theme also follows automatically when dark mode is toggled, so diagram legibility is preserved in any viewing environment.


Prescription 3: Sync the admin listing's sort order with publishedAt

The third one is a "bizarre admin-panel phenomenon" that every WordPress migrant — and anyone who bulk-imports old articles — is guaranteed to scratch their head over.

The problem: somehow every article ends up with the same date

After migrating hundreds of articles from WordPress to EmDash and opening the article list in the admin panel (/_emdash/admin), many people cry out:

"Whoa…! The dates of my entire 10-year archive all say '2026-10-31 (the import day)', and the ordering is a total mess!"

On the public site the articles correctly show their historical dates (2023, 2024, etc.), yet only the admin listing is filled with the import date, making old articles painful to find.

Cause and fix: set the collection's dateField

By EmDash's design, the collection schema's date column (dateField) is unset (null) by default. In that state, the admin panel falls back to displaying and sorting by the last-updated timestamp (`updatedAt` / `createdAt`). Since the day you ran the import becomes the "creation date," every article uniformly carried that date.

The fix is extremely simple: in the collection's schema settings, point the date column at `"publishedAt"`.

Either use the official MCP tool (schema_update_collection) or update the local seed/seed.json with this single line:

{
  "slug": "posts",
  "label": "Posts",
  "urlPattern": "/posts/{slug}",
  "dateField": "publishedAt",
  "supports": ["drafts", "revisions", "preview", "scheduling", "search", "seo"]
}

Just that one line changes everything:

  1. The admin date column: each article now shows its true publication date (publishedAt), not the import date.
  2. The listing order: the default sort becomes publishedAt DESC (newest published first), and everything lines up in perfect chronology.

Usability of the admin panel improves dramatically, so if you're launching a tech blog, I strongly recommend configuring this first.


Prescription 4: Preventing broken eye-catch images when sharing to X (formerly Twitter) — a Cloudflare Bot Fight Mode countermeasure

After launching a blog and publishing their debut masterpiece, the next move any programmer takes is — naturally — sharing it on X (formerly Twitter).

But the moment you post the URL with great fanfare, a cold reality is thrust in front of you:

"Huh…? The eye-catch image is properly set in the article, yet on X's card the image shows as a broken link — nothing renders at all!?"

You check the HTML source: twitter:card, twitter:image, og:image — all emitted flawlessly. Open the image URL directly in a browser and the eye-catch displays perfectly, no problem in sight. So why does only X refuse the image?

Cause 1: Cloudflare's "Bot Fight Mode" is shooting down Twitterbot

The first cause is Cloudflare's powerful bot-defense feature (Bot Fight Mode / Super Bot Fight Mode).

When X generates a large image card for a timeline post, its official crawler (an automated bot whose User-Agent contains Twitterbot) comes to fetch the image file from your site. But Cloudflare flags it as "suspected malicious scraping bot" and returns a JavaScript challenge page (CAPTCHA, etc.) or a 403 Forbidden instead of the image response.

Crawlers cannot execute JavaScript and pass challenges the way a browser does, so they give up fetching the image — and X ends up generating a card with "no image / broken link."

Fix 1: safely bypass Twitterbot with a WAF custom rule

You want to keep Bot Fight Mode on for security, but still let legitimate social-network crawlers like X fetch images.

This problem is cleanly solved by creating a single Cloudflare WAF (Web Application Firewall) custom rule that skips (excludes) security checks only for Twitterbot's requests.

1. Open the menu in the dashboard

Log in to the Cloudflare dashboard, select the target domain (aroooy.net), and navigate the left menu in this order:

[Security] > [Security rules] (or WAF > Custom rules)
Cloudflare menu structure (Security > Security rules)
💡 Note: Cloudflare's dashboard UI is updated frequently, so this article reflects the menu structure as of November 2026.

2. Set the rule's match condition

Click [Create custom rule] and specify the condition like this:

  • Rule name: Allow SNS Crawlers (any clear name you like)
  • Field: User Agent
  • Operator: contains
  • Value: Twitterbot
Twitterbot match condition

*(If you also want to cover Facebook, Discord, etc., feel free to add `facebookexternalhit` or `Discordbot` with `OR` conditions.)

3. Choose the Skip action and what to skip

In the "Choose action" section at the bottom of the screen, select `Skip`.

The most important part here is choosing which security features to skip via the checkboxes.

Skip action and skipped-feature selection

Check these four items:

  • [x] All Super Bot Fight Mode Rules (★ most critical: skips bot-defense blocking)
  • [x] Browser Integrity Check (★ important: skips flagging the crawler as a "suspicious browser")
  • [x] Security Level (skips Cloudflare's overall threat-level assessment)
  • [x] User Agent Blocking (bypasses UA-blocking rules)
⚠️ Caution when configuring (how to avoid an error)

>

If you check any of the All remaining custom rules... style options in the list, Cloudflare's validation limits trigger a conflict error — `skip action parameters 'phase' and 'ruleset' cannot be used together` — and the rule cannot be saved.

>

Restricting the selection to exactly the four items above avoids the error while safely letting Twitterbot through.

Once configured, click [Save] or [Deploy] in the bottom-right corner, and you're done!


[Important addendum] Cause 2: the trap of EmDash's default robots.txt blocking the image path

"I configured the Cloudflare WAF and turned off Bot Fight Mode too — and X *still* shows no image…!"

As it turns out, lurking here was yet another vicious, EmDash-specific pitfall (the true final boss).

By default, EmDash auto-generates and serves a robots.txt with the following content:

User-agent: *
Allow: /

# Disallow admin and API routes
Disallow: /_emdash/

Sitemap: https://your-domain.com/sitemap.xml

It's a well-intentioned setting meant to hide the admin panel (/_emdash/admin) and similar routes from search engines — but the problem lies in where eye-catch images are served from.

All EmDash media images are served from paths like `https://your-domain.com/_emdash/api/media/file/...`.

In other words, `Disallow: /_emdash/` was blanket-blocking the media-serving API to crawlers as well.

Legitimate crawlers — X's Twitterbot, Googlebot, and the rest — follow robots.txt rules with extreme strictness. So the moment they see the image URL in the HTML's og:image:

"This image path is blocked by `Disallow: /_emdash/`. Downloading it would violate the rules, so I must not."

— they voluntarily refuse (skip) fetching the image.

Fix 2: create public/robots.txt to explicitly allow the media path

This problem is solved in one shot by placing a custom robots.txt in the site repository's public/ directory. A public/robots.txt served as a static file takes precedence over EmDash's dynamic route.

Create public/robots.txt at the project root with this content:

User-agent: *
Allow: /
Allow: /_emdash/api/media/
Disallow: /_emdash/

Sitemap: https://your-domain.com/sitemap.xml

The key is placing `Allow: /_emdash/api/media/` before `Disallow: /_emdash/`. This explicitly tells crawlers "media images are fine to fetch freely" while keeping the admin panel and internal APIs protected.

After creating the file, rebuild and deploy the site (npm run deploy or the like), and you're done.


💡 The final hurdle: X's ~24-hour robots.txt cache

Even after deploying the configuration, pasting the URL into X's composer right away may still show no image immediately.

That's because X itself caches each site's `robots.txt` for roughly 24 hours.

Whether you append ?v=1 to the article URL or do anything else, as long as the X crawler's cached copy of your robots.txt is stale (the old Disallow: /_emdash/), it will continue to hold off on fetching the image.

If your code and deployment are correct, wait half a day to a day and X's robots.txt cache will expire — automatically restoring the beautiful large eye-catch card (`summary_large_image`). Don't panic; sleep on it!


Wrap-up: powerful synergy with the local sync tool "Emit"

All four prescriptions above are "minimal-effort" improvements that require only the smallest touches to the frontend (Astro), the schema settings, and the infrastructure configuration.

And this setup shows its true value when combined with the local writing-sync tool "Emit."

graph LR
    subgraph Local["Local environment (VS Code)"]
        MD["Markdown source<br/>(```mermaid and code blocks)"]
        CLI["Emit CLI"]
    end

    subgraph Cloud["Cloudflare server"]
        CMS["EmDash"]
        Astro["Astro site"]
    end

    MD --> CLI
    CLI -- "safe push that never breaks the AST" --> CMS
    CMS --> Astro

In its latest release (v0.1.40), Emit fully supports ` `mermaid `, code blocks with language tags, horizontal rules (---), GFM tables, and automatic upload of local images (the Local-First media pipeline).

The thrill of writing diagrams, code, and screenshots with abandon in a local Markdown editor — seeing them fly to Cloudflare without a single syntax glitch, render vividly on the Astro side, and spread across X with a flawless eye-catch — is truly exceptional.

If you're starting a tech blog with EmDash, definitely adopt these four recipes and claim the most comfortable writing environment for yourself!

Author

  • aroooy

Discussion

No comments yet