Mermaid
6 min read
Mermaid is a JavaScript library for diagrams as code — you describe a diagram in a compact, Markdown-inspired text syntax and Mermaid renders it to SVG, computing the layout automatically. Because the source is plain text, diagrams live next to code, diff cleanly in version control, and need no manual drag-and-drop in a drawing tool.
It is the de-facto standard for diagrams embedded in Markdown: GitHub, GitLab, Gitea, Obsidian, Notion, and static-site generators like Quartz render fenced ```mermaid blocks natively.
Overview
The workflow mirrors Graphviz: a text definition goes through a parser and an automatic layout engine, then renders to an image.
mermaid text → parser → auto-layout → SVG
Unlike Graphviz (one DOT language, many layout engines), Mermaid has a distinct mini-language per diagram type. Every diagram begins with a type keyword that selects the grammar and renderer:
markdown
```mermaid
flowchart LR
A[Start] --> B{Decision}
B -->|yes| C[Do thing]
B -->|no| D[Stop]
```
How it integrates
• Markdown / Git forges — fenced mermaid code blocks render automatically on GitHub, GitLab, Gitea, etc.
• Live Editor — https://mermaid.live renders as you type and encodes the whole diagram into the URL for sharing (also used as the "edit" link under rendered diagrams).
• CLI — @mermaid-js/mermaid-cli provides mmdc to render .mmd files to SVG/PNG/PDF in scripts and CI (see below).
• Library — drop in via CDN or npm install mermaid and call mermaid.run() / mermaid.render() in the browser.
• Generated diagrams — many tools emit Mermaid as an output format, e.g. process-compose graph --format mermaid.
Basic syntax
Common to all diagram types:
• The first token is the diagram type (flowchart, sequenceDiagram, classDiagram…).
• Comments start with %%.
• Statements are newline-separated; indentation is cosmetic.
• A YAML frontmatter block can set a title, the diagram config, and theme:
markdown
```mermaid
---
title: Example
config:
theme: forest
---
flowchart TD
A --> B
```
• Directives %%{init: {...}}%% tweak config inline without frontmatter.
Diagram types
Mermaid supports a large and growing set of diagram types. The most used:
| Type | Keyword | Purpose |
|---|---|---|
| Flowchart | flowchart / graph | Process flows, decision trees, general node-edge graphs |
| Sequence | sequenceDiagram | Interactions between participants over time |
| Class | classDiagram | OOP class structure and relationships (UML) |
| State | stateDiagram-v2 | State machines and transitions |
| Entity-Relationship | erDiagram | Database schema / ER models |
| Gantt | gantt | Project timelines and schedules |
| Git graph | gitGraph | Branch/commit history visualization |
| Pie | pie | Proportional data |
| User journey | journey | UX flows with satisfaction scores |
| Mindmap | mindmap | Hierarchical brainstorming |
| Timeline | timeline | Chronological events |
| Quadrant | quadrantChart | Two-axis positioning |
| XY chart | xychart-beta | Bar / line plots |
| C4 | C4Context | Architecture (C4 model) |
| Sankey | sankey-beta | Flow / distribution |
| Block | block-beta | Fixed-layout block diagrams |
| Requirement | requirementDiagram | Systems-engineering requirements |
| Architecture | architecture-beta | Cloud/service architecture with icons |
| Packet | packet-beta | Network packet / byte layouts |
| Kanban | kanban | Task boards |
(Newer/beta types also include Radar, Treemap, and Venn.)
Flowchart
The workhorse diagram. Direction is set after the keyword: TD/TB (top-down), BT, LR (left-right), RL.
flowchart LR
A[Square node] --> B(Rounded node)
B --> C{Diamond / decision}
C -->|yes| D[(Database)]
C -->|no| E((Circle))Node shapes
| Syntax | Shape |
|---|---|
id[text] | Rectangle |
id(text) | Rounded rectangle |
id([text]) | Stadium / pill |
id[[text]] | Subroutine |
id[(text)] | Cylinder (database) |
id((text)) | Circle |
id{text} | Rhombus (decision) |
id{{text}} | Hexagon |
id>text] | Asymmetric / flag |
The newer id@{ shape: ... } syntax exposes a much larger shape catalog.
Edges
flowchart LR
A --> B %% arrow
C --- D %% open line
E -.-> F %% dotted
G ==> H %% thick
I -- text --> J %% labeledSubgraphs
flowchart TB
subgraph web [Web tier]
lb[Load balancer] --> app1
lb --> app2
end
subgraph data [Data tier]
db[(Postgres)]
end
app1 --> db
app2 --> dbSequence diagram
sequenceDiagram
autonumber
participant C as Client
participant S as Server
C->>S: GET /resource
activate S
S-->>C: 200 OK
deactivate S
alt cache miss
S->>S: query database
else cache hit
S-->>C: cached response
end
Note over C,S: TLS encryptedArrows: ->> solid+arrow, -->> dashed (reply), -x lost message. Blocks include alt/else, opt, loop, par, critical, and activate/deactivate lifelines.
Class diagram
classDiagram
class Animal {
+String name
+int age
+makeSound() void
}
class Dog
Animal <|-- Dog : inheritance
Animal "1" --> "*" Owner : owned byRelationship arrows: <|-- inheritance, *-- composition, o-- aggregation, --> association, ..> dependency, ..|> realization.
State diagram
stateDiagram-v2
[*] --> Idle
Idle --> Running : start
Running --> Idle : stop
Running --> [*] : exit[*] marks start/end pseudo-states; composite states and concurrency (--) are supported.
Entity-relationship diagram
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
CUSTOMER {
string name
string email PK
}Cardinality uses crow's-foot notation: || exactly one, o{ zero-or-many, |{ one-or-many.
Gantt
gantt
title Roadmap
dateFormat YYYY-MM-DD
section Design
Spec :done, des1, 2026-01-01, 7d
Mockups :active, des2, after des1, 5d
section Build
Implement : dev1, after des2, 14dGit graph
gitGraph
commit
branch develop
checkout develop
commit
checkout main
merge developPie & mindmap
pie title Languages
"Rust" : 45
"Go" : 30
"Other": 25mindmap
root((KB))
Tools
Mermaid
Graphviz
AppsTheming and configuration
• Built-in themes: default, neutral, dark, forest, base — set via frontmatter config.theme or an %%{init: {'theme':'forest'}}%% directive.
• The base theme plus theme variables (themeVariables) allows full colour customization.
• Per-element styling in flowcharts via style/classDef/class:
flowchart LR
A --> B
classDef warn fill:#fdd,stroke:#f00
class A warn• A global mermaidConfig controls security level, font, and flowchart/sequence layout options. securityLevel: strict (the default) sanitizes labels to prevent XSS.
Tooling
mermaid-cli (mmdc)
Renders diagrams headlessly (via Puppeteer/Chromium) — useful in build pipelines and for exporting static images.
shell
npm install -g @mermaid-js/mermaid-cli
mmdc -i diagram.mmd -o diagram.svg
mmdc -i diagram.mmd -o diagram.png -t dark -b transparent
It can also process Markdown files, replacing mermaid blocks with rendered images.
Live Editor & pretty.fish
• mermaid.live — the official editor; renders live and encodes diagram state into the URL for sharing.
• pretty.fish — a third-party, browser-based Mermaid workspace that improves on the official editor: live preview, an infinite canvas to arrange multiple diagrams, multi-page projects, built-in themes, export to SVG/PNG/Mermaid source, URL-encoded sharing, and offline support as a PWA. No sign-up required.
Mermaid vs Graphviz
| Mermaid | Graphviz | |
|---|---|---|
| Language | One syntax per diagram type | Single DOT language |
| Layout | Built-in per type | 12 selectable layout engines |
| Runtime | JavaScript (browser/Node) | Native C, many bindings |
| Strength | Docs-native, many diagram kinds (sequence, gantt, ER…) | Precise control of large/complex graphs |
| Embedding | Renders inline in Markdown/Git forges | Pre-render to image, then embed |
Reach for Mermaid when the diagram should live inside documentation and read well in source form; reach for Graphviz when you need fine layout control over large or generated graphs.
See also