cheat-sheets

Mermaid

Mermaid draws diagrams from plain text: flowcharts, sequence, class, state, ER, Gantt and Git graphs. Write it in a fenced mermaid block so it renders on GitHub and in many editors, or render files with mmdc (mermaid-cli).

Documentation: Mermaid documentation · Mermaid CLI · GitHub: creating diagrams Project: Mermaid

Verification: syntax checked against the Mermaid documentation and the mermaid-cli source. The diagrams were not rendered locally (mermaid-cli needs a bundled Chromium), so a version difference or typo is possible. Test in the Mermaid Live Editor.

Basics #

ITEMDESCRIPTION
```mermaidFence that starts a diagram in Markdown (close with ```)
First lineDiagram type keyword, e.g. flowchart LR, sequenceDiagram, erDiagram
%% commentComment line
.mmd filePlain Mermaid text for mmdc and editors
Lower-case endBreaks flowcharts if used inside a label: write End
Quote labelsA["Text with (brackets)"] for special characters
markdown
```mermaid
flowchart LR
    A[Client] --> B[Proxy] --> C[App]
```

Flowchart #

graph is an older alias of flowchart. Direction is TB (or TD), BT, LR or RL.

SYNTAXDESCRIPTION
flowchart TDStart a top-down flowchart
A[Text]Rectangle
A(Text)Rounded
A([Text])Stadium
A[[Text]]Subroutine
A[(Text)]Cylinder (database)
A((Text))Circle
A{Text}Diamond (decision)
A{{Text}}Hexagon
A[/Text/]Parallelogram
A@{ shape: cyl, label: "Text" }Extended shape form (Mermaid 11.3.0 and later)
A --> BArrow
A --- BLine without arrowhead
A -->|Yes| B or A -- Yes --> BLabelled arrow
A -.-> BDotted arrow
A ==> BThick arrow
A ~~~ BInvisible link (layout only)
A --> B & COne source, several targets
A --> B --> CChain
subgraph ID [Title] … endGroup nodes
direction LRDirection inside a subgraph
classDef NAME fill:#f9f,stroke:#333Define a style class
class A,B NAME or A:::NAMEApply a class
style A fill:#f9fStyle one node
linkStyle 0 stroke:#f00Style a link by its position (zero-based)
click A "https://example.com" "Tooltip"Link a node (disabled at the strict security level)
mermaid
flowchart TD
    A[Request] --> B{Cached?}
    B -->|Yes| C[Serve from cache]
    B -->|No| D[(Database)]
    D --> C
    subgraph Edge
        B
    end

Sequence Diagram #

