Render Mermaid Diagrams in Astro
As of Astro 5.5, adding mermaid diagrams to Astro is much simpler.
Install the rehype-mermaid
Plugin
bun add rehype-mermaid
bunx playwright-core install --with-deps chromium
The Playwright Chromium dependency is required by rehype-mermaid
for rendering diagrams during build time.
Note: Cloudflare Pages builds don’t support running programs with elevated permissions (sudo
), which is required for the Playwright Chromium dependency. As a result, I had to switch from Cloudflare Pages to GitHub Actions for building my Astro website.
Configure Astro to Disable Highlighting for the mermaid
language
By default, Astro applies syntax highlighting to all code blocks, which can interfere with Mermaid diagram rendering. To fix this, we need to tell Astro to skip syntax highlighting specifically for Mermaid code blocks, while keeping it enabled for other languages.
//astro.config.mjs
import { defineConfig } from 'astro/config';
import rehypeMermaid from 'rehype-mermaid';
export default defineConfig({
markdown: {
syntaxHighlight: {
excludeLangs: ['mermaid'],
},
rehypePlugins: [rehypeMermaid],
},
});
This configuration does two important things:
- Tells Astro not to apply syntax highlighting to Mermaid code blocks
- Enables the Mermaid diagram rendering plugin
Then, you can create diagrams directly in your Markdown content:
```mermaid
graph TD
A[Start] --> B{Is it working?}
B -->|Yes| C[Great!]
B -->|No| D[Debug]
D --> B
```
This will then render as a diagram in your page.