Mermaid Diagram Syntax Guide

A comprehensive reference for every Mermaid diagram type. Each section includes syntax, examples, and a link to try it live in the editor.

1. Flowcharts

Flowcharts are the most commonly used Mermaid diagram. Use them to describe processes, decision trees, system architectures, or any step-by-step flow.

Basic syntax

A flowchart starts with flowchart followed by a direction:TD (top-down), LR (left-right), BT (bottom-top), or RL (right-left).

Simple flowchart
flowchart TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B
Open in Editor →

Node shapes

All node shapes
flowchart LR
    A[Rectangle]
    B(Rounded)
    C([Stadium])
    D[[Subroutine]]
    E[(Database)]
    F((Circle))
    G>Asymmetric]
    H{Diamond}
    I{{Hexagon}}
    J[/Parallelogram/]
    K[\Parallelogram alt\]
    L[/Trapezoid\]
    M[\Trapezoid alt/]
Open in Editor →

Link types

Different link styles
flowchart LR
    A --> B
    A --- C
    A -.- D
    A -.-> E
    A ==> F
    A -- text --> G
    A -. dotted .-> H
    A == thick ==> I
Open in Editor →

Subgraphs and styling

Practical example with subgraphs
flowchart TD
    subgraph Frontend
        A[React App] --> B[API Client]
    end
    subgraph Backend
        C[Express Server] --> D[(PostgreSQL)]
        C --> E[(Redis Cache)]
    end
    B --> C
    style A fill:#e1f5fe
    style D fill:#fff3e0
Open in Editor →
Tips: Use %% for comments. Node IDs must be unique across the entire diagram, including across subgraphs. If you need special characters in labels, wrap them in quotes: A["Node with (parens)"].

2. Sequence Diagrams

Sequence diagrams show how objects or services interact over time. They are ideal for documenting API flows, authentication handshakes, or any request-response exchange.

Basic syntax

Simple request-response
sequenceDiagram
    participant C as Client
    participant S as Server
    participant DB as Database
    C->>S: GET /users
    S->>DB: SELECT * FROM users
    DB-->>S: rows
    S-->>C: 200 OK (JSON)
Open in Editor →

Message types

All arrow types
sequenceDiagram
    A->>B: Solid with arrowhead
    A-->>B: Dotted with arrowhead
    A-xB: Solid with cross
    A--xB: Dotted with cross
    A-)B: Solid with open arrow
    A--)B: Dotted with open arrow
Open in Editor →

Activations, notes, loops, and alternatives

Advanced sequence diagram
sequenceDiagram
    actor U as User
    participant A as Auth Service
    participant API as API Gateway

    U->>A: Login (email, password)
    activate A
    A->>A: Validate credentials
    alt Valid credentials
        A-->>U: JWT token
        Note right of A: Token expires in 1h
        U->>API: Request + JWT
        activate API
        API->>A: Verify token
        A-->>API: Token valid
        API-->>U: 200 Response
        deactivate API
    else Invalid credentials
        A-->>U: 401 Unauthorized
    end
    deactivate A

    loop Every 55 minutes
        U->>A: Refresh token
        A-->>U: New JWT
    end
Open in Editor →
Tips: Use actor instead of participant to render a stick-figure icon. Use autonumber after sequenceDiagram to automatically number each message. Notes can be placed left of, right of, or over participants.

3. Class Diagrams

Class diagrams describe the structure of a system by showing classes, their attributes, methods, and relationships. Useful for OOP design and domain modelling.

Basic syntax

Defining classes
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound() void
    }
    class Dog {
        +String breed
        +fetch() void
    }
    class Cat {
        +bool isIndoor
        +purr() void
    }
    Animal <|-- Dog
    Animal <|-- Cat
Open in Editor →

Relationship types

All relationship arrows
classDiagram
    classA <|-- classB : Inheritance
    classC *-- classD : Composition
    classE o-- classF : Aggregation
    classG <-- classH : Association
    classI -- classJ : Link (solid)
    classK <.. classL : Dependency
    classM <|.. classN : Realization
    classO .. classP : Link (dashed)
Open in Editor →

Practical example with interfaces and multiplicity

E-commerce domain model
classDiagram
    class Order {
        +String id
        +Date createdAt
        +calculateTotal() float
        +cancel() void
    }
    class OrderItem {
        +String productId
        +int quantity
        +float unitPrice
    }
    class Customer {
        +String email
        +String name
        +placeOrder() Order
    }
    class Payment {
        <<interface>>
        +process() bool
        +refund() bool
    }
    class StripePayment {
        +String stripeId
        +process() bool
        +refund() bool
    }

    Customer "1" --> "*" Order : places
    Order "1" *-- "1..*" OrderItem : contains
    Payment <|.. StripePayment
    Order --> Payment : uses
