Back to blog
|11 min read|Docsio

Mermaid Diagram Syntax: 7 Examples You Can Copy

mermaid-diagramdiagrams-as-codedocumentationdeveloper-tools
Mermaid Diagram Syntax: 7 Examples You Can Copy

A mermaid diagram is a chart you write as text instead of drawing by hand. You type a few lines of Markdown-style code inside a fenced block, and a renderer turns it into a flowchart, sequence diagram, or one of a dozen other visuals. Because the diagram is code, it lives in version control right next to your docs and updates in the same pull request as the feature it describes.

That property is what makes a mermaid diagram fit a docs-as-code workflow so well. A screenshot of a diagram goes stale the moment someone renames a service. A mermaid diagram gets edited in the same commit, reviewed in the same diff, and never drifts from the system it documents. This guide walks through the seven diagram types you will actually use, each with working code you can paste and adapt.

What is a mermaid diagram?

Mermaid is a JavaScript library that reads text definitions and draws diagrams from them. The syntax borrows from Markdown, so it stays readable even before it renders. You write what the diagram means, and the layout engine decides where the boxes and arrows go.

The project started in 2014 after its creator lost a diagram file and had to redraw it by hand. The fix was to describe diagrams in plain text kept under version control, so documentation could keep pace with the code. That origin still shapes how teams use it today.

Every mermaid diagram starts with a keyword that names the type, followed by the definition. Here is the smallest complete example, a two-node flowchart:

flowchart LR
    A[Start] --> B[Done]

That renders as two boxes with an arrow pointing from Start to Done. Change LR to TD and the same diagram flows top-down instead of left-right. Everything else in mermaid builds on this pattern: declare a type, then describe the pieces.

Why write diagrams as code

Drawing tools like Lucidchart and Visio produce a binary file or an exported PNG. Neither reviews well in a pull request, and neither updates when the underlying system changes. You end up with docs that show an architecture two refactors out of date.

Diagrams-as-code fixes the drift. Since a mermaid diagram is plain text, Git tracks every change, teammates review edits line by line, and the diagram sits inside the same Markdown or MDX file as the prose it supports. When the feature changes, you edit two lines of the diagram in the same commit that changes the code.

This is the same reason screenshots become technical debt in documentation. A picture is a snapshot; code is a source of truth. For architecture docs especially, a text definition you can grep and diff beats an image nobody can edit without the original file.

Mermaid diagram syntax basics

Three rules cover most of what you need. First, the type keyword goes on line one. Second, node text in brackets [ ] renders as a rectangle, ( ) as a rounded box, and { } as a diamond. Third, arrows connect nodes: --> is a solid arrow, --- is a plain line, and -.-> is dotted.

Labels on arrows go between pipes, like A -->|yes| B. Comments start with %%. If you have written Markdown before, the Markdown syntax reference will feel familiar, because mermaid deliberately keeps the same lightweight, readable style.

To render a diagram, you have a few options. GitHub, GitLab, Notion, and Obsidian render mermaid fences automatically. The mermaid live editor at mermaid.live gives you instant preview in the browser. And any site running the mermaid js library renders fences on the page. Now the diagram types.

Flowchart

The flowchart is the diagram most people mean when they say "mermaid diagram." It maps decisions and steps, which makes it the go-to for onboarding flows, request handling, and any branching logic.

flowchart TD
    A[User submits form] --> B{Valid input?}
    B -->|Yes| C[Save to database]
    B -->|No| D[Show error message]
    C --> E[Send confirmation email]
    D --> A

This renders a top-down flowchart: a form submission hits a validation diamond, branches to either a save step or an error, and loops back on failure. The { } around "Valid input?" draws the diamond that signals a decision. Swap TD for LR to run it horizontally when the chart gets tall.

Flowcharts also cover process and data flow diagrams once you add subgraphs to group related nodes. Wrap a set of nodes in a subgraph Name ... end block and mermaid draws a labeled container around them.

Sequence diagram

A sequence diagram shows how parts of a system talk to each other over time. It is the clearest way to document an API handshake, an auth flow, or a message passing between services.

sequenceDiagram
    participant U as User
    participant A as API
    participant D as Database
    U->>A: POST /login
    A->>D: Query user record
    D-->>A: Return user
    A-->>U: 200 OK + token

Each participant becomes a vertical lifeline, and each arrow is a message in order from top to bottom. Solid arrows ->> are calls; dashed arrows -->> are responses. Add Note over A,D: text to annotate a step, or wrap messages in loop and alt blocks to show retries and conditional paths.

Class diagram

Class diagrams document object structure: the fields, methods, and relationships in your codebase. They pair well with a software architecture document where readers need to see how types connect.

classDiagram
    class User {
        +String name
        +String email
        +login()
        +logout()
    }
    class Order {
        +int id
        +Date created
        +total()
    }
    User "1" --> "*" Order : places

The + marks public members, and - marks private ones. The relationship line reads "one User places many Orders," with the "1" and "*" setting the cardinality. Mermaid supports inheritance (<|--), composition (*--), and aggregation (o--) using different arrowheads, so you can express real UML relationships without a UML tool.

Entity relationship diagram

