Introduction

TL;DR

Mermaid is a JavaScript-based diagramming tool that renders diagrams from Markdown-inspired text syntax in the browser. You declare diagrams in Markdown code blocks using the mermaid language identifier, and GitHub (since 2022), GitLab (13.0+), Notion, and Obsidian automatically render them. Mermaid supports 10+ diagram types including flowcharts, sequence diagrams, Gantt charts, ER diagrams, and class diagrams, enabling version-controlled, text-based documentation without GUI tools.

Mermaid eliminates context switching between documentation and diagram editors. Unlike Visio or Lucidchart, your diagrams live in the same repository as your code, are reviewable via Git diff, and can be collaboratively edited like any Markdown file.

Why it matters: Technical teams can maintain diagrams as living documentation without proprietary tools, reducing friction in architecture discussions, project planning, and system design reviews.

What is Mermaid?

Mermaid is a text-based diagramming and charting library that takes Markdown-inspired syntax and creates diagrams dynamically in the browser using JavaScript. Maintained by Knut Sveidqvist and developed collaboratively with the CommonMark community, Mermaid has become the de facto standard for diagram-as-code in modern technical documentation.

Core Advantages

Text-Based Definition: Diagrams are defined in plain text, not GUI coordinates. You describe relationships and flows; Mermaid handles layout.

Version Control: Diagram source code can be stored in Git, enabling:

  • Change tracking via commit history
  • Merge conflict detection
  • Pull request reviews with diff-based feedback
  • Branch-based diagram prototyping

Platform Support: GitHub, GitLab, Notion, Obsidian, and dozens of documentation platforms natively render Mermaid blocks.

No License Dependencies: Unlike Microsoft Visio or Lucidchart, Mermaid is open-source and requires no subscriptions.

Why it matters: Developers spend less time formatting and more time capturing logic. System architects can iterate on designs in issue comments and merge requests, shortening feedback loops by hours or days.


Getting Started: Basic Syntax

How to Declare Mermaid in Markdown

In any Markdown file, wrap your diagram code in a code block with the mermaid language identifier:

1
2
3
​```
[diagram code here]
​```

When rendered on GitHub or GitLab, this block becomes an iframe that loads Mermaid.js and converts your text into a SVG diagram.

Supported Platforms & Versions

PlatformSupportNotes
GitHub✅ YesEnabled 2022; works on Issues, PRs, Wikis, .md files
GitLab✅ YesGitLab 13.0+; Mermaid 8.4.8 bundled
Notion✅ YesNative support in code blocks
Obsidian✅ YesRequires optional plugin; local rendering
Local Markdown Viewers⚠️ ConditionalRequires mermaid.js CDN script
Static Site Generators⚠️ VariesJekyll, Hugo, 11ty need plugins (e.g., mermaid-filter)

For local HTML rendering, include the Mermaid CDN in your document head:

1
2
3
4
5
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
  mermaid.initialize({ startOnLoad: true });
  mermaid.contentLoaded();
</script>

Why it matters: While GitHub and GitLab render Mermaid automatically, teams using static sites or local-first tools need to ensure the Mermaid library is available.


Diagram Types & Syntax

1. Flowcharts (Flowchart)

Flowcharts depict process steps using geometric shapes (nodes) and directional arrows (edges). They are ideal for decision trees, troubleshooting workflows, and business processes.

Basic Syntax

1
2
3
4
5
6
flowchart TD
    A[Start] --> B{Is it?}
    B -->|Yes| C[OK]
    C --> D[Rethink]
    D --> B
    B ---->|No| E[End]

Node Shapes

ShapeSyntaxExample
Rectangleid[text]A[Process]
Rounded Boxid(text)B(Rounded)
Diamondid{text}C{Decision}
Circleid((text))D((Loop))
Cylinder (Database)id[(text)]E[(Database)]
Subroutineid[[text]]F[[Function]]
Asymmetricid>text]G>Flag]
Trapezoidid[/text/]H[/Input/]

Direction Modifiers