Open in Editor →
Tips: Visibility modifiers: + public, - private, # protected, ~ package/internal. Use <<interface>>, <<abstract>>, or <<enumeration>> as class annotations.

4. State Diagrams

State diagrams model the different states of an object and the transitions between them. Great for workflows, order lifecycles, or UI state machines.

Basic syntax

Simple state machine
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : submit
    Processing --> Success : done
    Processing --> Error : fail
    Error --> Idle : retry
    Success --> [*]
Open in Editor →

Composite states, notes, and forks

Order lifecycle
stateDiagram-v2
    [*] --> Pending

    state Pending {
        [*] --> Validating
        Validating --> Confirmed : valid
        Validating --> Rejected : invalid
    }

    Pending --> Processing : payment received
    Processing --> Shipped : dispatch

    state Shipped {
        [*] --> InTransit
        InTransit --> OutForDelivery
        OutForDelivery --> Delivered
    }

    Shipped --> Completed : delivered
    Completed --> [*]

    Processing --> Cancelled : cancel request
    Pending --> Cancelled : cancel request
    Cancelled --> [*]

    note right of Processing
        Payment must be confirmed
        before processing begins
    end note
Open in Editor →
Tips: Always use stateDiagram-v2 (not the legacy stateDiagram). The [*] symbol represents start and end states. Composite (nested) states are defined with state Name { ... }.

5. ER Diagrams

Entity-Relationship diagrams describe database schemas. Use them to plan tables, columns, and the relationships between entities before writing migrations.

Basic syntax

