Skip to main content

Mermaid

7 min readStableIntermediate

Write a diagram as text in a Markdown code fence. components/Mermaid.tsx renders it to SVG in the browser, then runs that SVG through DOMPurify before it reaches the page.

Quick Start

A mermaid fence is all you need — three lines of text become a flowchart.

quick.mdx
MDX
```mermaid
flowchart LR
    A[Write MDX] --> B[Build]
    B --> C[Deploy]
```

Adding Options

TD turns the layout top-down, curly braces make a decision node, and a pipe after an arrow labels the edge. The bracket style around a label picks the node shape: [/text/] is a parallelogram, [(text)] a cylinder, ([text]) a stadium, and ((text)) a circle. A YAML block at the top of the fence gives the whole diagram a title.

options.mdx
MDX
```mermaid
---
title: Docs publishing pipeline
---
flowchart TD
    A[/Write MDX/] --> B{Lint clean?}
    B -->|No| C[Fix errors]
    C --> A
    B -->|Yes| D[(Build)]
    D --> E([Deploy])
    E --> F((Live))
```

Advanced

Drop the language tag and the diagram still renders. A fence with no language is checked against 16 keywords, and this one matches because its first line starts with graph, the older alias for flowchart.

auto-detect.mdx
MDX
```
graph TD
    Q[Cmd+K] --> R[(search index)]
    R --> S{Match?}
    S -->|Yes| T[Open page]
    S -->|No| U[Fuzzy suggestions]
```

Bigger diagrams get more structure. subgraph boxes a related group, %% starts a comment the renderer ignores, -.-> draws a dotted edge and ==> a thick one, and a classDef plus class pair colors specific nodes.

advanced.mdx
MDX
```mermaid
flowchart TB
    %% Group the two halves of the pipeline
    subgraph Authoring
        A[MDX page] --> B[(snippets/)]
    end
    subgraph Pipeline
        C[remark] -.-> D[rehype]
        D ==> E([Static HTML])
    end
    B --> C
    classDef source fill:#dcfce7,stroke:#16a34a
    classDef output fill:#fef3c7,stroke:#eab308
    class A,B source
    class E output
```

Bad syntax never breaks the page. The diagram box prints Failed to render diagram and the rest of the article renders normally.

Three details are worth knowing before you go deep. mermaid.initialize runs once per page load with theme: 'default' and a fixed palette, so every diagram on the site shares one look and per-node classDef rules are the way to override it. The security level is strict, which escapes HTML in labels and turns off click interactions. Every rendered SVG then passes through DOMPurify with the SVG and SVG-filter profiles, plus foreignObject on the allow list for wrapped labels. A diagram wider than the article scrolls sideways inside its own bordered box.

Diagram types

Every example below is copyable as written. All of them except the XY chart start with one of the 16 auto-detected keywords, so the mermaid tag on the fence is optional for them.

Sequence diagram

Request flows between participants, with autonumber for step numbers, loop and alt blocks for control flow, and Note over for an aside.

sequence.mdx
MDX
```mermaid
sequenceDiagram
    autonumber
    participant C as Client
    participant S as Server
    participant D as Database
    C->>S: POST /api/auth/verify
    S->>D: Validate credentials
    D-->>S: User found
    S-->>C: 200 OK + JWT cookie
    Note over C,S: Cookie is HttpOnly and Secure
```

Class diagram

Type hierarchies and object models, with + for public members and <|-- for inheritance.

class.mdx
MDX
```mermaid
classDiagram
    class Page {
        +String title
        +String description
        +render() ReactNode
    }
    class FeaturePage {
        +String[] tiers
    }
    Page <|-- FeaturePage
```

State diagram

Lifecycles and state machines. [*] marks the start and end, and text after a colon labels the transition.

state.mdx
MDX
```mermaid
stateDiagram-v2
    [*] --> Draft
    Draft --> Review: submit
    Review --> Published: approve
    Review --> Draft: request changes
    Published --> Archived
    Archived --> [*]
```

Entity relationship diagram

Database schemas. The crow's-foot notation on each side spells out the cardinality.

er.mdx
MDX
```mermaid
erDiagram
    USER ||--o{ POST : creates
    POST ||--o{ COMMENT : has
    USER ||--o{ COMMENT : writes
```

Gantt chart

Schedules with sections, durations, dependencies through after, and zero-length milestone markers.

gantt.mdx
MDX
```mermaid
gantt
    title Docs Rollout
    dateFormat YYYY-MM-DD
    section Content
    Draft pages    :a1, 2026-01-05, 20d
    Review         :a2, after a1, 10d
    section Launch
    Staging deploy :a3, after a2, 5d
    Public launch  :milestone, after a3, 0d
```

Pie chart

Proportions from label and value pairs.

