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:

TypeKeywordPurpose
Flowchartflowchart / graphProcess flows, decision trees, general node-edge graphs
SequencesequenceDiagramInteractions between participants over time
ClassclassDiagramOOP class structure and relationships (UML)
StatestateDiagram-v2State machines and transitions
Entity-RelationshiperDiagramDatabase schema / ER models
GanttganttProject timelines and schedules
Git graphgitGraphBranch/commit history visualization
PiepieProportional data
User journeyjourneyUX flows with satisfaction scores
MindmapmindmapHierarchical brainstorming
TimelinetimelineChronological events
QuadrantquadrantChartTwo-axis positioning
XY chartxychart-betaBar / line plots
C4C4ContextArchitecture (C4 model)
Sankeysankey-betaFlow / distribution
Blockblock-betaFixed-layout block diagrams
RequirementrequirementDiagramSystems-engineering requirements
Architecturearchitecture-betaCloud/service architecture with icons
Packetpacket-betaNetwork packet / byte layouts
KanbankanbanTask 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

SyntaxShape
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   %% labeled

Subgraphs

flowchart TB
    subgraph web [Web tier]
        lb[Load balancer] --> app1
        lb --> app2
    end
    subgraph data [Data tier]
        db[(Postgres)]
    end
    app1 --> db
    app2 --> db



Sequence 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 encrypted

Arrows: ->> 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 by

Relationship 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, 14d

Git graph

gitGraph
    commit
    branch develop
    checkout develop
    commit
    checkout main
    merge develop

Pie & mindmap

pie title Languages
    "Rust" : 45
    "Go"   : 30
    "Other": 25

mindmap
    root((KB))
        Tools
            Mermaid
            Graphviz
        Apps



Theming 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

MermaidGraphviz
LanguageOne syntax per diagram typeSingle DOT language
LayoutBuilt-in per type12 selectable layout engines
RuntimeJavaScript (browser/Node)Native C, many bindings
StrengthDocs-native, many diagram kinds (sequence, gantt, ER…)Precise control of large/complex graphs
EmbeddingRenders inline in Markdown/Git forgesPre-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

• Graphviz — DOT-based graph rendering
• Quartz — static-site generator that renders Mermaid blocks
• process-compose — can emit its dependency graph as Mermaid