Simple ER diagram
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    PRODUCT ||--o{ LINE_ITEM : "is in"
Open in Editor →

Cardinality notation

Left side of -- describes cardinality from left entity; right side describes cardinality from right entity.

SymbolMeaning
||Exactly one
o|Zero or one
|{One or more
o{Zero or more

Practical example with attributes

Blog database schema
erDiagram
    USER {
        int id PK
        string email UK
        string name
        datetime created_at
    }
    POST {
        int id PK
        string title
        text body
        datetime published_at
        int author_id FK
    }
    COMMENT {
        int id PK
        text content
        datetime created_at
        int post_id FK
        int user_id FK
    }
    TAG {
        int id PK
        string name UK
    }
    POST_TAG {
        int post_id FK
        int tag_id FK
    }

    USER ||--o{ POST : writes
    USER ||--o{ COMMENT : writes
    POST ||--o{ COMMENT : has
    POST ||--o{ POST_TAG : ""
    TAG ||--o{ POST_TAG : ""
Open in Editor →
Tips: Attribute types are free-form strings (e.g., int, string, varchar(255)). Append PK, FK, or UK to mark primary keys, foreign keys, and unique keys. Entity names are case-sensitive and cannot contain spaces.

6. Gantt Charts

Gantt charts visualize project schedules. Each task has a start date and duration, and you can model dependencies between tasks.

Basic syntax

Simple project timeline
gantt
    title Project Launch Plan
    dateFormat YYYY-MM-DD

    section Planning
    Requirements     :a1, 2025-01-01, 14d
    Architecture     :a2, after a1, 7d

    section Development
    Backend API      :b1, after a2, 21d
    Frontend UI      :b2, after a2, 21d
    Integration      :b3, after b1, 7d

    section Launch
    QA Testing       :c1, after b3, 10d
    Deploy to prod   :milestone, c2, after c1, 0d
Open in Editor →

Task states and advanced features

Tasks with different states
gantt
    title Sprint 12 Progress
    dateFormat YYYY-MM-DD
    excludes weekends

    section Auth
    Login page           :done,    auth1, 2025-03-01, 3d
    OAuth integration    :active,  auth2, after auth1, 4d
    2FA support          :         auth3, after auth2, 5d

    section Dashboard
    Layout               :done,    dash1, 2025-03-01, 2d
    Charts               :active,  dash2, after dash1, 4d
    Export feature       :crit,    dash3, after dash2, 3d

    section Testing
    Unit tests           :         test1, after auth3, 3d
    E2E tests            :         test2, after dash3, 3d
Open in Editor →
Tips: Task states: done, active, crit (critical path). Use excludes weekends to skip Saturdays and Sundays. Use milestone with 0d duration for milestones. Dependencies are declared with after taskId.

7. Pie Charts

Pie charts display proportional data. They are the simplest Mermaid diagram type — just a title and data slices.

Basic syntax

Simple pie chart
pie title Browser Market Share (2025)
    "Chrome" : 65
    "Safari" : 19
    "Firefox" : 3
    "Edge" : 5
    "Other" : 8
Open in Editor →

Practical example

Time allocation
pie showData title Weekly Time Allocation
    "Coding" : 20
    "Code Review" : 5
    "Meetings" : 8
    "Planning" : 3
    "Documentation" : 2
    "Learning" : 2
Open in Editor →
Tips: Values are relative — Mermaid automatically calculates percentages. Add showData after pie to display raw values alongside the chart. Labels must be in double quotes.

8. Git Graphs

Git graphs visualize branching and merging strategies. Use them to document your Git workflow, illustrate rebasing, or explain branching models.

Basic syntax

Simple Git flow
gitGraph
    commit
    commit
    branch develop
    checkout develop
    commit
    commit
    checkout main
    merge develop
    commit
Open in Editor →

Practical example — feature branch workflow

Feature branch workflow
gitGraph
    commit id: "init"
    commit id: "base setup"
    branch develop
    commit id: "dev config"

    branch feature/auth
    commit id: "login page"
    commit id: "OAuth"
    checkout develop
    merge feature/auth id: "merge auth"

    branch feature/dashboard
    commit id: "layout"
    commit id: "charts"
    checkout develop
    merge feature/dashboard id: "merge dashboard"

    checkout main
    merge develop id: "v1.0" tag: "v1.0"
    commit id: "hotfix"
    checkout develop
    cherry-pick id: "hotfix"
Open in Editor →
Tips: Use id: "label" to name commits. Use tag: "v1.0" to add tags. The cherry-pick command references a commit by its id. Branch names cannot contain spaces.

9. Mindmaps

Mindmaps visualize hierarchical information radiating from a central concept. They are great for brainstorming, topic overviews, and knowledge organization.

Basic syntax

Indentation defines the hierarchy. Each level is indented further with spaces.

Simple mindmap
mindmap
  root((Project))
    Planning
      Requirements
      Timeline
      Budget
    Development
      Frontend
      Backend
      Database
    Launch
      QA
      Deployment
      Monitoring
Open in Editor →

Node shapes and practical example

Technology overview
mindmap
  root((Full Stack))
    Frontend
      React
        Next.js
        Remix
      Vue
        Nuxt
      Svelte
        SvelteKit
    Backend
      Node.js
        Express
        Fastify
      Python
        Django
        FastAPI
      Go
        Gin
        Echo
    Database
      SQL
        PostgreSQL
        MySQL
      NoSQL
        MongoDB
        Redis
    DevOps
      CI/CD
        GitHub Actions
        GitLab CI
      Cloud
        AWS
        Vercel
Open in Editor →
Tips: Node shapes in mindmaps: root((Circle)), id[Square], id(Rounded), id)Cloud(, id{{Hexagon}}. Only the root node is required to have a shape. Indentation must be consistent (use spaces, not tabs).

Quick Reference

Common patterns at a glance. Bookmark this section for day-to-day use.

Diagram declarations

DiagramOpening line
Flowchartflowchart TD
SequencesequenceDiagram
ClassclassDiagram
StatestateDiagram-v2
ERerDiagram
Ganttgantt
Piepie title My Title
Git GraphgitGraph
Mindmapmindmap

Flowchart directions

CodeDirection
TD / TBTop to bottom
BTBottom to top
LRLeft to right
RLRight to left

Flowchart node shapes

SyntaxShape
A[text]Rectangle
A(text)Rounded rectangle
A([text])Stadium / pill
A{text}Diamond / decision
A{{text}}Hexagon
A((text))Circle
A[(text)]Cylinder / database
A>text]Asymmetric / flag
A[/text/]Parallelogram
A[/text\]Trapezoid

Flowchart link types

SyntaxDescription
A --> BArrow
A --- BLine (no arrow)
A -.-> BDotted arrow
A ==> BThick arrow
A -- "text" --> BArrow with label
A --o BCircle end
A --x BCross end
A <--> BBidirectional

Sequence diagram arrows

SyntaxDescription
->>Solid line, arrowhead
-->>Dotted line, arrowhead
-xSolid line, cross
--xDotted line, cross
-)Solid line, open arrow (async)
--)Dotted line, open arrow (async)

Class diagram relationships

SyntaxRelationship
<|--Inheritance
*--Composition
o--Aggregation
<--Association
<|..Realization
<..Dependency

ER diagram cardinality

SyntaxMeaning
||--||One to one
||--o{One to zero-or-more
||--|{One to one-or-more
o|--o{Zero-or-one to zero-or-more

Common Mermaid directives

DirectivePurpose
%% commentSingle-line comment
%%{init: {...}}%%Configuration block (theme, look, etc.)
style nodeId fill:#f9fInline node styling
classDef name fill:#f9fDefine reusable style class
class nodeId nameApply style class to node
click nodeId href "url"Make node clickable