pie.mdx
MDX
```mermaid
pie title Time spent per docs task
    "Writing" : 55
    "Reviewing" : 25
    "Diagrams" : 12
    "Formatting" : 8
```

Git graph

Branching and merge history, with an optional id label on each commit.

git-graph.mdx
MDX
```mermaid
gitGraph
    commit id: "init"
    branch sazzad/feature-pages
    checkout sazzad/feature-pages
    commit id: "add math page"
    commit id: "add mermaid page"
    checkout main
    merge sazzad/feature-pages
    commit id: "release"
```

User journey

Steps through a task with a 1-to-5 satisfaction score and the actor after each colon.

journey.mdx
MDX
```mermaid
journey
    title Reader finds an answer
    section Arrive
      Open the docs home: 5: Reader
      Scan the sidebar: 3: Reader
    section Search
      Press Cmd+K: 5: Reader
      Read the page: 4: Reader
```

Mindmap

Hierarchies driven purely by indentation. Double parentheses around the root draw it as a circle.

mindmap.mdx
MDX
```mermaid
mindmap
  root((OwnDocs))
    Content
      MDX pages
      Snippets
      Variables
    Diagrams
      Mermaid
      Math
    Delivery
      Search
      MCP server
```

Timeline

Chronological milestones. A bare colon on its own line adds a second event to the same period.

timeline.mdx
MDX
```mermaid
timeline
    title Documentation milestones
    2024 : First MDX pages
    2025 : Search and snippets
         : OpenAPI embeds
    2026 : AI chat and MCP server
```

Quadrant chart

Two-axis prioritization. Each point takes an x and y pair between 0 and 1.

quadrant.mdx
MDX
```mermaid
quadrantChart
    title Docs work by effort and value
    x-axis Low Effort --> High Effort
    y-axis Low Value --> High Value
    quadrant-1 Do next
    quadrant-2 Plan it
    quadrant-3 Drop it
    quadrant-4 Quick wins
    Fix typos: [0.15, 0.35]
    Add diagrams: [0.55, 0.8]
    Rewrite API reference: [0.85, 0.9]
    Reorder sidebar: [0.25, 0.6]
```

Sankey diagram

Flow volumes between stages, written as comma-separated source, target, and value rows.

sankey.mdx
MDX
```mermaid
sankey-beta
 
Search,Getting Started,40
Search,Features,35
Sidebar,Features,25
Sidebar,Reference,20
Features,Mermaid,18
```

Requirement diagram

Requirements, the elements that implement them, and the relationship between the two.

requirement.mdx
MDX
```mermaid
requirementDiagram
    requirement sanitize_svg {
        id: 1
        text: Diagram SVG must be sanitized before insertion.
        risk: high
        verifymethod: test
    }
    element mermaid_component {
        type: component
    }
    mermaid_component - satisfies -> sanitize_svg
```

C4 context diagram

System context in C4 notation, with people, systems, external systems, and the relationships between them.

c4.mdx
MDX
```mermaid
C4Context
    title Docs site context
    Person(reader, "Reader", "Looks up product docs")
    System(docs, "OwnDocs site", "Next.js MDX documentation")
    System_Ext(agent, "AI agent", "Queries the MCP endpoint")
    Rel(reader, docs, "Reads")
    Rel(agent, docs, "Calls /api/mcp")
```

XY chart

Bars and lines on a shared pair of axes. xychart-beta is not one of the 16 auto-detected keywords, so this fence has to carry the mermaid tag. The same rule covers every other diagram Mermaid ships that the keyword list does not name.

xychart.mdx
MDX
```mermaid
xychart-beta
    title "Page views per month"
    x-axis [Jan, Feb, Mar, Apr]
    y-axis "Views" 0 --> 400
    bar [120, 180, 260, 340]
    line [120, 180, 260, 340]
```

Options

languagestring

The code fence language. Write mermaid, or omit it and let auto-detection infer the diagram from the first line of the code block. A fence tagged with any other language renders as ordinary code.

diagram typestring

The Mermaid diagram kind, taken from the first line of the code block. Auto-detected keywords are erDiagram, graph, flowchart, sequenceDiagram, classDiagram, stateDiagram, gantt, pie, gitGraph, journey, requirementDiagram, C4Context, mindmap, timeline, quadrantChart, and sankey. Matching is case-insensitive and prefix-based, so stateDiagram-v2 and sankey-beta both count.

diagram front matteryaml

An optional --- block at the top of the fence. Use it to set the diagram's title. A fence that opens with this block needs the mermaid tag, because auto-detection reads the first line only.

classDef / class / styledirective

Per-diagram styling. classDef names a fill and stroke, class applies it to a comma-separated node list, and style targets a single node. This is the supported way to color a diagram, since the global theme is set once in components/Mermaid.tsx.

%%comment

A comment line. The renderer ignores everything after it on that line.

Was this page helpful?