DirectionSyntaxOrientation
Top-DownTD or TBVertical flow downward
Bottom-TopBTVertical flow upward
Left-RightLRHorizontal flow right
Right-LeftRLHorizontal flow left
TypeSyntaxAppearance
ArrowA --> BSolid arrow
DottedA -.-> BDashed line with arrow
ThickA ==> BBold solid arrow
Text on Link`A –>label| B`
Long LinkA ---> BExtra-long edge (add more dashes)

Complete Flowchart Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
flowchart LR
    A[User Input] --> B{Valid?}
    B -->|Yes| C[Process]
    B -->|No| D[Error]
    C --> E[(Database)]
    D --> F[Log Error]
    E --> G[Output]
    F --> G
    
    classDef processNode fill:#e1f5ff,stroke:#01579b,stroke-width:2px
    classDef errorNode fill:#ffebee,stroke:#b71c1c,stroke-width:2px
    class C,E processNode
    class D,F errorNode

Why it matters: Flowcharts are universally understood by both technical and non-technical stakeholders, making them essential for communicating algorithms, API workflows, and troubleshooting procedures.


2. Sequence Diagrams

Sequence diagrams model interactions between multiple actors (participants) over time, showing the order and dependencies of messages. They are critical for API design, microservices communication, and protocol specification.[7]

Basic Syntax[2]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
sequenceDiagram
    autonumber
    actor C as Client
    participant S as Server
    participant DB as Database
    
    C->>S: Login (Username, Password)
    S->>DB: SELECT user_id WHERE email=?
    note over DB: Password stored as hash+salt
    DB-->>S: user_id, salt, hash
    S->>S: Verify hash(password + salt)
    alt Hash Matches
        S-->>C: 200 OK & JWT Token
    else Auth Failed
        S-->>C: 401 Unauthorized
    end

Participant Types[2]

TypeSyntaxSymbol
Actoractor APerson icon (left edge)
Participantparticipant BBox (vertical lifeline)
Entityentity EDatabase icon
Customparticipant B as LabelAliased name

Message Types[2]

InteractionSyntaxArrow Style
Synchronous (blocking)A->>B: messageSolid arrow
Asynchronous (non-blocking)A--->B: messageOpen arrow
Return / ResponseB-->>A: messageDotted solid arrow
Asynchronous ReturnB--->>A: messageDotted open arrow

Control Flow[2]

StructureSyntax
Notenote over A: text or note right of A: text
Looploop Labelend
Alt (If/Else)alt Conditionelseend
Opt (If)opt Conditionend
Parallelpar Nameandend
Breakbreak Labelend
Activateactivate A / deactivate A
Autonumberautonumber (at top)

Advanced Sequence Diagram

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
sequenceDiagram
    autonumber
    participant User
    participant API
    participant Cache
    participant DB
    
    User->>API: GET /users/123
    API->>Cache: Check cache key
    alt Cache Hit
        Cache-->>API: User data
    else Cache Miss
        API->>DB: Query user by id
        activate DB
        DB-->>API: Return user record
        deactivate DB
        API->>Cache: SET key with TTL
    end
    API-->>User: 200 JSON response
    
    loop Every 5 minutes
        API->>Cache: Refresh expiry
    end

Why it matters: Sequence diagrams force engineers to think through timing, error handling, and dependencies before implementation—reducing bugs and architectural rework.


3. Gantt Charts

Gantt charts visualize project timelines, task dependencies, and work allocation over time. They are essential for project managers, product teams, and cross-functional roadmapping.[8]

Basic Syntax[8]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
gantt
    title Q1 2025 Development Roadmap
    dateFormat YYYY-MM-DD
    axisFormat %Y-%m-%d
    
    section Backend
    API Design :s1, 2025-01-01, 1w
    Implementation :s2, after s1, 3w
    Testing :crit, s3, after s2, 2w
    
    section Frontend
    UI Design :s4, 2025-01-08, 1w
    Development :s5, after s4, 3w
    Integration :s6, after s5, 2w
    
    section DevOps
    Infrastructure :s7, 2025-01-15, 2w
    Deployment :crit, s8, after s7, 1w
    
    milestone Launch :m1, after s8, 1d

Task States[8]

StateSyntaxAppearance
DefaultNoneRegular bar
CompleteddoneStriped bar
ActiveactiveHighlighted bar
CriticalcritRed/bold bar

Task Syntax[8]

