Mermaid.js allows you to create diagrams using text-based syntax. This post shows how to create various diagram types, from simple flowcharts to complex system architectures. Each example includes both the code and its rendered result.

1. Basic Flowchart

Here’s the code:

flowchart LR
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B

Which renders as:

flowchart LR A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> B

2. Sequence Diagram

The code:

sequenceDiagram
    participant Browser
    participant API
    participant DB
    
    Browser->>API: GET /data
    API->>DB: Query
    DB-->>API: Results
    API-->>Browser: Response

Renders as:

sequenceDiagram participant Browser participant API participant DB Browser->>API: GET /data API->>DB: Query DB-->>API: Results API-->>Browser: Response

3. State Diagram

The code:

stateDiagram-v2
    [*] --> Still
    Still --> [*]
    Still --> Moving
    Moving --> Still
    Moving --> Crash
    Crash --> [*]

Renders as:

stateDiagram-v2 [*] --> Still Still --> [*] Still --> Moving Moving --> Still Moving --> Crash Crash --> [*]

4. Class Diagram

The code:

classDiagram
    Animal <|-- Duck
    Animal <|-- Fish
    Animal : +String species
    Animal : +int age
    Animal: +makeSound()
    class Duck{
        +String beakColor
        +swim()
        +quack()
    }

Renders as:

classDiagram Animal <|-- Duck Animal <|-- Fish Animal : +String species Animal : +int age Animal: +makeSound() class Duck{ +String beakColor +swim() +quack() }

5. Gantt Chart

The code:

gantt
    title A Gantt Chart
    dateFormat YYYY-MM-DD
    section Section 1
    Task 1    :a1, 2024-01-01, 30d
    Task 2    :after a1, 20d
    section Section 2
    Task 3    :2024-02-01, 12d
    Task 4    :24d

Renders as:

gantt title A Gantt Chart dateFormat YYYY-MM-DD section Section 1 Task 1 :a1, 2024-01-01, 30d Task 2 :after a1, 20d section Section 2 Task 3 :2024-02-01, 12d Task 4 :24d

6. Git Graph

The code:

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

Renders as:

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

7. Entity Relationship Diagram

The code:

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    CUSTOMER {
        string name
        string email
    }
    ORDER {
        int id
        string status
    }
    LINE_ITEM {
        string product
        int quantity
    }

Renders as:

