Mermaid Diagrams
Objective
Produce correct, readable Mermaid diagrams that render identically on GitHub, GitLab, and local tooling. Diagrams should be focused (one concept per diagram), use descriptive labels, and avoid known syntax pitfalls that cause silent rendering failures.
Scope
In-scope:
- All Mermaid diagram types and their syntax
- Diagram selection guidance (which type for which purpose)
- Syntax rules, edge cases, and common pitfalls
- GitHub rendering compatibility
- Image export via the bundled CLI script
- Embedding diagrams in Markdown documentation
Out-of-scope:
- Mermaid.js library internals or custom plugin development
- Non-Mermaid diagramming tools (PlantUML, D2, Graphviz)
- Static site generator integration or theming
Diagram Type Selection
Choose the diagram type that best matches the concept being visualized.
| Diagram type |
Keyword |
Use for |
| Flowchart |
flowchart |
Process flows, decision trees, algorithms, pipelines |
| Sequence |
sequenceDiagram |
API calls, request/response flows, protocol handshakes |
| Class |
classDiagram |
OOP class hierarchies, interface relationships |
| State |
stateDiagram-v2 |
State machines, object lifecycles, feature flags |
| Entity Relationship |
erDiagram |
Database schemas, data model relationships |
| Gantt |
gantt |
Project schedules, timeline planning |
| Pie |
pie |
Proportional breakdowns, usage shares |
| Mindmap |
mindmap |
Brainstorming, topic hierarchies, concept maps |
| Timeline |
timeline |
Chronological events, milestones, release history |
| Gitgraph |
gitGraph |
Branch strategies, merge workflows |
| Quadrant |
quadrantChart |
Priority matrices, risk assessment, categorization |
| Sankey |
sankey-beta |
Flow quantities, resource allocation, energy diagrams |
| XY Chart |
xychart-beta |
Line/bar charts with numeric axes |
| Block |
block-beta |
System block diagrams, architecture boxes |
| Architecture |
architecture-beta |
Cloud architecture, service topology |
| Packet |
packet-beta |
Network packet structure, protocol headers |
| Requirement |
requirementDiagram |
Requirements traceability |
| Kanban |
kanban |
Task boards, workflow stages |
Types marked beta may have evolving syntax. Test rendering on your target platform before committing.
Syntax Fundamentals
Embedding in Markdown
Open a fenced code block with the mermaid language identifier:
```mermaid
flowchart LR
A[Input] --> B[Process] --> C[Output]
```
Direction
Flowcharts and block diagrams accept a direction keyword after the diagram type:
| Direction |
Meaning |
TD or TB |
Top to bottom |
LR |
Left to right |
BT |
Bottom to top |
RL |
Right to left |
Prefer LR for pipelines and data flows. Use TD for hierarchies and trees.
Node Shapes
A[Rectangle] A(Rounded) A([Stadium])
A[[Subroutine]] A[(Cylinder)] A((Circle))
A{Diamond} A{{Hexagon}} A[/Parallelogram/]
A[\Parallelogram\] A[/Trapezoid\] A[\Trapezoid/]
Edge Syntax
A --> B Solid arrow
A --- B Solid line (no arrow)
A -.-> B Dotted arrow
A -.- B Dotted line
A ==> B Thick arrow
A == text ==> B Thick arrow with label
A -- text --> B Solid arrow with label
Place each edge on its own line for readability and reliable parsing.
Subgraphs
flowchart LR
subgraph Backend
API[API Server]
DB[(Database)]
end
subgraph Frontend
UI[Web App]
end
UI --> API --> DB
Rules:
subgraph Name and end must each be on their own line.
- To use spaces in a display name:
subgraph build_pipeline [Build Pipeline].
- Keep nesting shallow (max 2 levels) for reliable GitHub rendering.
Pitfalls and Issues to Avoid
Special Characters in Labels
- Wrap labels containing special characters in double quotes:
A["100% Complete"].
- Avoid smart quotes (
""), em dashes (—), and Unicode arrows (→). Use ASCII equivalents.
- Node IDs must be alphanumeric or use underscores. No spaces or hyphens in IDs.
- Parentheses, brackets, and braces in label text can break parsing. Quote the label.
Text Wrapping
Mermaid does not auto-wrap text inside nodes. For multi-line labels, use <br/>:
A["Line one<br/>Line two<br/>Line three"]
Diagram Size
- Keep diagrams under 15 nodes. Larger diagrams become unreadable and slow to render.
- Split complex systems into multiple focused diagrams rather than one monolithic diagram.
- Add a brief text description before or after the diagram for accessibility.
GitHub Rendering Differences
- GitHub may run an older Mermaid version than the latest release. Beta features (
sankey-beta, xychart-beta, architecture-beta) may not render.
- GitHub strips custom CSS and restricts theme variables. Do not rely on
themeVariables or %%{init:}%% directives for GitHub-hosted documentation.
- Always preview diagrams on GitHub after pushing. The Mermaid Live Editor may render syntax that GitHub rejects.
Arrow and Syntax Errors
- Do not use Unicode arrows (
→, ⇒). Use only ASCII arrow syntax (-->, ==>, -.->)
- Place one statement per line. Multiple edges on a single line may fail to parse.
- Semicolons as statement terminators are supported but discouraged — use line breaks instead.
- Comments use
%% prefix: %% This is a comment.
Theme Compatibility
- Use built-in themes only:
default, dark, forest, neutral.
- Custom colors via
themeVariables are not portable across all renderers.
- For image export, specify the theme via the CLI's
--theme flag rather than embedding %%{init:}%% directives.
Image Export
Use the bundled CLI script to convert .mmd files or Markdown-embedded diagrams to PNG, SVG, or PDF.
See the Related Files section for the script location and usage.
Quick Export
# Single file
node scripts/mermaid-export.mjs input.mmd output.png
# With options
node scripts/mermaid-export.mjs input.mmd output.svg --theme dark --background transparent
# From a Markdown file (extracts all mermaid blocks)
node scripts/mermaid-export.mjs README.md output-dir/ --format png
The script delegates to @mermaid-js/mermaid-cli (mmdc) and handles dependency installation automatically. See the script header for full option documentation.
Official Documentation
Related Files
scripts/mermaid-export.mjs: CLI script for converting Mermaid diagrams to PNG, SVG, or PDF images. Wraps @mermaid-js/mermaid-cli with automatic dependency management.
references/diagram-types.md: Detailed syntax reference for each diagram type with annotated examples.
Constraints
MUST:
- Use the
mermaid language identifier on all Mermaid code fences.
- Keep diagrams under 15 nodes. Split larger concepts across multiple diagrams.
- Use descriptive node labels, not single letters (
Auth Service not A).
- Use ASCII-only characters in node IDs and arrow syntax.
- Quote labels that contain special characters.
- Include a text description near each diagram for accessibility.
- Test diagram rendering on the target platform (especially GitHub) before committing.
MUST NOT:
- Use Unicode arrows, smart quotes, or em dashes in diagram syntax.
- Rely on
%%{init:}%% theme directives for GitHub-hosted documentation.
- Embed more than one concept per diagram.
- Use deeply nested subgraphs (more than 2 levels).
- Place multiple edge statements on a single line.
MAY:
- Use
%%{init:}%% directives for documentation rendered by local or self-hosted tools.
- Use beta diagram types when the target platform supports them.
- Export diagrams to images for platforms that do not support native Mermaid rendering.
1---2name: mermaid-diagrams3description: Use when creating, editing, reviewing, or converting Mermaid diagrams. Covers all diagram types (flowchart, sequence, class, state, ER, gantt, pie, mindmap, timeline, gitgraph, and more), syntax rules, rendering pitfalls, GitHub compatibility, image export via CLI, and best practices for diagrams-as-code in Markdown documentation.4---56# Mermaid Diagrams78## Objective910Produce correct, readable Mermaid diagrams that render identically on GitHub, GitLab, and local tooling. Diagrams should be focused (one concept per diagram), use descriptive labels, and avoid known syntax pitfalls that cause silent rendering failures.1112## Scope1314**In-scope:**1516- All Mermaid diagram types and their syntax17- Diagram selection guidance (which type for which purpose)18- Syntax rules, edge cases, and common pitfalls19- GitHub rendering compatibility20- Image export via the bundled CLI script21- Embedding diagrams in Markdown documentation2223**Out-of-scope:**2425- Mermaid.js library internals or custom plugin development26- Non-Mermaid diagramming tools (PlantUML, D2, Graphviz)27- Static site generator integration or theming2829## Diagram Type Selection3031Choose the diagram type that best matches the concept being visualized.3233| Diagram type | Keyword | Use for |34| --- | --- | --- |35| Flowchart | `flowchart` | Process flows, decision trees, algorithms, pipelines |36| Sequence | `sequenceDiagram` | API calls, request/response flows, protocol handshakes |37| Class | `classDiagram` | OOP class hierarchies, interface relationships |38| State | `stateDiagram-v2` | State machines, object lifecycles, feature flags |39| Entity Relationship | `erDiagram` | Database schemas, data model relationships |40| Gantt | `gantt` | Project schedules, timeline planning |41| Pie | `pie` | Proportional breakdowns, usage shares |42| Mindmap | `mindmap` | Brainstorming, topic hierarchies, concept maps |43| Timeline | `timeline` | Chronological events, milestones, release history |44| Gitgraph | `gitGraph` | Branch strategies, merge workflows |45| Quadrant | `quadrantChart` | Priority matrices, risk assessment, categorization |46| Sankey | `sankey-beta` | Flow quantities, resource allocation, energy diagrams |47| XY Chart | `xychart-beta` | Line/bar charts with numeric axes |48| Block | `block-beta` | System block diagrams, architecture boxes |49| Architecture | `architecture-beta` | Cloud architecture, service topology |50| Packet | `packet-beta` | Network packet structure, protocol headers |51| Requirement | `requirementDiagram` | Requirements traceability |52| Kanban | `kanban` | Task boards, workflow stages |5354Types marked `beta` may have evolving syntax. Test rendering on your target platform before committing.5556## Syntax Fundamentals5758### Embedding in Markdown5960Open a fenced code block with the `mermaid` language identifier:6162````markdown63```mermaid64flowchart LR65 A[Input] --> B[Process] --> C[Output]66```67````6869### Direction7071Flowcharts and block diagrams accept a direction keyword after the diagram type:7273| Direction | Meaning |74| --- | --- |75| `TD` or `TB` | Top to bottom |76| `LR` | Left to right |77| `BT` | Bottom to top |78| `RL` | Right to left |7980Prefer `LR` for pipelines and data flows. Use `TD` for hierarchies and trees.8182### Node Shapes8384```text85A[Rectangle] A(Rounded) A([Stadium])86A[[Subroutine]] A[(Cylinder)] A((Circle))87A{Diamond} A{{Hexagon}} A[/Parallelogram/]88A[\Parallelogram\] A[/Trapezoid\] A[\Trapezoid/]89```9091### Edge Syntax9293```text94A --> B Solid arrow95A --- B Solid line (no arrow)96A -.-> B Dotted arrow97A -.- B Dotted line98A ==> B Thick arrow99A == text ==> B Thick arrow with label100A -- text --> B Solid arrow with label101```102103Place each edge on its own line for readability and reliable parsing.104105### Subgraphs106107```mermaid108flowchart LR109 subgraph Backend110 API[API Server]111 DB[(Database)]112 end113 subgraph Frontend114 UI[Web App]115 end116 UI --> API --> DB117```118119Rules:120121- `subgraph Name` and `end` must each be on their own line.122- To use spaces in a display name: `subgraph build_pipeline [Build Pipeline]`.123- Keep nesting shallow (max 2 levels) for reliable GitHub rendering.124125## Pitfalls and Issues to Avoid126127### Special Characters in Labels128129- Wrap labels containing special characters in double quotes: `A["100% Complete"]`.130- Avoid smart quotes (`""`), em dashes (`—`), and Unicode arrows (`→`). Use ASCII equivalents.131- Node IDs must be alphanumeric or use underscores. No spaces or hyphens in IDs.132- Parentheses, brackets, and braces in label text can break parsing. Quote the label.133134### Text Wrapping135136Mermaid does not auto-wrap text inside nodes. For multi-line labels, use `<br/>`:137138```text139A["Line one<br/>Line two<br/>Line three"]140```141142### Diagram Size143144- Keep diagrams under 15 nodes. Larger diagrams become unreadable and slow to render.145- Split complex systems into multiple focused diagrams rather than one monolithic diagram.146- Add a brief text description before or after the diagram for accessibility.147148### GitHub Rendering Differences149150- GitHub may run an older Mermaid version than the latest release. Beta features (`sankey-beta`, `xychart-beta`, `architecture-beta`) may not render.151- GitHub strips custom CSS and restricts theme variables. Do not rely on `themeVariables` or `%%{init:}%%` directives for GitHub-hosted documentation.152- Always preview diagrams on GitHub after pushing. The Mermaid Live Editor may render syntax that GitHub rejects.153154### Arrow and Syntax Errors155156- Do not use Unicode arrows (`→`, `⇒`). Use only ASCII arrow syntax (`-->`, `==>`, `-.->`)157- Place one statement per line. Multiple edges on a single line may fail to parse.158- Semicolons as statement terminators are supported but discouraged — use line breaks instead.159- Comments use `%%` prefix: `%% This is a comment`.160161### Theme Compatibility162163- Use built-in themes only: `default`, `dark`, `forest`, `neutral`.164- Custom colors via `themeVariables` are not portable across all renderers.165- For image export, specify the theme via the CLI's `--theme` flag rather than embedding `%%{init:}%%` directives.166167## Image Export168169Use the bundled CLI script to convert `.mmd` files or Markdown-embedded diagrams to PNG, SVG, or PDF.170171See the [Related Files](#related-files) section for the script location and usage.172173### Quick Export174175```bash176# Single file177node scripts/mermaid-export.mjs input.mmd output.png178179# With options180node scripts/mermaid-export.mjs input.mmd output.svg --theme dark --background transparent181182# From a Markdown file (extracts all mermaid blocks)183node scripts/mermaid-export.mjs README.md output-dir/ --format png184```185186The script delegates to `@mermaid-js/mermaid-cli` (mmdc) and handles dependency installation automatically. See the script header for full option documentation.187188## Official Documentation189190| Resource | URL |191| --- | --- |192| Mermaid syntax reference | <https://mermaid.js.org/intro/syntax-reference.html> |193| Mermaid Live Editor | <https://mermaid.live/> |194| GitHub Mermaid support | <https://github.blog/developer-skills/github/include-diagrams-markdown-files-mermaid/> |195| Mermaid CLI (mmdc) | <https://github.com/mermaid-js/mermaid-cli> |196| Diagram type documentation | <https://mermaid.js.org/syntax/flowchart.html> (replace `flowchart` with diagram type) |197198## Related Files199200- `scripts/mermaid-export.mjs`: CLI script for converting Mermaid diagrams to PNG, SVG, or PDF images. Wraps `@mermaid-js/mermaid-cli` with automatic dependency management.201- `references/diagram-types.md`: Detailed syntax reference for each diagram type with annotated examples.202203## Constraints204205**MUST:**206207- Use the `mermaid` language identifier on all Mermaid code fences.208- Keep diagrams under 15 nodes. Split larger concepts across multiple diagrams.209- Use descriptive node labels, not single letters (`Auth Service` not `A`).210- Use ASCII-only characters in node IDs and arrow syntax.211- Quote labels that contain special characters.212- Include a text description near each diagram for accessibility.213- Test diagram rendering on the target platform (especially GitHub) before committing.214215**MUST NOT:**216217- Use Unicode arrows, smart quotes, or em dashes in diagram syntax.218- Rely on `%%{init:}%%` theme directives for GitHub-hosted documentation.219- Embed more than one concept per diagram.220- Use deeply nested subgraphs (more than 2 levels).221- Place multiple edge statements on a single line.222223**MAY:**224225- Use `%%{init:}%%` directives for documentation rendered by local or self-hosted tools.226- Use beta diagram types when the target platform supports them.227- Export diagrams to images for platforms that do not support native Mermaid rendering.