MermaidJS Diagramming for GitHub Markdown
Teaches AI models to write clean, well-structured MermaidJS diagrams that render beautifully on GitHub's native Markdown viewer. Covers diagram type selection, syntax best practices, GitHub-specific constraints, and common pitfalls across 10+ diagram types — flowcharts, sequence diagrams, Gantt charts, mindmaps, and more.
TL;DR Checklist
When to Use
Use this skill when:
- Writing architecture documentation that needs a system diagram showing how components interact
- Creating a README with a CI/CD pipeline flowchart, data flow diagram, or project structure overview
- Documenting a sequence of API calls, message exchanges, or protocol interactions in an issue or PR
- Building project timelines or roadmaps with Gantt charts in project Wikis
- Adding version control history visualizations with Git graphs in changelogs or release notes
- Explaining entity relationships (ER diagrams) or class hierarchies in design documents
- Visualizing user journeys or state machines for feature documentation
- Creating mindmaps or timeline diagrams for technical proposals or ADRs
When NOT to Use
Avoid this skill for:
- Complex UML class diagrams with 30+ classes and dense relationships — Mermaid's class diagram support is limited; use PlantUML or a dedicated UML tool instead
- Pixel-perfect diagrams where exact spacing, font sizes, or alignment matter — Mermaid uses auto-layout and you cannot fine-tune positions
- Diagrams that need interactivity (click events, tooltips, zoom/pan) — GitHub strips all interactive features; use a standalone Mermaid renderer or an image-based alternative
- Diagrams over ~50KB in source size — GitHub may fail to render large blocks
- Color-coded diagrams where meaning depends on hue alone — GitHub's dark/light mode may invert or reduce contrast; add text labels as a backup
Core Workflow
Choose the Right Diagram Type — Match the concept you're visualizing to the correct Mermaid diagram type:
- Processes, pipelines, decision trees →
flowchart
- API calls, message passing, time-ordered interactions →
sequenceDiagram
- State machines, UI flow →
stateDiagram-v2
- Class hierarchies, data models →
classDiagram
- Entity relationships →
erDiagram
- Project timelines, schedules →
gantt
- Git branches, merges, history →
gitGraph
- Hierarchical ideas, brainstorming →
mindmap
- Chronological events →
timeline
- Quadrant-based analysis (SWOT, priority) →
quadrantChart
- Software architecture (C4 model) →
C4Context, C4Container, C4Component
- Proportions, shares →
pie
- User goals and steps →
journey
- Technical requirements traceability →
requirementDiagram
- Flow/category relationships →
block
- Data flow between categories →
sankey
- X-Y data plotting →
xyChart
Checkpoint: If you can describe your diagram in one sentence as "X shows how Y does Z" the type is probably right. If you need three sentences, split into two diagrams.
Plan the Layout Direction — Choose the layout that matches your narrative flow:
- TD (top-down) — Hierarchies, sequential processes, decision trees, anything with 3+ layers. Readers scan top-to-bottom naturally.
- LR (left-right) — Timelines, simple pipelines (2–4 stages), before/after comparisons, horizontal flows. Easier to read for wide-but-shallow structures.
- Direction per subgraph — Use
direction TB or direction LR inside subgraphs to mix layouts for complex diagrams.
Checkpoint: If your diagram has more vertical depth than horizontal width, use TD. If it's wider than tall, use LR.
Structure Nodes with Descriptive IDs — Use meaningful, CamelCase IDs that document themselves:
%% ✅ GOOD — IDs describe the component
flowchart TD
AuthService --> Database
AuthService --> CacheLayer
%% ❌ BAD — IDs are meaningless
flowchart TD
A1 --> B2
A1 --> C3
- Use
%% comments to document parts of the diagram for future maintainers
- Keep labels under ~25 characters when possible; use
<br/> for longer text
- Use the same ID style (PascalCase, camelCase, or kebab-case) consistently within a document
Add Edge Labels for Clarity — Every edge that represents a meaningful transition gets a label:
flowchart LR
Client -- "sends request" --> API
API -- "validates token" --> Auth
API -- "queries data" --> Database
- Label syntax:
-- "label text" --> or --|label text|--> for short labels
- Without labels, readers must guess why edges exist — label non-obvious transitions
- Edge labels should be short phrases (under 30 characters) when possible
Test in the Mermaid Live Editor — Before committing, paste the entire block into mermaid.live:
- Verify the diagram renders without errors
- Check that long labels don't overflow nodes
- Confirm layout direction produces a readable arrangement
- Toggle GitHub's light/dark mode (via browser dev tools) to verify contrast works in both
- If the diagram fails to render, check for: Unicode characters, missing subgraph
end keywords, unmatched quotes, or IDs with spaces
Diagram Type Reference
| Type |
Best Use Case |
GitHub Notes |
Example |
flowchart |
Processes, pipelines, decision trees, architecture flows |
Most common type; flowchart preferred over deprecated graph |
CI/CD pipeline with build → test → deploy stages |
sequenceDiagram |
API calls, time-ordered interactions, message passing |
Auto-numbers participants; use actor for human roles |
Client → Auth server → API → Database request flow |
classDiagram |
Data models, class hierarchies, interface contracts |
Limited to ~15 classes before layout gets crowded |
User, Order, Product with relationships and cardinality |
stateDiagram-v2 |
State machines, UI workflows, lifecycle management |
Use [*] for start/end states |
Order lifecycle: Created → Paid → Shipped → Delivered |
erDiagram |
Entity-relationship models, database schemas |
Supports cardinality notation; keep under 10 entities |
Customers, Orders, Products with ` |
gantt |
Project timelines, schedules, release planning |
Date format: YYYY-MM-DD; use crit for critical path |
Sprint timeline with epics, tasks, and milestones |
pie |
Proportions, market share, resource allocation |
Simple format; titles shown as legend |
Language usage: 60% TypeScript, 25% Python, 15% Go |
gitGraph |
Branch strategies, merge workflows, release history |
Branches auto-order by first commit; use cherry-pick |
Feature branch → develop → main with release tags |
mindmap |
Brainstorming, knowledge hierarchies, outlines |
Indentation-driven syntax; no edge labels |
Project architecture with backend, frontend, infra branches |
timeline |
Chronological events, roadmaps, histories |
Sections group related events; limited styling |
Product roadmap: Q1 MVP → Q2 Beta → Q3 GA |
quadrantChart |
Prioritization matrices, SWOT analysis, portfolio |
Points positioned by X/Y values (0–1 range); quadrant labels in config |
Feature priority: effort vs impact |
C4Context |
System context diagrams (C4 model) |
Uses Person and System boundaries; good for high-level architecture |
User → System A → System B interactions |
block |
Category-based flow diagrams |
Columns group related blocks; simple structure |
Tech stack: Languages, Frameworks, Tools in columns |
journey |
User experience flows, task completion steps |
Auto-scales; tasks listed in order with scores |
User onboarding: signup → verify → dashboard |
GitHub Rendering Guide
Code Fence
Use lowercase ```mermaid — GitHub only renders lowercase. Uppercase ```Mermaid or ```mmd will not render.
<!-- ✅ WORKS on GitHub -->
```mermaid
flowchart TD
A --> B
flowchart TD
A --> B
### Feature Restrictions
GitHub's native Mermaid renderer removes or ignores certain features. Know these limitations before you write:
| Feature | GitHub Support | Workaround |
|---------|---------------|------------|
| Click events (`click A callback`) | ❌ Stripped | Add text links outside the diagram instead |
| Tooltips (title attribute on nodes) | ❌ Stripped | Add explanation in surrounding prose |
| Theme config via `%%{init:...}` | ⚠️ Config ignored | GitHub uses system light/dark mode; test both |
| `fontSize`, `fontFamily` in config | ⚠️ Partially respected | Keep labels short — default font is always readable |
| Markdown strings (`"..."`) | ✅ Supported | Use for bold/italic/`code` in labels |
| Subgraph styling | ✅ Supported | Use `style` or `classDef` for consistent coloring |
### Size Limit
Diagrams over approximately **50KB** in source text may fail to render on GitHub. As a rule of thumb:
- Keep diagrams under 20–25 nodes
- Keep labels under ~25 characters when possible
- If you need more nodes, split into multiple smaller diagrams that each cover one concept
- Diagrams over 50KB are silently dropped — you get no error message
### Theme Adaptation
GitHub renders Mermaid in the **viewer's system theme** (light or dark mode). You cannot force a specific theme. Design diagrams that work in both:
- Do **not** rely on color alone to convey meaning — always add text labels or patterns
- Use high-contrast combinations (dark text on light backgrounds, light text on dark backgrounds)
- Test in both modes by toggling your OS/browser theme before pushing
### Testing Protocol
Before committing any Mermaid diagram:
1. Paste the full code block into [mermaid.live](https://mermaid.live) — fix any parse errors
2. Copy the rendered output as a PNG and verify it reads well at a glance
3. Toggle your system theme and re-check contrast
4. If the diagram is complex, ask a colleague to describe what they see in 1–2 sentences — if they can't, simplify
---
## Syntax Reference
### Node Shapes
| Shape | Syntax | Example |
|-------|--------|---------|
| Default rectangle | `id[label]` | `Server[Web Server]` |
| Rounded rectangle | `id(label)` | `API(API Gateway)` |
| Stadium (pill shape) | `id([label])` | `Start([Begin Process])` |
| Rhombus (decision) | `id{label}` | `Auth{Is Valid?}` |
| Parallelogram | `id[\\label\\]` | `Input[\\Parse Data\\]` |
| Trapezoid | `id[/label\\]` | `Service[/Transform\\]` |
| Double circle | `id(((label)))` | `End(((System Halt)))` |
| Asymmetric | `id>label]` | `Output>Result]` |
| Hexagon | `id{{label}}` | `Routing{{Load Balance}}` |
### Edge Styles
| Style | Syntax | Use Case |
|-------|--------|----------|
| Solid arrow | `-->` | Default flow, data passing |
| Thick arrow | `==>` | Primary/critical path |
| Dotted arrow | `-.->` | Optional/monitoring/async flow |
| Open circle | `--o` | UML aggregation or "uses" |
| Cross | `--x` | Error path, termination |
| Bidirectional | `<-->` | Two-way communication |
| Label (inline) | `-- "text" -->` | Standard edge labels |
| Label (short) | `--\|text\|-->` | Compact labels |
### Subgraph Structure
Wrap related nodes in a `subgraph` block with an optional `direction` override:
```mermaid
flowchart TD
subgraph Frontend["Frontend Layer"]
direction LR
A[React App] --> B[API Client]
end
subgraph Backend["Backend Services"]
direction TB
C[Auth Service] --> D[Database]
C --> E[Cache]
end
B --> C
Rules:
- Every
subgraph needs a closing end keyword — forgetting end is the most common Mermaid syntax error
- Use
subgraph Name["Display Name"] if the display name differs from the ID or contains special characters
- Direction override (
direction TB/LR) is optional — without it, the subgraph inherits the parent's direction
Comments
Use %% for single-line comments. Comments are ignored by the renderer but visible in source:
%% This diagram shows the user authentication flow
flowchart TD
%% Entry point
Login --> Auth{Valid Credentials?}
Auth -- Yes --> Dashboard
Auth -- No --> LoginError
Styling with classDef and style
Apply CSS-like classes to nodes for consistent visual grouping:
flowchart TD
classDef primary fill:#e1f5fe,stroke:#01579b,stroke-width:2px
classDef danger fill:#ffebee,stroke:#b71c1c
A[Login] --> B[Dashboard]
C[Error Handler] --> D[Fallback]
class A,B primary
class C,D danger
Alternatively, use inline style for one-off nodes:
flowchart TD
A[Critical Component] --> B[Normal Component]
style A fill:#ffebee,stroke:#c62828,stroke-width:4px
Markdown Strings for Rich Labels
Use double-quoted markdown strings to include bold, italic, or code formatting in node labels:
flowchart LR
A["**Build** the _package_"] --> B["Run `npm test`"]
Supported formatting inside markdown strings: **bold**, *italic*, `code`.
Line breaks inside markdown strings: use <br/> not \n.
Diagram Configuration (YAML Frontmatter)
Set global rendering options with a YAML block at the top of the diagram:
---
config:
theme: neutral
flowchart:
curveBasis: 0.3
---
flowchart TD
A --> B
Available themes: default, forest, dark, neutral, base.
Use base as a starting point for custom themes with themeVariables.
Implementation Patterns
Pattern 1: Deployment Pipeline Flowchart
A top-down flowchart showing a CI/CD deployment pipeline with subgraphs for each stage. Uses TD direction for the natural reading flow from commit to production.
---
config:
theme: neutral
---
flowchart TD
subgraph Source["Source Control"]
direction LR
Dev[Developer] --> PR[Pull Request]
PR --> Review[Code Review]
Review --> Merge[Merge to Main]
end
subgraph CI["Continuous Integration"]
direction TB
Merge --> Lint[Lint & Type Check]
Lint --> Test[Run Tests]
Test --> Build[Build Artifact]
end
subgraph CD["Continuous Deployment"]
direction TB
Build --> Staging[Deploy to Staging]
Staging --> E2E[E2E Tests]
E2E --> Approve{Approved?}
Approve -- Yes --> Prod[Deploy to Production]
Approve -- No --> Rollback[Rollback]
end
%% Cross-stage styling
classDef ci fill:#e3f2fd,stroke:#1565c0
classDef cd fill:#e8f5e9,stroke:#2e7d32
classDef gate fill:#fff3e0,stroke:#e65100
class Lint,Test,Build ci
class Staging,E2E,Prod cd
class Approve,Rollback gate
Key design choices:
- Three subgraphs create visual separation between source control, CI, and CD stages
direction LR in Source keeps the PR flow compact horizontally
- A decision rhombus (
Approve) marks the manual gating step
- Color classes distinguish CI (blue), CD (green), and gates (orange)
- Edge labels on the gating paths explain the two outcomes
Pattern 2: API Interaction Sequence Diagram
A sequence diagram showing how a client, auth service, API gateway, and database interact during a token-based request. Reads left-to-right as time progresses downward.
sequenceDiagram
actor User
participant Client as Web Client
participant Auth as Auth Service
participant API as API Gateway
participant DB as Database
User->>Client: Submit credentials
Client->>Auth: POST /auth/token
Auth->>Auth: Validate credentials
Auth-->>Client: Return JWT token
Note over Client,Auth: Token cached for 15 minutes
Client->>API: GET /api/resource<br/>Authorization: Bearer JWT
API->>Auth: Verify token signature
Auth-->>API: Token valid (payload)
API->>DB: SELECT * FROM resources
DB-->>API: Return results
API-->>Client: 200 OK + JSON body
Client-->>User: Display resources
alt Token Expired
Client->>Auth: POST /auth/refresh
Auth-->>Client: New JWT token
end
Key design choices:
actor User distinguishes the human role from system participants
- Dotted lines (
-->>) for responses, solid lines (->>) for requests — standard convention
Note over documents the token caching behavior inline
<br/> in the API request label keeps the readable content on one line
alt block handles the token refresh edge case without cluttering the main flow
Pattern 3: Before/After Comparison
Two subgraphs side by side (LR direction) comparing a naive architecture against an improved one. Useful for RFCs, ADRs, or refactoring proposals.
---
config:
theme: neutral
---
flowchart LR
subgraph Before["Before: Monolithic"]
direction TB
Monolith[Single App Server]
MonolithDB[(Single Database)]
Monolith --> MonolithDB
Monolith --- Monolith
end
subgraph After["After: Microservices"]
direction TB
API[API Gateway]
Users[User Service]
Orders[Order Service]
Notify[Notification Service]
UserDB[(User DB)]
OrderDB[(Order DB)]
API --> Users
API --> Orders
Users --> UserDB
Orders --> OrderDB
Orders -.-> Notify
end
style Before fill:#ffebee,stroke:#c62828,stroke-width:2px,stroke-dasharray: 5 5
style After fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
Key design choices:
- LR layout places both architectures side by side for easy visual comparison
- Red dashed border on "Before" signals it's the problem state; green solid on "After" signals improvement
- The microservices subgraph uses the same general structure but adds new services
- Dotted edge from Orders to Notify indicates an async/eventual interaction
- Restrained node count (6 in After) keeps the comparison readable
Pattern 4: Composition Diagram with Mixed Layout
A complex architecture diagram that combines TD and LR directions in nested subgraphs. Shows how direction directives can create readable multi-region layouts.
---
config:
theme: base
themeVariables:
primaryColor: "#f5f5f5"
primaryBorderColor: "#333"
lineColor: "#666"
---
flowchart TB
subgraph ClientLayer["Client Layer"]
direction LR
Web[Web App]
Mobile[Mobile App]
CLI[CLI Tool]
end
subgraph Gateway["API Gateway"]
LB[Load Balancer]
Rate[Rate Limiter]
LB --> Rate
end
subgraph Services["Microservices"]
direction TB
subgraph Auth["Auth Domain"]
Login[Login Service]
Token[Token Service]
end
subgraph Data["Data Domain"]
Query[Query Service]
Write[Write Service]
Cache[Cache Layer]
end
subgraph Jobs["Background Jobs"]
Worker1[Report Worker]
Worker2[Sync Worker]
end
end
subgraph Storage["Data Stores"]
direction LR
PG[(PostgreSQL)]
Redis[(Redis)]
S3[(Object Store)]
end
%% Connections between layers
Web --> LB
Mobile --> LB
CLI --> LB
Rate --> Login
Rate --> Query
Rate --> Write
Login --> Token
Query --> PG
Query --> Redis
Write --> PG
Write --> S3
Worker1 --> PG
Worker2 --> Redis
classDef client fill:#e3f2fd,stroke:#1565c0
classDef gateway fill:#fff3e0,stroke:#e65100
classDef domain fill:#f3e5f5,stroke:#7b1fa2
classDef storage fill:#e8f5e9,stroke:#2e7d32
class Web,Mobile,CLI client
class LB,Rate gateway
class Login,Token,Query,Write,Cache,Worker1,Worker2 domain
class PG,Redis,S3 storage
Key design choices:
- Outer TB layout stacks the four main layers vertically (clients → gateway → services → storage)
- LR direction inside
ClientLayer and Storage keeps those layers horizontally compact
- Nested subgraphs inside
Services group domains without creating a new top-level layer
- Four color classes distinguish client, gateway, domain, and storage roles
- Config uses
base theme with custom themeVariables for a neutral, professional look
Constraints
MUST DO
- Use
flowchart over graph — graph is deprecated. All new diagrams should use flowchart.
- Use ASCII-safe characters only — Smart quotes (
""), em dashes (—), en dashes (–), Unicode arrows (→, ↔, ⇒), and non-ASCII punctuation break Mermaid's parser. Use straight quotes (""), hyphens (-), and ASCII arrows (-->, <-->, ==>) instead.
- Use
<br/> for line breaks — Actual newlines inside quoted node labels or edge labels may produce parse errors.
- Add edge labels for non-obvious transitions — If the reader has to guess why an edge exists, it needs a label.
- Test every diagram in the Mermaid Live Editor — Always paste the raw Mermaid source into mermaid.live and verify it renders before committing.
- Add text descriptions around diagrams — Include a sentence explaining what the diagram shows, so the page is meaningful if the diagram fails to render or for screen reader users. Use this as alt-text equivalent.
- Keep labels short — Under ~25 characters when possible. Use
<br/> for longer labels.
- Prefer multiple small diagrams — One focused diagram per concept is better than one crowded diagram with 40 nodes.
MUST NOT DO
- Do NOT use Unicode arrows or special characters in labels or IDs — Characters like
→, —, –, ✓, ✗ silently break Mermaid rendering. Use -->, ->, -, x, v or simple ASCII alternatives.
- Do NOT embed interactive features —
click callbacks, tooltip attributes, and target links are stripped by GitHub. Put links in the surrounding Markdown instead.
- Do NOT create diagrams over ~50KB — GitHub silently drops them with no error message. If you need more content, split into multiple diagrams.
- Do NOT rely on color alone to convey meaning — GitHub renders in both light and dark mode. Always add text labels, patterns, or icons as a backup for color distinctions.
- Do NOT mix diagram types in a single code block — Each
```mermaid block must contain exactly one diagram type. If you need a flowchart and a sequence diagram, use two separate blocks with separate descriptions.
- Do NOT use
\n for line breaks — Mermaid expects <br/> for line breaks inside labels. The \n escape sequence is not supported inside quoted strings.
- Do NOT use spaces or special characters in node IDs — IDs like
[My Service] or [data:flow] will fail. Use CamelCase instead: MyService, DataFlow.
Output Template
When asked to create a Mermaid diagram, produce:
Diagram Type & Purpose — One sentence explaining what the diagram shows and why it's the right type for this content (e.g., "A TD flowchart showing the CI/CD pipeline from commit to production deployment.")
Code Block — The complete Mermaid diagram code inside a ```mermaid code fence. Include a --- config block if theme or layout tweaks are needed.
Legend / Key — If using semantic colors, custom classes, or abbreviations in node IDs, include a brief legend explaining them. For simple diagrams, a one-sentence description suffices.
Template:
<!-- Explanation -->
<!-- [Diagram Type] showing [what it represents] -->
```mermaid
[diagram code]
**Example:**
```markdown
A TD flowchart showing the user authentication flow from login request to dashboard access.
```mermaid
flowchart TD
A[Login Request] --> B{Valid Credentials?}
B -- Yes --> C[Dashboard]
B -- No --> D[Error Page]
style C fill:#e8f5e9,stroke:#2e7d32
style D fill:#ffebee,stroke:#c62828
Legend: Green nodes represent success states, red nodes represent error states.
---
## Related Skills
| Skill | Purpose |
|-------|---------|
| `technical-documentation` | Writing the prose that surrounds and explains your Mermaid diagrams — READMEs, API docs, architecture overviews |
1---2name: mermaid-diagrams3description: Creates clear, web-savvy MermaidJS diagrams (flowcharts, sequence diagrams, Gantt charts, and more) for Markdown documentation that renders beautifully on GitHub.4license: MIT5---678910# MermaidJS Diagramming for GitHub Markdown1112Teaches AI models to write clean, well-structured MermaidJS diagrams that render beautifully on GitHub's native Markdown viewer. Covers diagram type selection, syntax best practices, GitHub-specific constraints, and common pitfalls across 10+ diagram types — flowcharts, sequence diagrams, Gantt charts, mindmaps, and more.1314## TL;DR Checklist1516- [ ] Prefer `flowchart` over `graph` — `graph` is deprecated in Mermaid17- [ ] Keep diagrams under 20–25 nodes for readability on GitHub18- [ ] Use ASCII-safe characters only — no Unicode arrows (`→`), em dashes (`—`), or smart quotes19- [ ] Use `<br/>` (not `\n`) for line breaks inside node labels20- [ ] Label edges with transition descriptions — don't assume flow is obvious21- [ ] Use subgraphs to group related nodes when exceeding 10–15 nodes22- [ ] Put diagram-defining config in a YAML `---` frontmatter block at the top23- [ ] Use ` ```mermaid` (lowercase) code fence — uppercase `Mermaid` won't render on GitHub24- [ ] Test every diagram in the [Mermaid Live Editor](https://mermaid.live) before committing25- [ ] Add text descriptions around diagrams for accessibility and context2627---2829## When to Use3031Use this skill when:3233- Writing architecture documentation that needs a system diagram showing how components interact34- Creating a README with a CI/CD pipeline flowchart, data flow diagram, or project structure overview35- Documenting a sequence of API calls, message exchanges, or protocol interactions in an issue or PR36- Building project timelines or roadmaps with Gantt charts in project Wikis37- Adding version control history visualizations with Git graphs in changelogs or release notes38- Explaining entity relationships (ER diagrams) or class hierarchies in design documents39- Visualizing user journeys or state machines for feature documentation40- Creating mindmaps or timeline diagrams for technical proposals or ADRs4142## When NOT to Use4344Avoid this skill for:4546- Complex UML class diagrams with 30+ classes and dense relationships — Mermaid's class diagram support is limited; use PlantUML or a dedicated UML tool instead47- Pixel-perfect diagrams where exact spacing, font sizes, or alignment matter — Mermaid uses auto-layout and you cannot fine-tune positions48- Diagrams that need interactivity (click events, tooltips, zoom/pan) — GitHub strips all interactive features; use a standalone Mermaid renderer or an image-based alternative49- Diagrams over ~50KB in source size — GitHub may fail to render large blocks50- Color-coded diagrams where meaning depends on hue alone — GitHub's dark/light mode may invert or reduce contrast; add text labels as a backup5152---5354## Core Workflow55561. **Choose the Right Diagram Type** — Match the concept you're visualizing to the correct Mermaid diagram type:57 - Processes, pipelines, decision trees → `flowchart`58 - API calls, message passing, time-ordered interactions → `sequenceDiagram`59 - State machines, UI flow → `stateDiagram-v2`60 - Class hierarchies, data models → `classDiagram`61 - Entity relationships → `erDiagram`62 - Project timelines, schedules → `gantt`63 - Git branches, merges, history → `gitGraph`64 - Hierarchical ideas, brainstorming → `mindmap`65 - Chronological events → `timeline`66 - Quadrant-based analysis (SWOT, priority) → `quadrantChart`67 - Software architecture (C4 model) → `C4Context`, `C4Container`, `C4Component`68 - Proportions, shares → `pie`69 - User goals and steps → `journey`70 - Technical requirements traceability → `requirementDiagram`71 - Flow/category relationships → `block`72 - Data flow between categories → `sankey`73 - X-Y data plotting → `xyChart`7475 **Checkpoint:** If you can describe your diagram in one sentence as "X shows how Y does Z" the type is probably right. If you need three sentences, split into two diagrams.76772. **Plan the Layout Direction** — Choose the layout that matches your narrative flow:78 - **TD (top-down)** — Hierarchies, sequential processes, decision trees, anything with 3+ layers. Readers scan top-to-bottom naturally.79 - **LR (left-right)** — Timelines, simple pipelines (2–4 stages), before/after comparisons, horizontal flows. Easier to read for wide-but-shallow structures.80 - **Direction per subgraph** — Use `direction TB` or `direction LR` inside subgraphs to mix layouts for complex diagrams.8182 **Checkpoint:** If your diagram has more vertical depth than horizontal width, use TD. If it's wider than tall, use LR.83843. **Structure Nodes with Descriptive IDs** — Use meaningful, CamelCase IDs that document themselves:85 ```mermaid86 %% ✅ GOOD — IDs describe the component87 flowchart TD88 AuthService --> Database89 AuthService --> CacheLayer9091 %% ❌ BAD — IDs are meaningless92 flowchart TD93 A1 --> B294 A1 --> C395 ```96 - Use `%%` comments to document parts of the diagram for future maintainers97 - Keep labels under ~25 characters when possible; use `<br/>` for longer text98 - Use the same ID style (PascalCase, camelCase, or kebab-case) consistently within a document991004. **Add Edge Labels for Clarity** — Every edge that represents a meaningful transition gets a label:101 ```mermaid102 flowchart LR103 Client -- "sends request" --> API104 API -- "validates token" --> Auth105 API -- "queries data" --> Database106 ```107 - Label syntax: `-- "label text" -->` or `--|label text|-->` for short labels108 - Without labels, readers must guess why edges exist — label non-obvious transitions109 - Edge labels should be short phrases (under 30 characters) when possible1101115. **Test in the Mermaid Live Editor** — Before committing, paste the entire block into [mermaid.live](https://mermaid.live):112 - Verify the diagram renders without errors113 - Check that long labels don't overflow nodes114 - Confirm layout direction produces a readable arrangement115 - Toggle GitHub's light/dark mode (via browser dev tools) to verify contrast works in both116 - If the diagram fails to render, check for: Unicode characters, missing subgraph `end` keywords, unmatched quotes, or IDs with spaces117118---119120## Diagram Type Reference121122| Type | Best Use Case | GitHub Notes | Example |123|------|--------------|--------------|---------|124| `flowchart` | Processes, pipelines, decision trees, architecture flows | Most common type; `flowchart` preferred over deprecated `graph` | CI/CD pipeline with build → test → deploy stages |125| `sequenceDiagram` | API calls, time-ordered interactions, message passing | Auto-numbers participants; use `actor` for human roles | Client → Auth server → API → Database request flow |126| `classDiagram` | Data models, class hierarchies, interface contracts | Limited to ~15 classes before layout gets crowded | User, Order, Product with relationships and cardinality |127| `stateDiagram-v2` | State machines, UI workflows, lifecycle management | Use `[*]` for start/end states | Order lifecycle: Created → Paid → Shipped → Delivered |128| `erDiagram` | Entity-relationship models, database schemas | Supports cardinality notation; keep under 10 entities | Customers, Orders, Products with `||--o{` relationships |129| `gantt` | Project timelines, schedules, release planning | Date format: `YYYY-MM-DD`; use `crit` for critical path | Sprint timeline with epics, tasks, and milestones |130| `pie` | Proportions, market share, resource allocation | Simple format; titles shown as legend | Language usage: 60% TypeScript, 25% Python, 15% Go |131| `gitGraph` | Branch strategies, merge workflows, release history | Branches auto-order by first commit; use `cherry-pick` | Feature branch → develop → main with release tags |132| `mindmap` | Brainstorming, knowledge hierarchies, outlines | Indentation-driven syntax; no edge labels | Project architecture with backend, frontend, infra branches |133| `timeline` | Chronological events, roadmaps, histories | Sections group related events; limited styling | Product roadmap: Q1 MVP → Q2 Beta → Q3 GA |134| `quadrantChart` | Prioritization matrices, SWOT analysis, portfolio | Points positioned by X/Y values (0–1 range); quadrant labels in config | Feature priority: effort vs impact |135| `C4Context` | System context diagrams (C4 model) | Uses `Person` and `System` boundaries; good for high-level architecture | User → System A → System B interactions |136| `block` | Category-based flow diagrams | Columns group related blocks; simple structure | Tech stack: Languages, Frameworks, Tools in columns |137| `journey` | User experience flows, task completion steps | Auto-scales; tasks listed in order with scores | User onboarding: signup → verify → dashboard |138139---140141## GitHub Rendering Guide142143### Code Fence144145Use **lowercase** ` ```mermaid ` — GitHub only renders lowercase. Uppercase ` ```Mermaid ` or ` ```mmd ` will not render.146147```markdown148<!-- ✅ WORKS on GitHub -->149```mermaid150flowchart TD151 A --> B152```153154<!-- ❌ DOES NOT WORK on GitHub -->155```Mermaid156flowchart TD157 A --> B158```159```160161### Feature Restrictions162163GitHub's native Mermaid renderer removes or ignores certain features. Know these limitations before you write:164165| Feature | GitHub Support | Workaround |166|---------|---------------|------------|167| Click events (`click A callback`) | ❌ Stripped | Add text links outside the diagram instead |168| Tooltips (title attribute on nodes) | ❌ Stripped | Add explanation in surrounding prose |169| Theme config via `%%{init:...}` | ⚠️ Config ignored | GitHub uses system light/dark mode; test both |170| `fontSize`, `fontFamily` in config | ⚠️ Partially respected | Keep labels short — default font is always readable |171| Markdown strings (`"..."`) | ✅ Supported | Use for bold/italic/`code` in labels |172| Subgraph styling | ✅ Supported | Use `style` or `classDef` for consistent coloring |173174### Size Limit175176Diagrams over approximately **50KB** in source text may fail to render on GitHub. As a rule of thumb:177- Keep diagrams under 20–25 nodes178- Keep labels under ~25 characters when possible179- If you need more nodes, split into multiple smaller diagrams that each cover one concept180- Diagrams over 50KB are silently dropped — you get no error message181182### Theme Adaptation183184GitHub renders Mermaid in the **viewer's system theme** (light or dark mode). You cannot force a specific theme. Design diagrams that work in both:185- Do **not** rely on color alone to convey meaning — always add text labels or patterns186- Use high-contrast combinations (dark text on light backgrounds, light text on dark backgrounds)187- Test in both modes by toggling your OS/browser theme before pushing188189### Testing Protocol190191Before committing any Mermaid diagram:1921931. Paste the full code block into [mermaid.live](https://mermaid.live) — fix any parse errors1942. Copy the rendered output as a PNG and verify it reads well at a glance1953. Toggle your system theme and re-check contrast1964. If the diagram is complex, ask a colleague to describe what they see in 1–2 sentences — if they can't, simplify197198---199200## Syntax Reference201202### Node Shapes203204| Shape | Syntax | Example |205|-------|--------|---------|206| Default rectangle | `id[label]` | `Server[Web Server]` |207| Rounded rectangle | `id(label)` | `API(API Gateway)` |208| Stadium (pill shape) | `id([label])` | `Start([Begin Process])` |209| Rhombus (decision) | `id{label}` | `Auth{Is Valid?}` |210| Parallelogram | `id[\\label\\]` | `Input[\\Parse Data\\]` |211| Trapezoid | `id[/label\\]` | `Service[/Transform\\]` |212| Double circle | `id(((label)))` | `End(((System Halt)))` |213| Asymmetric | `id>label]` | `Output>Result]` |214| Hexagon | `id{{label}}` | `Routing{{Load Balance}}` |215216### Edge Styles217218| Style | Syntax | Use Case |219|-------|--------|----------|220| Solid arrow | `-->` | Default flow, data passing |221| Thick arrow | `==>` | Primary/critical path |222| Dotted arrow | `-.->` | Optional/monitoring/async flow |223| Open circle | `--o` | UML aggregation or "uses" |224| Cross | `--x` | Error path, termination |225| Bidirectional | `<-->` | Two-way communication |226| Label (inline) | `-- "text" -->` | Standard edge labels |227| Label (short) | `--\|text\|-->` | Compact labels |228229### Subgraph Structure230231Wrap related nodes in a `subgraph` block with an optional `direction` override:232233```mermaid234flowchart TD235 subgraph Frontend["Frontend Layer"]236 direction LR237 A[React App] --> B[API Client]238 end239 subgraph Backend["Backend Services"]240 direction TB241 C[Auth Service] --> D[Database]242 C --> E[Cache]243 end244 B --> C245```246247Rules:248- Every `subgraph` needs a closing `end` keyword — forgetting `end` is the most common Mermaid syntax error249- Use `subgraph Name["Display Name"]` if the display name differs from the ID or contains special characters250- Direction override (`direction TB/LR`) is optional — without it, the subgraph inherits the parent's direction251252### Comments253254Use `%%` for single-line comments. Comments are ignored by the renderer but visible in source:255256```mermaid257%% This diagram shows the user authentication flow258flowchart TD259 %% Entry point260 Login --> Auth{Valid Credentials?}261 Auth -- Yes --> Dashboard262 Auth -- No --> LoginError263```264265### Styling with classDef and style266267Apply CSS-like classes to nodes for consistent visual grouping:268269```mermaid270flowchart TD271 classDef primary fill:#e1f5fe,stroke:#01579b,stroke-width:2px272 classDef danger fill:#ffebee,stroke:#b71c1c273274 A[Login] --> B[Dashboard]275 C[Error Handler] --> D[Fallback]276277 class A,B primary278 class C,D danger279```280281Alternatively, use inline `style` for one-off nodes:282283```mermaid284flowchart TD285 A[Critical Component] --> B[Normal Component]286 style A fill:#ffebee,stroke:#c62828,stroke-width:4px287```288289### Markdown Strings for Rich Labels290291Use double-quoted markdown strings to include **bold**, *italic*, or `code` formatting in node labels:292293```mermaid294flowchart LR295 A["**Build** the _package_"] --> B["Run `npm test`"]296```297298Supported formatting inside markdown strings: `**bold**`, `*italic*`, `` `code` ``.299Line breaks inside markdown strings: use `<br/>` not `\n`.300301### Diagram Configuration (YAML Frontmatter)302303Set global rendering options with a YAML block at the top of the diagram:304305```mermaid306---307config:308 theme: neutral309 flowchart:310 curveBasis: 0.3311---312flowchart TD313 A --> B314```315316Available themes: `default`, `forest`, `dark`, `neutral`, `base`.317Use `base` as a starting point for custom themes with `themeVariables`.318319---320321## Implementation Patterns322323### Pattern 1: Deployment Pipeline Flowchart324325A top-down flowchart showing a CI/CD deployment pipeline with subgraphs for each stage. Uses TD direction for the natural reading flow from commit to production.326327```mermaid328---329config:330 theme: neutral331---332flowchart TD333 subgraph Source["Source Control"]334 direction LR335 Dev[Developer] --> PR[Pull Request]336 PR --> Review[Code Review]337 Review --> Merge[Merge to Main]338 end339340 subgraph CI["Continuous Integration"]341 direction TB342 Merge --> Lint[Lint & Type Check]343 Lint --> Test[Run Tests]344 Test --> Build[Build Artifact]345 end346347 subgraph CD["Continuous Deployment"]348 direction TB349 Build --> Staging[Deploy to Staging]350 Staging --> E2E[E2E Tests]351 E2E --> Approve{Approved?}352 Approve -- Yes --> Prod[Deploy to Production]353 Approve -- No --> Rollback[Rollback]354 end355356 %% Cross-stage styling357 classDef ci fill:#e3f2fd,stroke:#1565c0358 classDef cd fill:#e8f5e9,stroke:#2e7d32359 classDef gate fill:#fff3e0,stroke:#e65100360361 class Lint,Test,Build ci362 class Staging,E2E,Prod cd363 class Approve,Rollback gate364```365366**Key design choices:**367- Three subgraphs create visual separation between source control, CI, and CD stages368- `direction LR` in Source keeps the PR flow compact horizontally369- A decision rhombus (`Approve`) marks the manual gating step370- Color classes distinguish CI (blue), CD (green), and gates (orange)371- Edge labels on the gating paths explain the two outcomes372373### Pattern 2: API Interaction Sequence Diagram374375A sequence diagram showing how a client, auth service, API gateway, and database interact during a token-based request. Reads left-to-right as time progresses downward.376377```mermaid378sequenceDiagram379 actor User380 participant Client as Web Client381 participant Auth as Auth Service382 participant API as API Gateway383 participant DB as Database384385 User->>Client: Submit credentials386 Client->>Auth: POST /auth/token387 Auth->>Auth: Validate credentials388 Auth-->>Client: Return JWT token389 Note over Client,Auth: Token cached for 15 minutes390391 Client->>API: GET /api/resource<br/>Authorization: Bearer JWT392 API->>Auth: Verify token signature393 Auth-->>API: Token valid (payload)394 API->>DB: SELECT * FROM resources395 DB-->>API: Return results396 API-->>Client: 200 OK + JSON body397 Client-->>User: Display resources398399 alt Token Expired400 Client->>Auth: POST /auth/refresh401 Auth-->>Client: New JWT token402 end403```404405**Key design choices:**406- `actor User` distinguishes the human role from system participants407- Dotted lines (`-->>`) for responses, solid lines (`->>`) for requests — standard convention408- `Note over` documents the token caching behavior inline409- `<br/>` in the API request label keeps the readable content on one line410- `alt` block handles the token refresh edge case without cluttering the main flow411412### Pattern 3: Before/After Comparison413414Two subgraphs side by side (LR direction) comparing a naive architecture against an improved one. Useful for RFCs, ADRs, or refactoring proposals.415416```mermaid417---418config:419 theme: neutral420---421flowchart LR422 subgraph Before["Before: Monolithic"]423 direction TB424 Monolith[Single App Server]425 MonolithDB[(Single Database)]426 Monolith --> MonolithDB427 Monolith --- Monolith428 end429430 subgraph After["After: Microservices"]431 direction TB432 API[API Gateway]433 Users[User Service]434 Orders[Order Service]435 Notify[Notification Service]436 UserDB[(User DB)]437 OrderDB[(Order DB)]438439 API --> Users440 API --> Orders441 Users --> UserDB442 Orders --> OrderDB443 Orders -.-> Notify444 end445446 style Before fill:#ffebee,stroke:#c62828,stroke-width:2px,stroke-dasharray: 5 5447 style After fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px448```449450**Key design choices:**451- LR layout places both architectures side by side for easy visual comparison452- Red dashed border on "Before" signals it's the problem state; green solid on "After" signals improvement453- The microservices subgraph uses the same general structure but adds new services454- Dotted edge from Orders to Notify indicates an async/eventual interaction455- Restrained node count (6 in After) keeps the comparison readable456457### Pattern 4: Composition Diagram with Mixed Layout458459A complex architecture diagram that combines TD and LR directions in nested subgraphs. Shows how direction directives can create readable multi-region layouts.460461```mermaid462---463config:464 theme: base465 themeVariables:466 primaryColor: "#f5f5f5"467 primaryBorderColor: "#333"468 lineColor: "#666"469---470flowchart TB471 subgraph ClientLayer["Client Layer"]472 direction LR473 Web[Web App]474 Mobile[Mobile App]475 CLI[CLI Tool]476 end477478 subgraph Gateway["API Gateway"]479 LB[Load Balancer]480 Rate[Rate Limiter]481 LB --> Rate482 end483484 subgraph Services["Microservices"]485 direction TB486 subgraph Auth["Auth Domain"]487 Login[Login Service]488 Token[Token Service]489 end490 subgraph Data["Data Domain"]491 Query[Query Service]492 Write[Write Service]493 Cache[Cache Layer]494 end495 subgraph Jobs["Background Jobs"]496 Worker1[Report Worker]497 Worker2[Sync Worker]498 end499 end500501 subgraph Storage["Data Stores"]502 direction LR503 PG[(PostgreSQL)]504 Redis[(Redis)]505 S3[(Object Store)]506 end507508 %% Connections between layers509 Web --> LB510 Mobile --> LB511 CLI --> LB512 Rate --> Login513 Rate --> Query514 Rate --> Write515 Login --> Token516 Query --> PG517 Query --> Redis518 Write --> PG519 Write --> S3520 Worker1 --> PG521 Worker2 --> Redis522523 classDef client fill:#e3f2fd,stroke:#1565c0524 classDef gateway fill:#fff3e0,stroke:#e65100525 classDef domain fill:#f3e5f5,stroke:#7b1fa2526 classDef storage fill:#e8f5e9,stroke:#2e7d32527528 class Web,Mobile,CLI client529 class LB,Rate gateway530 class Login,Token,Query,Write,Cache,Worker1,Worker2 domain531 class PG,Redis,S3 storage532```533534**Key design choices:**535- Outer TB layout stacks the four main layers vertically (clients → gateway → services → storage)536- LR direction inside `ClientLayer` and `Storage` keeps those layers horizontally compact537- Nested subgraphs inside `Services` group domains without creating a new top-level layer538- Four color classes distinguish client, gateway, domain, and storage roles539- Config uses `base` theme with custom `themeVariables` for a neutral, professional look540541---542543## Constraints544545### MUST DO546547- **Use `flowchart` over `graph`** — `graph` is deprecated. All new diagrams should use `flowchart`.548- **Use ASCII-safe characters only** — Smart quotes (`""`), em dashes (`—`), en dashes (`–`), Unicode arrows (`→`, `↔`, `⇒`), and non-ASCII punctuation break Mermaid's parser. Use straight quotes (`""`), hyphens (`-`), and ASCII arrows (`-->`, `<-->`, `==>`) instead.549- **Use `<br/>` for line breaks** — Actual newlines inside quoted node labels or edge labels may produce parse errors.550- **Add edge labels for non-obvious transitions** — If the reader has to guess why an edge exists, it needs a label.551- **Test every diagram in the Mermaid Live Editor** — Always paste the raw Mermaid source into [mermaid.live](https://mermaid.live) and verify it renders before committing.552- **Add text descriptions around diagrams** — Include a sentence explaining what the diagram shows, so the page is meaningful if the diagram fails to render or for screen reader users. Use this as alt-text equivalent.553- **Keep labels short** — Under ~25 characters when possible. Use `<br/>` for longer labels.554- **Prefer multiple small diagrams** — One focused diagram per concept is better than one crowded diagram with 40 nodes.555556### MUST NOT DO557558- **Do NOT use Unicode arrows or special characters in labels or IDs** — Characters like `→`, `—`, `–`, `✓`, `✗` silently break Mermaid rendering. Use `-->`, `->`, `-`, `x`, `v` or simple ASCII alternatives.559- **Do NOT embed interactive features** — `click` callbacks, `tooltip` attributes, and `target` links are stripped by GitHub. Put links in the surrounding Markdown instead.560- **Do NOT create diagrams over ~50KB** — GitHub silently drops them with no error message. If you need more content, split into multiple diagrams.561- **Do NOT rely on color alone to convey meaning** — GitHub renders in both light and dark mode. Always add text labels, patterns, or icons as a backup for color distinctions.562- **Do NOT mix diagram types in a single code block** — Each ` ```mermaid ` block must contain exactly one diagram type. If you need a flowchart and a sequence diagram, use two separate blocks with separate descriptions.563- **Do NOT use `\n` for line breaks** — Mermaid expects `<br/>` for line breaks inside labels. The `\n` escape sequence is not supported inside quoted strings.564- **Do NOT use spaces or special characters in node IDs** — IDs like `[My Service]` or `[data:flow]` will fail. Use CamelCase instead: `MyService`, `DataFlow`.565566---567568## Output Template569570When asked to create a Mermaid diagram, produce:5715721. **Diagram Type & Purpose** — One sentence explaining what the diagram shows and why it's the right type for this content (e.g., "A TD flowchart showing the CI/CD pipeline from commit to production deployment.")5735742. **Code Block** — The complete Mermaid diagram code inside a ` ```mermaid ` code fence. Include a `---` config block if theme or layout tweaks are needed.5755763. **Legend / Key** — If using semantic colors, custom classes, or abbreviations in node IDs, include a brief legend explaining them. For simple diagrams, a one-sentence description suffices.577578**Template:**579580```markdown581<!-- Explanation -->582<!-- [Diagram Type] showing [what it represents] -->583584```mermaid585[diagram code]586```587588<!-- Legend -->589<!-- Colors/classes used: [explanation of each] -->590```591592**Example:**593594```markdown595A TD flowchart showing the user authentication flow from login request to dashboard access.596597```mermaid598flowchart TD599 A[Login Request] --> B{Valid Credentials?}600 B -- Yes --> C[Dashboard]601 B -- No --> D[Error Page]602 style C fill:#e8f5e9,stroke:#2e7d32603 style D fill:#ffebee,stroke:#c62828604```605606**Legend:** Green nodes represent success states, red nodes represent error states.607```608609---610611## Related Skills612613| Skill | Purpose |614|-------|---------|615| `technical-documentation` | Writing the prose that surrounds and explains your Mermaid diagrams — READMEs, API docs, architecture overviews |