erDiagram CUSTOMER ||--o{ ORDER : places ORDER ||--|{ LINE_ITEM : contains CUSTOMER { string name string email } ORDER { int id string status } LINE_ITEM { string product int quantity }

8. Pie Chart

The code:

pie
    title What do we spend time on?
    "Development" : 40
    "Testing" : 20
    "Documentation" : 15
    "Meetings" : 25

Renders as:

pie title What do we spend time on? "Development" : 40 "Testing" : 20 "Documentation" : 15 "Meetings" : 25

9. User Journey

The code:

journey
    title My working day
    section Go to work
      Make tea: 5: Me
      Go upstairs: 3: Me
      Do work: 1: Me, Cat
    section Go home
      Go downstairs: 5: Me
      Sit down: 3: Me

Renders as:

journey title My working day section Go to work Make tea: 5: Me Go upstairs: 3: Me Do work: 1: Me, Cat section Go home Go downstairs: 5: Me Sit down: 3: Me

10. Flowchart with Styling

The code:

flowchart LR
    A[Hard] -->|Text| B(Round)
    B --> C{Decision}
    C -->|One| D[Result 1]
    C -->|Two| E[Result 2]
    
    style A fill:#f9f,stroke:#333,stroke-width:4px
    style B fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff
    style C fill:#9f9,stroke:#333,stroke-width:2px

Renders as:

flowchart LR A[Hard] -->|Text| B(Round) B --> C{Decision} C -->|One| D[Result 1] C -->|Two| E[Result 2] style A fill:#f9f,stroke:#333,stroke-width:4px style B fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff style C fill:#9f9,stroke:#333,stroke-width:2px

11. Quadrant Chart

The code:

quadrantChart
    title Prioritize Features
    x-axis Low Priority --> High Priority
    y-axis Low Impact --> High Impact
    quadrant-1 Quick Wins
    quadrant-2 Major Projects
    quadrant-3 Time Sinks
    quadrant-4 Back Burner
    User Authentication: [0.4, 0.3]
    Search Feature: [0.95, 0.95]
    Dark Mode: [0.2, 0.15]
    File Export: [0.85, 0.35]
    Mobile Support: [0.9, 0.8]

Renders as:

quadrantChart title Prioritize Features x-axis Low Priority --> High Priority y-axis Low Impact --> High Impact quadrant-1 Quick Wins quadrant-2 Major Projects quadrant-3 Time Sinks quadrant-4 Back Burner User Authentication: [0.4, 0.3] Search Feature: [0.95, 0.95] Dark Mode: [0.2, 0.15] File Export: [0.85, 0.35] Mobile Support: [0.9, 0.8]

12. Mindmap

The code:

mindmap
    root((DevOps))
        Development
            Version Control
                Git
                SVN
            Languages
                JavaScript
                Python
                Go
            Testing
                Unit Tests
                Integration Tests
        Operations
            Infrastructure
                Servers
                Cloud
                    AWS
                    Azure
                    GCP
            Monitoring
                Logging
                Metrics
                Alerts
            Deployment
                CI/CD
                Containers
                    Docker
                    Kubernetes

Renders as:

mindmap root((DevOps)) Development Version Control Git SVN Languages JavaScript Python Go Testing Unit Tests Integration Tests Operations Infrastructure Servers Cloud AWS Azure GCP Monitoring Logging Metrics Alerts Deployment CI/CD Containers Docker Kubernetes

13. Timeline

The code:

timeline
    title History of Programming Languages
    section 1950s
        FORTRAN : 1957
        LISP : 1958
    section 1960s
        BASIC : 1964
        Pascal : 1969
    section 1970s
        C : 1972
        SQL : 1974
    section 1980s
        C++ : 1983
        Perl : 1987
    section 1990s
        Python : 1991
        Java : 1995
        JavaScript : 1995
    section 2000s
        C# : 2000
        Scala : 2004

Renders as:

timeline title History of Programming Languages section 1950s FORTRAN : 1957 LISP : 1958 section 1960s BASIC : 1964 Pascal : 1969 section 1970s C : 1972 SQL : 1974 section 1980s C++ : 1983 Perl : 1987 section 1990s Python : 1991 Java : 1995 JavaScript : 1995 section 2000s C# : 2000 Scala : 2004

14. Requirement Diagram

The code:

requirementDiagram
    requirement test_req {
        id: 1
        text: Authentication System
        risk: high
        verifymethod: test
    }

    functionalRequirement test_req2 {
        id: 1.1
        text: User Login
        risk: medium
        verifymethod: demonstration
    }

    performanceRequirement test_req3 {
        id: 1.2
        text: Password Encryption
        risk: high
        verifymethod: test
    }

    element test_entity {
        type: simulation
    }

    test_req - satisfies -> test_req2
    test_req2 - traces -> test_req3
    test_req - contains -> test_req3
    test_entity - verifies -> test_req

Renders as:

requirementDiagram requirement test_req { id: 1 text: Authentication System risk: high verifymethod: test } functionalRequirement test_req2 { id: 1.1 text: User Login risk: medium verifymethod: demonstration } performanceRequirement test_req3 { id: 1.2 text: Password Encryption risk: high verifymethod: test } element test_entity { type: simulation } test_req - satisfies -> test_req2 test_req2 - traces -> test_req3 test_req - contains -> test_req3 test_entity - verifies -> test_req

15. C4 Basic Diagram

The code:

C4Context
    title System Context diagram for Internet Banking System
    Person(customerA, "Banking Customer", "A customer of the bank, with personal bank accounts")
    Container_Boundary(c1, "Internet Banking") {
        System(systemAA, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.")
    }
    Boundary(b1, "Bank") {
        SystemDb_Ext(SystemE, "Mainframe Banking System", "Stores all of the core banking information about customers, accounts, transactions, etc.")
    }
    
    BiRel(customerA, systemAA, "Uses")
    Rel(systemAA, SystemE, "Uses")

Renders as:

C4Context title System Context diagram for Internet Banking System Person(customerA, "Banking Customer", "A customer of the bank, with personal bank accounts") Container_Boundary(c1, "Internet Banking") { System(systemAA, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.") } Boundary(b1, "Bank") { SystemDb_Ext(SystemE, "Mainframe Banking System", "Stores all of the core banking information about customers, accounts, transactions, etc.") } BiRel(customerA, systemAA, "Uses") Rel(systemAA, SystemE, "Uses")

16. C4 Complex Diagram

The code:

C4Context
    title Complex System Architecture
    Person(user, "End User", "A user of the system")
    
    Enterprise_Boundary(eb1, "Company System") {
        System_Boundary(sb1, "Frontend") {
            Container(web, "Web Application", "React", "Provides user interface")
            Container(mobile, "Mobile App", "React Native", "Mobile interface")
        }
        
        System_Boundary(sb2, "Backend") {
            Container(api, "API Gateway", "Node.js", "Handles API requests")
            ContainerDb(db1, "User Database", "PostgreSQL", "Stores user data")
            Container(auth, "Auth Service", "Go", "Handles authentication")
            ContainerQueue(queue, "Message Queue", "RabbitMQ", "Message broker")
        }
        
        System_Boundary(sb3, "Processing") {
            Container(worker, "Worker Service", "Python", "Processes background jobs")
            ContainerDb(db2, "Analytics DB", "MongoDB", "Stores analytics")
        }
    }
    
    System_Ext(email, "Email System", "Sends emails to users")
    System_Ext(payment, "Payment Gateway", "Processes payments")
    
    Rel(user, web, "Uses", "HTTPS")
    Rel(user, mobile, "Uses", "HTTPS")
    BiRel(web, api, "API calls", "REST/HTTPS")
    BiRel(mobile, api, "API calls", "REST/HTTPS")
    
    Rel(api, auth, "Authenticates", "gRPC")
    Rel(api, db1, "Reads/Writes", "SQL")
    Rel(api, queue, "Publishes", "AMQP")
    
    Rel(worker, queue, "Subscribes", "AMQP")
    Rel(worker, db2, "Stores results", "MongoDB Protocol")
    
    Rel(api, email, "Sends emails", "SMTP")
    Rel(api, payment, "Processes", "HTTPS")

Renders as:

C4Context title Complex System Architecture Person(user, "End User", "A user of the system") Enterprise_Boundary(eb1, "Company System") { System_Boundary(sb1, "Frontend") { Container(web, "Web Application", "React", "Provides user interface") Container(mobile, "Mobile App", "React Native", "Mobile interface") } System_Boundary(sb2, "Backend") { Container(api, "API Gateway", "Node.js", "Handles API requests") ContainerDb(db1, "User Database", "PostgreSQL", "Stores user data") Container(auth, "Auth Service", "Go", "Handles authentication") ContainerQueue(queue, "Message Queue", "RabbitMQ", "Message broker") } System_Boundary(sb3, "Processing") { Container(worker, "Worker Service", "Python", "Processes background jobs") ContainerDb(db2, "Analytics DB", "MongoDB", "Stores analytics") } } System_Ext(email, "Email System", "Sends emails to users") System_Ext(payment, "Payment Gateway", "Processes payments") Rel(user, web, "Uses", "HTTPS") Rel(user, mobile, "Uses", "HTTPS") BiRel(web, api, "API calls", "REST/HTTPS") BiRel(mobile, api, "API calls", "REST/HTTPS") Rel(api, auth, "Authenticates", "gRPC") Rel(api, db1, "Reads/Writes", "SQL") Rel(api, queue, "Publishes", "AMQP") Rel(worker, queue, "Subscribes", "AMQP") Rel(worker, db2, "Stores results", "MongoDB Protocol") Rel(api, email, "Sends emails", "SMTP") Rel(api, payment, "Processes", "HTTPS")

17. Complex Flowchart with Subgraphs

The code:

flowchart TB
    subgraph one
        a1-->a2
        subgraph two
            b1-->b2
        end
        subgraph three
            c1-->c2
        end
        two --> three
        a2 --> two
    end
    
    subgraph main
        m1-->m2
        m2-->m3
    end
    
    one --> main
    
    style one fill:#f9f,stroke:#333,stroke-width:2px
    style main fill:#bbf,stroke:#333,stroke-width:2px
    style two fill:#bfb,stroke:#333,stroke-width:2px
    style three fill:#fbb,stroke:#333,stroke-width:2px

Renders as:

flowchart TB subgraph one a1-->a2 subgraph two b1-->b2 end subgraph three c1-->c2 end two --> three a2 --> two end subgraph main m1-->m2 m2-->m3 end one --> main style one fill:#f9f,stroke:#333,stroke-width:2px style main fill:#bbf,stroke:#333,stroke-width:2px style two fill:#bfb,stroke:#333,stroke-width:2px style three fill:#fbb,stroke:#333,stroke-width:2px

18. Complex Sequence Diagram with Loops and Alt

The code:

sequenceDiagram
    participant Client
    participant Server
    participant Database

    Client->>+Server: Login Request
    
    rect rgb(200, 220, 240)
        Server->>Server: Validate Input
    end
    
    alt valid credentials
        Server->>+Database: Query User
        Database-->>-Server: Return User Data
        
        loop Token Generation
            Server->>Server: Generate Session
            Server->>Server: Create JWT
        end
        
        Server-->>-Client: Login Success + Token
    else invalid credentials
        Server-->>Client: Login Failed
    end

    Note over Client,Server: Subsequent requests will include token

Renders as:

sequenceDiagram participant Client participant Server participant Database Client->>+Server: Login Request rect rgb(200, 220, 240) Server->>Server: Validate Input end alt valid credentials Server->>+Database: Query User Database-->>-Server: Return User Data loop Token Generation Server->>Server: Generate Session Server->>Server: Create JWT end Server-->>-Client: Login Success + Token else invalid credentials Server-->>Client: Login Failed end Note over Client,Server: Subsequent requests will include token

19. State Diagram with Composite States

The code:

stateDiagram-v2
    [*] --> PowerOff
    PowerOff --> Starting : Power On
    Starting --> Running : System Ready
    
    state Running {
        [*] --> Idle
        Idle --> Processing : New Task
        Processing --> Idle : Task Complete
        Processing --> Error : Task Failed
        Error --> Idle : Retry
    }
    
    Running --> PowerOff : Power Off
    Running --> Starting : Restart
    
    note right of Running : System can handle\nmultiple states

Renders as:

stateDiagram-v2 [*] --> PowerOff PowerOff --> Starting : Power On Starting --> Running : System Ready state Running { [*] --> Idle Idle --> Processing : New Task Processing --> Idle : Task Complete Processing --> Error : Task Failed Error --> Idle : Retry } Running --> PowerOff : Power Off Running --> Starting : Restart note right of Running : System can handle\nmultiple states

These examples demonstrate the versatility of Mermaid.js for creating various types of diagrams. The syntax is clear and maintainable, making it a great choice for documentation in code repositories, technical blogs, and project wikis. For the complete and up-to-date syntax reference, check out the official Mermaid.js documentation.