Mermaid.js Cheat Sheet

Complete Mermaid.js syntax reference for all diagram types. Click "Copy" on any code block, then open it in the live editor.

Overview

Mermaid.js is a JavaScript-based diagramming language that renders text definitions into SVG diagrams. It is natively supported in GitHub, GitLab, Notion, Obsidian, VS Code (with extensions), and many other tools. Instead of dragging boxes in a GUI, you write plain text and get a diagram — making it version-controllable, diff-able, and paste-able anywhere markdown works.

Every Mermaid diagram starts with a diagram type keyword on the first line: flowchart, sequenceDiagram, gantt, etc. Everything after that follows the syntax for that type. You can embed diagrams in any markdown code block tagged ```mermaid.

Diagram Types at a Glance

KeywordDiagram TypeBest For
flowchart / graphFlowchartProcesses, decisions, pipelines
sequenceDiagramSequence DiagramAPI calls, auth flows, microservices
ganttGantt ChartProject timelines, sprint planning
classDiagramClass DiagramOOP models, design patterns
stateDiagram-v2State DiagramState machines, order lifecycles
erDiagramER DiagramDatabase schema design
piePie ChartProportions, market share
mindmapMind MapBrainstorming, topic structures
gitGraphGit GraphBranch strategies, release flows
timelineTimelineHistory, product roadmaps
quadrantChartQuadrant ChartPriority matrices, 2×2 analysis
xychart-betaXY ChartBar charts, line graphs from data
journeyUser JourneyUX flows, experience mapping
block-betaBlock DiagramSystem architecture, layouts

Global Directives

Apply to any diagram type by placing on the first line:

%%{init: {'theme': 'dark', 'logLevel': 'fatal'}}%%
graph TD
    A --> B

Comments

flowchart TD
    %% This is a comment — ignored by the renderer
    A --> B  %% Inline comment also works

Flowcharts

Direction

graph TD   %% Top to Bottom
graph LR   %% Left to Right
graph BT   %% Bottom to Top
graph RL   %% Right to Left

Node Shapes

flowchart TD
    A[Rectangle]
    B(Rounded)
    C([Stadium])
    D[[Subroutine]]
    E[(Cylinder/DB)]
    F((Circle))
    G{Diamond}
    H{{Hexagon}}
    I>Flag]
    J[/Parallelogram/]
    K[\Parallelogram Alt\]
    L[/Trapezoid\]

Edge Types

flowchart LR
    A --> B           %% Arrow
    A --- B           %% Line
    A -.-> B          %% Dotted arrow
    A ==> B           %% Thick arrow
    A --o B           %% Circle end
    A --x B           %% Cross end
    A -->|label| B    %% Labeled arrow

Subgraphs

flowchart TB
    subgraph "Group Name"
        A --> B
    end
    subgraph Another
        direction LR
        C --> D
    end

Styling

flowchart TD
    A:::myClass --> B
    classDef myClass fill:#f9f,stroke:#333,color:black
    style B fill:#bbf,stroke:#33f

Sequence Diagrams

Basics

sequenceDiagram
    participant A as Alice
    actor U as User
    A->>B: Solid arrow (sync)
    B-->>A: Dotted arrow (response)
    A-)B: Open arrow (async)
    A-xB: Cross (lost message)

Activation

sequenceDiagram
    A->>+B: Request (activate)
    B-->>-A: Response (deactivate)

Blocks

sequenceDiagram
    autonumber

    loop Every 5s
        A->>B: Ping
    end

    alt Success
        B-->>A: 200 OK
    else Failure
        B-->>A: 500 Error
    end

    opt Optional step
        A->>B: Maybe
    end

    par Parallel
        A->>B: Request 1
    and
        A->>C: Request 2
    end

Notes

sequenceDiagram
    Note over A,B: Spanning note
    Note right of B: Side note
    rect rgb(200, 220, 255)
        A->>B: Highlighted section
    end

Gantt Charts

gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    axisFormat %b %d
    excludes weekends

    section Phase 1
    Task 1          :done, t1, 2025-01-01, 7d
    Task 2          :active, t2, after t1, 5d
    Milestone       :milestone, m1, after t2, 0d

    section Phase 2
    Task 3          :t3, after m1, 10d
    Critical task   :crit, t4, after t3, 3d

Task States

  • done — completed
  • active — in progress
  • crit — critical path
  • Combine: crit, done

Class Diagrams

Classes

classDiagram
    class ClassName {
        +String publicAttr
        -int privateAttr
        #bool protectedAttr
        ~float internalAttr
        +publicMethod() void
        -privateMethod(param) String
        +staticMethod()$ int
        +abstractMethod()* void
    }

Relationships

classDiagram
    A <|-- B    : Inheritance
    C *-- D     : Composition
    E o-- F     : Aggregation
    G --> H     : Association
    I ..> J     : Dependency
    K ..|> L    : Realization
    M "1" --> "*" N : Cardinality

Annotations

classDiagram
    class MyInterface {
        <<interface>>
    }
    class MyAbstract {
        <<abstract>>
    }
    class MyEnum {
        <<enumeration>>
        VALUE_A
        VALUE_B
    }

State Diagrams

stateDiagram-v2
    direction LR
    [*] --> Active
    Active --> Inactive : disable
    Inactive --> Active : enable
    Active --> [*] : delete

    state Active {
        [*] --> Running
        Running --> Paused : pause
        Paused --> Running : resume
    }

Special States

stateDiagram-v2
    state check <<choice>>
    state fork_state <<fork>>
    state join_state <<join>>

    note right of Active
        This is a note
    end note

ER Diagrams

erDiagram
    CUSTOMER {
        int id PK
        string name
        string email UK
    }
    ORDER {
        int id PK
        int customer_id FK
        date ordered_at
    }
    CUSTOMER ||--o{ ORDER : places

Cardinality

  • || — exactly one
  • o| — zero or one
  • }| — one or more
  • }o — zero or more
  • -- solid (identifying) / .. dashed (non-identifying)

Pie Charts

pie title Distribution
    "Category A" : 40
    "Category B" : 30
    "Category C" : 20
    "Other" : 10

Add showData after pie to show raw values.

Mind Maps

mindmap
    root((Central Topic))
        Branch 1
            Sub-topic A
            Sub-topic B
        Branch 2
            Sub-topic C
                Detail 1
                Detail 2
        Branch 3

Git Graphs

gitGraph
    commit
    commit
    branch develop
    checkout develop
    commit
    commit
    checkout main
    merge develop
    commit

Timeline

timeline
    title History
    2020 : Founded
         : MVP launched
    2021 : Series A
         : Reached 10k users
    2022 : Series B
         : International expansion

Quadrant Chart

Quadrant charts plot items on a 2×2 matrix — ideal for priority matrices (effort vs. impact), BCG portfolio grids (market share vs. growth), or any “rank by two dimensions” analysis. Items above or below the axes get labelled automatically.

quadrantChart
    title Feature Priority Matrix
    x-axis Low Effort --> High Effort
    y-axis Low Impact --> High Impact
    quadrant-1 Quick Wins
    quadrant-2 Major Projects
    quadrant-3 Fill-ins
    quadrant-4 Hard Slogs
    Auth refactor: [0.3, 0.8]
    Dark mode: [0.2, 0.4]
    AI assistant: [0.85, 0.95]
    Export to PDF: [0.6, 0.5]
    Onboarding flow: [0.4, 0.75]

Axis Labels

Both axes range from 0 (left/bottom) to 1 (right/top). Point coordinates are [x, y] values within that range. Labels use the quadrant-1 through quadrant-4 keys (top-right, top-left, bottom-left, bottom-right).

quadrantChart
    title Boston Consulting Group Matrix
    x-axis Low Market Share --> High Market Share
    y-axis Low Growth --> High Growth
    quadrant-1 Stars
    quadrant-2 Question Marks
    quadrant-3 Dogs
    quadrant-4 Cash Cows
    Product A: [0.7, 0.8]
    Product B: [0.2, 0.7]
    Product C: [0.8, 0.2]
    Product D: [0.15, 0.15]

XY Chart

XY charts (introduced in Mermaid 10.x as xychart-beta) render bar charts and line charts from raw data arrays. Unlike Gantt or pie, XY charts work from explicit numeric datasets — great for revenue trends, performance benchmarks, and survey results.

Bar Chart

xychart-beta
    title "Monthly Revenue (USD)"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Revenue" 0 --> 50000
    bar [12000, 18000, 15000, 22000, 31000, 45000]

Line Chart

xychart-beta
    title "Weekly Active Users"
    x-axis [W1, W2, W3, W4, W5, W6, W7, W8]
    y-axis "Users" 0 --> 10000
    line [1200, 2400, 3100, 4000, 5200, 6800, 7500, 9200]

Combined Bar + Line

xychart-beta
    title "Revenue vs Target"
    x-axis [Q1, Q2, Q3, Q4]
    y-axis "Amount ($k)" 0 --> 200
    bar [80, 110, 130, 160]
    line [100, 100, 150, 150]

User Journey

User journey diagrams (keyword: journey) map the steps a user takes to complete a task, with a satisfaction score (1–5) and which actor performs each step. Perfect for UX research, onboarding analysis, and customer experience mapping.

journey
    title User Onboarding Journey
    section Discovery
        Find product via Google: 4: User
        Read landing page: 3: User
        Watch demo video: 5: User
    section Sign Up
        Click Sign Up button: 5: User
        Fill registration form: 2: User
        Verify email: 3: User
    section First Use
        Complete onboarding wizard: 4: User, System
        Create first project: 5: User
        Invite team member: 4: User

E-commerce Purchase Journey

journey
    title Online Purchase Journey
    section Awareness
        Search on Google: 3: Customer
        See ad on social media: 2: Customer
    section Consideration
        Browse product page: 4: Customer
        Compare with alternatives: 3: Customer
        Read reviews: 4: Customer
    section Purchase
        Add to cart: 5: Customer
        Enter shipping info: 2: Customer
        Payment: 3: Customer, System
        Confirmation email: 5: System
    section Post-Purchase
        Track package: 4: Customer, Courier
        Receive delivery: 5: Customer, Courier
        Leave review: 4: Customer

Scores range 1 (terrible experience) to 5 (delightful). Multiple actors per step show who is responsible. Low-score steps are your highest-priority UX improvement targets.

Block Diagram

Block diagrams (block-beta, introduced in Mermaid 10.9) arrange rectangular blocks in a grid layout. Unlike flowcharts, you control the column count explicitly — making them ideal for system architecture, hardware layouts, and spatial arrangements where position carries meaning.

Basic Grid Layout

block-beta
    columns 3
    A["Frontend"] B["API Gateway"] C["Auth Service"]
    D["Database"] E["Cache"] F["Storage"]
    A --> B
    B --> C
    B --> D
    B --> E

System Architecture

block-beta
    columns 1
    block:internet["Internet"]
        LB["Load Balancer"]
    end
    block:app["Application Tier"]
        columns 3
        WEB1["Web Server 1"]
        WEB2["Web Server 2"]
        WEB3["Web Server 3"]
    end
    block:data["Data Tier"]
        columns 2
        PG["PostgreSQL Primary"]
        CACHE["Redis Cache"]
    end
    internet --> app
    app --> data

Block Shapes

block-beta
    columns 4
    A["Rectangle"]
    B("Rounded")
    C(("Circle"))
    D{"Diamond"}
    E[/"Parallelogram"/]
    F[["Subroutine"]]
    G(["Stadium"])
    H[("Database")]

Block shapes use the same bracket syntax as flowchart nodes. Connections between blocks use --> just like flowcharts. Blocks not connected by arrows are still laid out in grid order.

Themes & Config

%%{init: {'theme': 'dark'}}%%
graph TD
    A --> B

Available themes: default, dark, forest, neutral, base

Tips

  • Use %% for comments
  • Wrap special characters in quotes: A["Text (parens)"]
  • Use <br/> for line breaks in labels

Tips & Common Gotchas

Special Characters in Labels

Parentheses, quotes, and angle brackets inside node labels will break parsing. Wrap labels in double quotes to escape them:

flowchart TD
    A["validate(email)"] --> B["returns bool"]
    C["Error: 404 Not Found"] --> D["Retry < 3 times?"]

Line Breaks Inside Labels

flowchart TD
    A["Line one<br/>Line two"] --> B["Also works<br/>in rounded nodes"]

Long Labels on Arrows

flowchart LR
    A -->|"Short label"| B
    C -->|"Longer label that<br/>wraps to two lines"| D

Subgraph Direction Override

The outer flowchart direction and inner subgraph direction can differ:

flowchart TB
    subgraph horizontal["Runs Left-Right"]
        direction LR
        A --> B --> C
    end
    subgraph vertical["Runs Top-Down"]
        direction TB
        D --> E --> F
    end
    horizontal --> vertical

Reusing Node IDs

Once defined, reference a node by its ID without re-declaring its shape. Repeating the shape definition on second use creates a duplicate visual:

flowchart TD
    A[Start] --> B{Check}
    B --> C[Process]
    C --> B    %% reference B again — no shape brackets needed
    B --> D[End]

Sequence Diagram: Autonumber

sequenceDiagram
    autonumber
    A->>B: First message (1)
    B-->>A: Response (2)
    A->>C: Another (3)

Gantt: Exclude Weekends & Specific Dates

gantt
    dateFormat YYYY-MM-DD
    excludes weekends, 2025-12-25, 2026-01-01
    section Work
    Task A :2025-12-22, 7d

ThemeVariables for Fine-Grained Color Control

%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#7c3aed',
    'primaryTextColor': '#ffffff',
    'primaryBorderColor': '#5b21b6',
    'lineColor': '#6b7280',
    'secondaryColor': '#ddd6fe',
    'tertiaryColor': '#f3f4f6'
  }
}}%%
flowchart TD
    A[Branded Node] --> B[Another Node]

Click Events (Interactive Diagrams)

flowchart TD
    A[Go to Docs] --> B[Go to Editor]
    click A href "https://mermaid.js.org/intro/" _blank
    click B href "https://mermaideditor.lol" _self

Entity Relationship: Self-Referencing

erDiagram
    CATEGORY {
        int id PK
        string name
        int parent_id FK
    }
    CATEGORY ||--o{ CATEGORY : "has subcategory"

Pro tip: Test any syntax live

Paste any code block from this cheat sheet into the Mermaid Live Editor to see it render instantly. No sign-up, no install required.