1
Task Name : [state], [id], [start], [duration]
  • state (optional): done, active, crit, or milestone
  • id: Unique identifier for dependencies
  • start: Date (YYYY-MM-DD) or after [previous_id]
  • duration: 1w, 3d, 2h, 30m (week, day, hour, minute)

Date Format Options[8]

FormatExampleUse Case
YYYY-MM-DD2025-01-15ISO standard
YYYY/MM/DD2025/01/15Alternative
Relativeafter task_id, 1wDependency-driven

Advanced Gantt with Milestones

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
gantt
    title AI Model Release Timeline (2024-2025)
    dateFormat YYYY-MM-DD
    
    section Models
    GPT-4 Turbo :2023-11-06, 180d
    GPT-4o :2024-05-13, 150d
    o1-preview :2024-09-12, 90d
    
    section Research
    Vision Research :2024-01-01, 365d
    Reasoning Research :crit, 2024-03-01, 240d
    
    milestone GPT-5 Target :m1, 2025-06-01, 1d

Why it matters: Gantt charts enable stakeholders to see task sequencing, critical paths, and realistic delivery dates—essential for managing expectations and allocating resources.


4. Entity-Relationship Diagrams (ER Diagrams)

ER diagrams model database schemas, showing entities (tables), attributes, and relationships using crow’s foot notation.[10]