SYNTAXDESCRIPTION
participant A as AliceDeclare and alias a participant (sets the order)
actor BParticipant drawn as a person
A->>B: TextSolid line with arrowhead
A-->>B: TextDotted line with arrowhead (replies)
A->B: Text / A-->B: TextLine without arrowhead
A-xB: TextSolid line with a cross (failed)
A-)B: TextOpen arrow (asynchronous)
A->>+B: Text / B-->>-A: TextActivate and deactivate B
activate B / deactivate BSame, as separate lines
Note right of B: TextNote beside a participant (left of also works)
Note over A,B: TextNote across participants
autonumberNumber the messages
loop Text … endRepeat
alt Text … else Text … endAlternatives
opt Text … endOptional
par Text … and Text … endParallel
critical Text … option Text … endMust succeed, with fallback
break Text … endStop the sequence
rect rgb(191, 223, 255) … endColoured background block
box Aqua Group … endGroup participants (no # hex colours)
mermaid
sequenceDiagram
    autonumber
    participant C as Client
    participant S as Server
    C->>+S: GET /health
    alt healthy
        S-->>-C: 200 OK
    else failing
        S-->>C: 503
    end
    Note over C,S: Retry after 5 seconds

Class Diagram #

SYNTAXDESCRIPTION
class AnimalDeclare a class
class Animal { +String name +eat() }Members in braces, one per line
+ / - / # / ~Public, private, protected, package visibility
method()* / method()$Abstract or static method
Animal <|-- DogInheritance
Car *-- EngineComposition
Library o-- BookAggregation
A --> BAssociation
A ..> BDependency
A ..|> BRealisation
A "1" --> "*" B : hasCardinality and label
<<interface>> ShapeAnnotation (or put it inside the braces)
class Box~T~Generic type
direction RLLayout direction
mermaid
classDiagram
    class Animal {
        +String name
        +eat()
    }
    class Dog
    Animal <|-- Dog
    Dog "1" --> "*" Toy : owns

State Diagram #

Use stateDiagram-v2.

SYNTAXDESCRIPTION
[*] --> IdleStart state
Done --> [*]End state
Idle --> Running : startTransition with a label
state "Long name" as S1Alias for a state
state Group { ... }Composite (nested) state
state C <<choice>>Decision
state F <<fork>> / state J <<join>>Fork and join
-- inside a composite stateSeparate concurrent regions
note right of Idle : TextNote (left of also works)
direction LRLayout direction
mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Running : start
    Running --> Idle : stop
    Running --> Failed : error
    Failed --> [*]

ER Diagram #

CARDINALITY (LEFT|RIGHT)MEANING
|o | o|Zero or one
|| | ||Exactly one
}o | o{Zero or more
}| | |{One or more
SYNTAXDESCRIPTION
A ||--o{ B : placesIdentifying relationship (solid line) with a label
A }o..o{ B : isNon-identifying relationship (dashed line)
A { string name PK }Attributes in braces, one type name per line
PK, FK, UKKey markers after the attribute; combine as PK, FK
string phone "Comment"Quoted comment at the end of an attribute line
mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    CUSTOMER {
        int id PK
        string name
    }
    ORDER {
        int id PK
        int customer_id FK
    }

Gantt #

SYNTAXDESCRIPTION
ganttStart a Gantt chart
title PlanChart title
dateFormat YYYY-MM-DDFormat of input dates
axisFormat %d/%mFormat of the axis labels
section NameGroup of tasks
Task :done, id1, 2025-01-01, 5dTask with status, ID, start date and duration
Task :active, id2, after id1, 10dStarts when id1 ends
Task :crit, id3, after id2, 3dCritical task
Release :milestone, m1, after id3, 0dMilestone
mermaid
gantt
    title Migration
    dateFormat YYYY-MM-DD
    section Build
    Design  :done, des1, 2025-01-01, 5d
    Develop :active, dev1, after des1, 10d
    Launch  :milestone, m1, after dev1, 0d

Git Graph #

SYNTAXDESCRIPTION
gitGraphStart a graph (add LR:, TB: or BT: for orientation)
commitCommit on the current branch
commit id: "A" tag: "v1.0"Commit with an ID and a tag
commit type: HIGHLIGHTCommit type: NORMAL, REVERSE or HIGHLIGHT
branch developCreate and switch to a branch
checkout mainSwitch branch
merge developMerge a branch into the current one
cherry-pick id: "A"Copy a commit from another branch
mermaid
gitGraph
    commit
    branch develop
    checkout develop
    commit
    commit
    checkout main
    merge develop tag: "v1.0"
    commit

Themes and Configuration #

Theme names (Mermaid documentation): default, neutral, dark, forest, base, plus newer looks such as neo, neo-dark, redux, redux-dark, redux-color and redux-dark-color on recent versions. Only base accepts custom themeVariables.

Frontmatter at the top of the diagram is the current method:

mermaid
---
config:
  theme: base
  themeVariables:
    primaryColor: "#BB2528"
    lineColor: "#F8B229"
---
flowchart LR
    A --> B

The older init directive still works and goes on the line before the diagram:

text
%%{init: {"theme": "forest", "flowchart": {"curve": "linear"}}}%%
OPTIONDESCRIPTION
themeTheme name
themeVariablesColours and fonts (with base), e.g. primaryColor, lineColor, fontFamily
flowchart.curveLink shape, e.g. linear
sequence.wrapWrap long messages
securityLevelstrict (default) disables click links and scripts; loose enables them
look / layoutVisual style and layout engine on recent versions (unverified: check your version’s docs)

GitHub and Editors #

WHERENOTES
GitHubRenders mermaid blocks in Markdown files, issues, discussions, pull requests and wikis
GitHub versionA mermaid block containing only info shows the version GitHub runs, which may lag behind the docs
Obsidian, Joplin, VS CodeRender mermaid blocks natively or with an extension (see Obsidian, Joplin and VSCode (Visual Studio Code))
Third-party pluginsNot available on GitHub, and may cause errors

mermaid-cli (mmdc) #

Install with npm install -g @mermaid-js/mermaid-cli, or run it with npx -p @mermaid-js/mermaid-cli mmdc. It drives a headless Chromium through Puppeteer.

COMMANDDESCRIPTION
mmdc -i <INPUT>.mmd -o <OUTPUT>.svgRender to SVG (PNG and PDF by file extension)
mmdc -i <INPUT>.mmd -o <OUTPUT>.png -s 2PNG at scale 2
mmdc -i <INPUT>.mmd -o <OUTPUT>.png -t dark -b transparentTheme and background
mmdc -i <INPUT>.mmd -o <OUTPUT>.png -c <CONFIG>.jsonMermaid JSON config file
mmdc -i <INPUT>.mmd -o <OUTPUT>.svg -C <STYLE>.cssCustom CSS (used as themeCSS)
mmdc -i <INPUT>.mmd -o <OUTPUT>.pdf --pdf-paper-format A4PDF with a paper size
mmdc -i <INPUT>.md -o <OUTPUT>.mdRender each mermaid block in a Markdown file to an image and rewrite the links
mmdc -i <INPUT>.md -o <OUTPUT>.md -a <DIR>Write the images to a directory
mmdc -i - -o <OUTPUT>.svgRead the diagram from standard input
mmdc -p <PUPPETEER>.json -i <INPUT>.mmdPuppeteer config (for example launch args in containers)
mmdc -q ...Quiet
mmdc -hAll options

Run in Docker without installing Node: docker run --rm -u "$(id -u):$(id -g)" -v "$PWD:/data" minlag/mermaid-cli -i diagram.mmd -o diagram.svg. In a container as root, Chromium may need {"args": ["--no-sandbox"]} in the Puppeteer config (unverified here).

Troubleshooting #

SYMPTOMFIX
Syntax error in textCheck the first line keyword, unclosed quotes or brackets and a stray end
Diagram works in the live editor but not on GitHubGitHub’s Mermaid version is older; use info to check it and avoid newer syntax
Label with (, ), : or # breaksWrap the label in double quotes
Flowchart ends at a node called endCapitalise it (End) or quote it
A---oB draws a circle edgeAdd a space or change the case (A --- oB)
click does nothingThe security level is strict; click links need loose
mmdc fails to launch the browserInstall Chromium dependencies, or pass -p with --no-sandbox in a container

See Also #

Search all sheets

Tip: / or Ctrl/Cmd+K to open, Esc to close.