An ER diagram models your database schema: tables, columns, and how records relate. It is the fastest way to give a new engineer a map of the data before they open the migration files.

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    PRODUCT ||--o{ LINE_ITEM : "ordered in"
    CUSTOMER {
        int id
        string name
        string email
    }
    ORDER {
        int id
        date created_at
    }

The crow's-foot notation carries the meaning. ||--o{ reads as "one customer to zero-or-many orders," while ||--|{ means "one to one-or-many." The attribute blocks in braces list columns with their types. This renders a clean schema map that updates the moment you edit a line, unlike a screenshot pulled from a database GUI.

State diagram

A state diagram tracks the lifecycle of an object as it moves between states. Use it for anything with a status field: a subscription, a support ticket, a deployment, or a content draft.

stateDiagram-v2
    [*] --> Draft
    Draft --> Review: submit
    Review --> Draft: request changes
    Review --> Published: approve
    Published --> [*]

The [*] marks the start and end points, and each arrow shows a transition with the event that triggers it. This example maps a publishing workflow from draft to published, with a loop back when a reviewer asks for changes. The stateDiagram-v2 keyword uses mermaid's newer, cleaner renderer, so prefer it over the older stateDiagram.

Gantt chart

A gantt chart plots tasks against a timeline. It works for roadmaps, sprint plans, and any schedule where you need to show what happens when and what depends on what.

gantt
    title Documentation Sprint
    dateFormat YYYY-MM-DD
    section Writing
    Draft API docs      :a1, 2026-07-01, 5d
    Review pass         :after a1, 3d
    section Publishing
    Build and deploy    :2026-07-10, 2d

Each line is a task with a start date and a duration like 5d. The after a1 syntax chains a task to start when another finishes, so dependencies stay accurate when you shift a date. Sections group related tasks into swimlanes. It is not a full project planner, but for a diagram that lives in your docs, it beats maintaining a separate spreadsheet.

Pie chart

The pie chart handles simple proportions. It is the one mermaid diagram meant for data rather than structure, useful for a quick breakdown in a report or a readme.

pie title Support tickets by category
    "Setup" : 45
    "Billing" : 25
    "API" : 20
    "Other" : 10

Each label and number becomes a slice, and mermaid calculates the percentages for you. Keep it to a handful of categories; a pie with twelve slivers is harder to read than a table. For anything beyond a rough split, reach for a real charting library instead.

Where mermaid diagrams render

The reason a mermaid diagram is worth learning is reach. GitHub and GitLab render fences in markdown files and pull request comments. Notion, Obsidian, and Confluence support them. Most static site generators built for docs, including Docusaurus and MkDocs, render mermaid on the page.

That last point matters for anyone publishing a docs site. If your platform renders mermaid natively, your diagrams stay in the docs source and rebuild on every deploy, no image exports to manage. Docsio renders mermaid fences in your published pages the same way, so a diagram you write in a doc shows up live and updates whenever you edit the code. The diagram never falls out of sync because there is no separate file to forget.

For a diagram-heavy page like an architecture overview or a design doc template, this is the difference between docs that stay current and docs that rot. The diagram is part of the text, versioned with everything else, and readable by anyone who opens the file.

Common syntax mistakes

Two errors trip up most beginners. First, special characters in node labels break the parser. If a label contains parentheses, quotes, or a colon, wrap the whole label in double quotes: A["Call save() method"]. Second, indentation matters less than you think, but the type keyword on line one is mandatory. A diagram that renders as raw text almost always has a typo in that first line.

When a diagram fails to render, paste it into the mermaid live editor. It shows the exact line and character where the parse fails, which is faster than guessing. Once it renders there, copy it back into your docs with confidence.

FAQ

What is a mermaid diagram?

A mermaid diagram is a chart generated from text rather than drawn by hand. You write Markdown-inspired code describing the nodes and connections, and the mermaid JavaScript library renders it as a flowchart, sequence diagram, or other visual. Because it is plain text, it lives in version control alongside your documentation.

Why are they called mermaid diagrams?

The tool is named after The Little Mermaid. Its creator, Knut Sveidqvist, built the first version in 2014 after losing a diagram file, and his children were watching the film at the time. The name stuck, and the project has grown into one of the most widely supported diagramming tools for developers.

Is a mermaid diagram good for beginners?

Yes. The syntax is intentionally close to Markdown, so a two-node flowchart takes one line of code. You can build and preview diagrams in the free mermaid live editor with no install. Most people write their first working diagram within a few minutes of seeing an example.

Can ChatGPT generate mermaid diagrams?

Yes. ChatGPT and other AI models produce valid mermaid syntax from a plain-language description, which gives you a fast starting point. The output is not always perfect, so paste it into the live editor to catch parse errors, then adjust the labels and connections to match your actual system.

How do you generate a mermaid diagram for free?

The mermaid live editor at mermaid.live renders diagrams in your browser with no signup. You can also write fences directly in GitHub, GitLab, Notion, or Obsidian, all of which render mermaid for free. For published docs, platforms like Docsio render your diagrams live from the source with no export step.

Start writing diagrams that stay current

Pick one diagram from your existing docs that is currently a screenshot, and rewrite it as a mermaid diagram this week. You get a version-controlled source you can diff, and a visual that updates in the same pull request as the code. Once it clicks, the drawing tool starts to feel like the slow path.

If you want those diagrams live on a hosted docs site without managing a build pipeline, Docsio generates a published docs site from your product URL and renders mermaid fences out of the box, no build setup required.

Ready to ship your docs?

Generate a complete documentation site from your URL in under 5 minutes.

Get Started Free