Basic Syntax[10]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    CUSTOMER }|..|{ DELIVERY-ADDRESS : uses
    
    CUSTOMER {
        string email PK
        string name
        string phone
    }
    
    ORDER {
        int order_id PK
        string order_date
        string status
    }
    
    LINE-ITEM {
        int item_id PK
        int product_id FK
        int quantity
        float price
    }

Crow’s Foot Cardinality[10]

NotationCardinalityMeaning
|o0..1Zero or one
|{1..*One or many
o{0..*Zero or many
||1..1Exactly one

Relationship Syntax[10]

1
ENTITY1 [cardinality1] -- [cardinality2] ENTITY2 : relationship_label

Example: CUSTOMER \|\|--o{ ORDER : places

  • CUSTOMER: 1 or 1 (one customer)
  • ORDER: 0 or many (multiple orders)
  • Label: “places” (from customer perspective)

Advanced ER with Attributes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
erDiagram
    PRODUCT {
        int product_id PK
        string sku UK
        string name
        text description
        float price
        int stock_qty
        datetime created_at
        datetime updated_at
    }
    
    ORDER {
        int order_id PK
        int customer_id FK
        datetime order_date
        string status
        float total_amount
    }
    
    CUSTOMER {
        int customer_id PK
        string email UK
        string name
        string phone
        string country
    }
    
    CUSTOMER ||--o{ ORDER : "1:N"
    PRODUCT o{--|| ORDER : "contained in"

Why it matters: ER diagrams align database architects, backend engineers, and data analysts on schema structure before implementation—preventing costly redesigns.


5. Class Diagrams

Class diagrams model object-oriented structure, showing classes, attributes, methods, and inheritance relationships.[11]

Basic Syntax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
classDiagram
    class Animal {
        +int age
        +String gender
        -String[] DNA
        +isMammal() bool
        +mate() void
    }
    
    class Dog {
        +String breed
        +bark() void
    }
    
    class Cat {
        +bool indoor
        +meow() void
    }
    
    Animal <|-- Dog : Inheritance
    Animal <|-- Cat : Inheritance

Relationship Types[11]

RelationshipSyntaxSymbolMeaning
InheritanceA <|-- B<|B extends A
CompositionA --* B--*A owns B (strong)
AggregationA --o B--oA uses B (weak)
AssociationA --> B-->A knows B
DependencyA ..> B..>A depends on B
RealizationA ..|> B..|>A implements B (interface)

Member Visibility[11]

ModifierSymbolVisibility
Public+Accessible everywhere
Protected#Accessible in subclasses
Private-Accessible only in class
Package~Accessible in package

Complete Class Diagram Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
classDiagram
    class PaymentProcessor {
        #String apiKey
        +processPayment(amount, method) bool
        #validateCard(card) bool
        -encryptData(data) String
    }
    
    class StripeProcessor {
        +processPayment(amount, method) bool
    }
    
    class PayPalProcessor {
        +processPayment(amount, method) bool
    }
    
    PaymentProcessor <|-- StripeProcessor
    PaymentProcessor <|-- PayPalProcessor

Why it matters: Class diagrams facilitate code reviews and onboarding by making the codebase’s structure explicit before diving into implementation details.


Advanced Features & Customization

Styling & Classes

Apply consistent styling to nodes without repeating CSS:[10]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
flowchart TD
    A[Process Step 1]
    B[Process Step 2]
    C[Error Handler]
    
    classDef processStyle fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#000
    classDef errorStyle fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#000
    classDef default fill:#f5f5f5,stroke:#666,stroke-width:1px
    
    class A,B processStyle
    class C errorStyle

Available CSS Properties:

  • fill: Background color (hex)
  • stroke: Border color (hex)
  • stroke-width: Border thickness (px)
  • color: Text color (hex)
  • font-style: italic or normal
  • font-weight: bold or normal

Markdown Formatting in Nodes

Mermaid 10.0+ supports Markdown formatting within node text:[12]

1
2
3
4
flowchart TD
    A["**Bold Text** and *italic text*"]
    B["Line 1<br/>Line 2<br/>Line 3"]
    C["- Item 1<br/>- Item 2<br/>- Item 3"]

Supported Formatting:

  • **text**: Bold
  • *text*: Italic
  • <br/>: Line break
  • Basic Markdown lists

Why it matters: Rich text formatting makes diagrams more readable and reduces the need for accompanying documentation.

Configuration via YAML Frontmatter

For static site generators that parse YAML, configure Mermaid globally:[10]

1
2
3
4
5
6
7
---
config:
  layout: elk
  mermaid:
    theme: dark
    fontFamily: monospace
---

This applies to all diagrams in that document without repetition.


Practical Implementation Tips

1. Using Mermaid Live Editor

For complex diagrams, use Mermaid Live to draft, visualize, and debug in real-time before copying into your repository.[9]

Workflow:

  1. Visit https://mermaid.live
  2. Write diagram code in the left panel
  3. See live preview on the right
  4. Export as SVG or PNG
  5. Copy code into your .md file

2. Incremental Diagram Building

Start with core elements and iteratively add details:[13]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
%% Version 1: Entities only
erDiagram
    CUSTOMER
    ORDER
    PRODUCT

%% Version 2: Add relationships
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ PRODUCT : contains

%% Version 3: Add attributes
erDiagram
    CUSTOMER {
        int id PK
        string email
    }
    ORDER {
        int id PK
        int customer_id FK
    }

This iterative approach makes reviewing and debugging easier.

3. Git-Based Diagram Management

Store diagrams in version control to track evolution:

1
2
3
4
5
# Diagram changes are visible as diffs
git log -p docs/architecture.md | grep "flowchart\|-->"

# Branches can contain diagram experiments
git checkout -b feature/new-workflow-diagram

This is impossible with image-based tools and enables collaborative design iteration.

4. Rendering Diagrams to Static Files (Node.js)

For PDF exports or static hosting, use the Mermaid CLI:[5]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Install
npm install -g @mermaid-js/mermaid-cli

# Render to SVG
mmdc -i diagram.mmd -o diagram.svg

# Render to PNG
mmdc -i diagram.mmd -o diagram.png -w 1200 -H 800

# Batch render
mmdc -i ./diagrams/ -o ./output/

Use Case: Generate diagram snapshots in CI/CD pipelines for technical specifications or PDFs.

5. Integration with GitHub Workflows

Embed diagrams directly in issue templates and pull request descriptions:[1]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
## Architecture Change
This PR updates the authentication flow:

​```
sequenceDiagram
    User->>API: POST /login
    API->>Auth: Verify credentials
    Auth-->>API: JWT token
    API-->>User: 200 OK + token
​```

This enables visual communication without leaving GitHub.

Why it matters: Visual context in issues and PRs reduces misunderstandings and accelerates decision-making.


Common Pitfalls & Troubleshooting

IssueCauseSolution
Diagram not rendering on GitHubMermaid not supported in your fork/repo settingUpdate GitHub (auto-enabled 2022+) or enable in Settings
“mermaid” block renders as codePlatform doesn’t support MermaidUse Mermaid Live → PNG/SVG export
Text overflows node boxesLong labels without breaksUse <br/> or quoted markdown strings
Circular dependencies failGraph has unresolvable cyclesRefactor diagram to be acyclic or use loop construct
Styling not appliedCSS property typoCheck exact property names: stroke-width (not stroke_width)

Summary

  • Mermaid is text-based diagram-as-code that integrates natively with GitHub, GitLab, and modern documentation platforms.
  • 10+ diagram types cover flowcharts, sequences, Gantt charts, ER models, and class diagrams.
  • Version control integration enables diff-based diagram reviews and branch-based iteration.
  • No external tools needed—write and review diagrams in pull requests, issues, and wikis.
  • Start with Mermaid Live for complex diagrams to validate syntax before committing.
  • Styling and Markdown formatting improve readability without sacrificing maintainability.

#Mermaid #Markdown #DiagramAsCode #GitHub #GitLab #TechnicalDocumentation #Flowchart #SequenceDiagram #DevOps #SoftwareArchitecture


References

  • (Include diagrams in your Markdown files with Mermaid, 2024-07-22)[https://github.blog/developer-skills/github/include-diagrams-markdown-files-mermaid/]
  • (Add Flow Chart in Markdown Using Mermaid, 2022-09-20)[https://help.jotterpad.app/en/article/add-flow-chart-in-markdown-using-mermaid-te0vrj/]
  • (Sequence diagram, 2021-01-22)[https://mkdocs-magicspace.alnoda.org/tutorials/markdown/diagrams/]
  • (Use Mermaid syntax to create diagrams, 2020-04-14)[https://www.drawio.com/blog/mermaid-diagrams]
  • (Flowcharts - Basic Syntax, 2025)[https://emersonbottero.github.io/mermaid-docs/syntax/flowchart.html]
  • (Add Sequence Diagram in Markdown Using Mermaid, 2022-09-20)[https://help.jotterpad.app/en/article/add-sequence-diagram-in-markdown-using-mermaid-1ngera4/]
  • (How to install Mermaid to render flowcharts in markdown, 2025-02-09)[https://stackoverflow.com/questions/50762662/how-to-install-mermaid-to-render-flowcharts-in-markdown]
  • (How to Create Stunning Mermaid Diagrams, 2025-08-04)[https://clickup.com/blog/mermaid-diagram-examples/]
  • (Sequence Diagrams in Markdown with Mermaid.js, 2023-04-09)[https://newdevsguide.com/2023/04/10/mermaid-sequence-diagrams/]
  • (Flowchart Basic Syntax, 2025-05-21)[https://docs.mermaidchart.com/mermaid-oss/syntax/flowchart.html]
  • (Entity Relationship Diagram, 2025-04-10)[https://docs.mermaidchart.com/mermaid-oss/syntax/entityRelationshipDiagram.html]
  • (Gantt Diagrams, 2025-04-10)[https://docs.mermaidchart.com/mermaid-oss/syntax/gantt.html]
  • (Support gitlab markdown in mermaid markdown, 2018-01-17)[https://gitlab.com/gitlab-org/gitlab/-/issues/20727]
  • (Mermaid Gantt Chart Timeline Visualization, 2024-09-18)[https://www.youtube.com/watch?v=nXQk6nAiYCk]
  • (GitLab Flavored Markdown: Mermaid, 2020-06-04)[https://everyonecancontribute.cafe/post/2020-06-05-mermaid/]
  • (Markdown Mermaid Type Overview, 2021-11-11)[https://minhan2.tistory.com/entry/Markdown-mermaid-%ED%83%80%EC%9E%85-%EC%A2%85%EB%A5%98]
  • (Why mermaid graph not appear in GitLab, 2019-11-29)[https://stackoverflow.com/questions/59117144/why-mermaid-graph-not-appear-in-gitlab]
  • (Gantt Diagrams, 2023-12-31)[https://docs.mermaidviewer.com/diagrams/gantt.html]
  • (다이어그램? ERD? Mermaid 하나면 끝!, 2021)[https://www.jeong-min.com/47-mermaid/]