STARMORPH_BLOG
Published on
23 min read

Mermaid.js Tutorial: The Complete Guide to Diagrams as Code (2026)

Authors

TL;DR: Mermaid.js lets you create diagrams by writing simple text-based syntax instead of dragging shapes around in a GUI. It is the standard for diagrams as code, with native support in GitHub, GitLab, Notion, and Obsidian. This guide covers every diagram type, theming, AI generation, and export workflows.

Table of Contents

What is Mermaid.js?

Mermaid.js is a JavaScript library that turns text definitions into diagrams. Instead of dragging boxes and drawing arrows in tools like Lucidchart or draw.io, you write a few lines of code and the diagram renders automatically. This approach is called diagrams as code, and it changes how developers document systems.

The project has over 82,000 stars on GitHub, making it one of the most popular developer tools in the ecosystem. More importantly, Mermaid is natively supported in the places developers already work:

  • GitHub renders Mermaid blocks in Markdown files, issues, and pull requests
  • GitLab supports Mermaid in wikis, issues, and merge requests
  • Notion has built-in Mermaid code block rendering
  • Obsidian renders Mermaid diagrams inline in notes

Why does this matter? Three reasons:

  1. Version control. Your diagrams live in the same repo as your code. When the architecture changes, git diff shows you exactly what changed in the diagram.
  2. Speed. Writing A --> B --> C is faster than clicking, dragging, aligning, and connecting shapes manually.
  3. Reproducibility. Anyone on your team can edit the text and regenerate the diagram. No proprietary file formats, no "who has the Figma login" conversations.

If you have ever spent 30 minutes fighting with alignment in a drag-and-drop tool, Mermaid is the fix.

Getting Started

You do not need to install anything to start using Mermaid. The fastest way to write your first diagram is to open an online editor.

Where to write Mermaid

Online editors are the easiest starting point:

  • Mermaid Editor — dark theme, AI generation, high-quality PNG/PDF export
  • mermaid.live — the official Mermaid editor, minimal features
  • GitHub — paste Mermaid code in any Markdown file and it renders on push

VS Code users can install the Mermaid Preview extension to render diagrams inline as you type.

Basic syntax structure

Every Mermaid diagram starts with a diagram type declaration followed by the diagram content:

graph TD
    A[Start] --> B[Process]
    B --> C[End]

Breaking this down:

  • graph declares a flowchart
  • TD sets the direction — top to down (other options: LR for left to right, BT for bottom to top, RL for right to left)
  • Each line defines a node and its connections
  • Square brackets [text] create rectangle nodes
  • --> draws an arrow between nodes

Your first diagram

Here is a simple flowchart that models a code review process:

graph LR
    A[Write Code] --> B{Tests Pass?}
    B -- Yes --> C[Open PR]
    B -- No --> D[Fix Tests]
    D --> A
    C --> E[Code Review]
    E --> F{Approved?}
    F -- Yes --> G[Merge]
    F -- No --> A

This produces a left-to-right flowchart with decision diamonds (curly braces {}), labeled edges (-- Yes -->), and a loop back to the start on failure.

Try this in Mermaid Editor — paste the code and watch the diagram render in real time.

That is all you need to get started. The rest of this guide covers every diagram type Mermaid supports, from sequence diagrams to Gantt charts, with copy-paste examples for each.

Flowcharts

Flowcharts are the most common Mermaid diagram type. They model processes, decision trees, system architectures, and any workflow where things move from one step to the next. Mermaid calls them graph or flowchart — both keywords work identically.

Direction

The direction declaration controls which way the diagram flows:

  • graph TD or graph TB — top to bottom (default)
  • graph LR — left to right
  • graph BT — bottom to top
  • graph RL — right to left

Choose LR for horizontal workflows like CI/CD pipelines. Use TD for hierarchical structures like org charts or decision trees.

Node shapes

Mermaid uses bracket syntax to define node shapes. Each shape communicates a different meaning:

graph TD
    A[Rectangle] --> B(Rounded)
    B --> C{Diamond}
    C --> D((Circle))
    D --> E{{Hexagon}}
    E --> F[/Parallelogram/]
    F --> G[\Trapezoid\]

The most important shapes are rectangles for processes, diamonds for decisions, and rounded boxes for start/end points. You do not need to memorize every shape — use diamonds for yes/no branching and rectangles for everything else.

Arrow types

Arrows connect nodes and define the flow direction. Mermaid supports several styles:

  • --> solid arrow
  • -.-> dotted arrow
  • ==> thick arrow
  • -->|label| arrow with a text label
  • -- text --> alternative label syntax

Here is a simple three-node flow with labeled arrows:

graph LR
    A[User Request] -->|HTTP GET| B[API Server]
    B -->|Query| C[(Database)]
    C -.->|Results| B
    B ==>|JSON Response| A

Dotted arrows work well for return paths or optional flows. Thick arrows highlight the primary or critical path.

Decision trees

Diamonds create branching logic. Combine them with labeled edges to model if/else logic:

graph TD
    A[Receive Order] --> B{In Stock?}
    B -->|Yes| C[Process Payment]
    B -->|No| D[Notify Customer]
    C --> E{Payment OK?}
    E -->|Yes| F[Ship Order]
    E -->|No| G[Retry Payment]
    G --> E
    D --> H[Offer Alternatives]

Each diamond represents a question, and each outgoing edge is a possible answer. This pattern maps directly to conditional logic in code.

Subgraphs

Subgraphs group related nodes into labeled containers. They are essential for modeling complex systems with distinct phases or services:

graph LR
    subgraph CI[Continuous Integration]
        A[Push Code] --> B[Run Tests]
        B --> C[Build Image]
    end

    subgraph CD[Continuous Deployment]
        D[Push to Registry] --> E[Deploy Staging]
        E --> F{Smoke Tests Pass?}
        F -->|Yes| G[Deploy Production]
        F -->|No| H[Rollback]
    end

    C --> D

Subgraphs can be nested, and you can draw arrows between nodes in different subgraphs. This makes them ideal for microservice architectures where you want to show service boundaries.

Try building your own flowchart in Mermaid Editor — paste any example above and modify it to match your use case.

Sequence Diagrams

Sequence diagrams show how components communicate over time. They are the standard way to document API flows, authentication handshakes, and microservice interactions. The vertical axis represents time flowing downward, and each participant gets a lifeline.

Participants and actors

Define participants at the top to control their order. Use actor for human stick figures and participant for system boxes:

sequenceDiagram
    actor User
    participant Client
    participant Server
    participant DB as Database

The as keyword creates an alias — DB as Database displays "Database" but lets you type DB in the rest of the diagram.

Message types

Messages flow between participants using different arrow styles:

  • -> solid line (synchronous)
  • --> dotted line (return/response)
  • ->> solid with arrowhead (async request)
  • -->> dotted with arrowhead (async response)
  • -x solid with cross (lost message)

Activation bars

Activation bars show when a participant is actively processing. Use activate/deactivate or the +/- shorthand:

sequenceDiagram
    Client->>+Server: POST /login
    Server->>+DB: SELECT user
    DB-->>-Server: user record
    Server-->>-Client: 200 OK + JWT

The + after >> activates the target, and - before >> deactivates the source. This visually shows which components are busy at any point in time.

Control flow

Mermaid supports loops, conditionals, optional blocks, and parallel execution:

sequenceDiagram
    actor User
    participant App
    participant Auth
    participant API

    User->>App: Click Login
    App->>Auth: POST /auth/token
    Auth-->>App: JWT Token

    alt Token Valid
        App->>API: GET /data (Bearer token)
        API-->>App: 200 OK
        App-->>User: Show Dashboard
    else Token Expired
        App->>Auth: POST /auth/refresh
        Auth-->>App: New JWT
        App->>API: GET /data (new token)
        API-->>App: 200 OK
        App-->>User: Show Dashboard
    end

    loop Every 5 minutes
        App->>API: GET /heartbeat
        API-->>App: 200 OK
    end

Use alt/else for branching paths, opt for optional interactions, loop for repeated exchanges, and par for parallel flows. You can nest these blocks inside each other.

Notes

Add context with notes attached to participants:

sequenceDiagram
    participant A as Service A
    participant B as Service B
    Note right of A: Retry up to 3 times
    A->>B: Request
    Note over A,B: TLS encrypted
    B-->>A: Response

Notes can appear to the right of, left of, or over one or two participants.

Build your own sequence diagram in Mermaid Editor — great for documenting API flows before writing code.

Class Diagrams

Class diagrams model the structure of object-oriented systems. They show classes, their attributes and methods, and the relationships between them. Mermaid uses UML-standard notation, so if you have seen class diagrams in textbooks, the syntax will feel familiar.

Class syntax

Define classes with their attributes and methods. Use visibility markers to indicate access levels:

  • + public
  • - private
  • # protected
  • ~ package/internal
classDiagram
    class User {
        +String email
        +String name
        -String passwordHash
        +login(password) bool
        +updateProfile(data) void
        -hashPassword(raw) String
    }

Methods include their parameters and return types. This maps directly to TypeScript interfaces or Java class definitions.

Relationships

Mermaid supports all standard UML relationship types:

  • <|-- inheritance (extends)
  • *-- composition (owns, lifecycle-dependent)
  • o-- aggregation (has, independent lifecycle)
  • --> association (uses)
  • ..> dependency (depends on)
  • ..|> implementation (implements interface)

Annotations

Mark classes as interfaces or abstract with annotations:

classDiagram
    class PaymentProcessor {
        <<interface>>
        +processPayment(amount) bool
        +refund(transactionId) bool
    }

    class StripeProcessor {
        +processPayment(amount) bool
        +refund(transactionId) bool
        -apiKey: String
    }

    class PayPalProcessor {
        +processPayment(amount) bool
        +refund(transactionId) bool
        -clientId: String
    }

    PaymentProcessor <|.. StripeProcessor
    PaymentProcessor <|.. PayPalProcessor

Full example: e-commerce domain model

Here is a complete class diagram for a typical e-commerce system:

classDiagram
    class User {
        +String id
        +String email
        +String name
        +getOrders() Order[]
    }

    class Order {
        +String id
        +Date createdAt
        +String status
        +getTotal() number
        +cancel() void
    }

    class OrderItem {
        +int quantity
        +number price
        +getSubtotal() number
    }

    class Product {
        +String id
        +String name
        +number price
        +int stock
        +isAvailable() bool
    }

    class Cart {
        +addItem(product, qty) void
        +removeItem(productId) void
        +checkout() Order
    }

    User "1" --> "*" Order : places
    User "1" --> "1" Cart : has
    Order "1" *-- "*" OrderItem : contains
    OrderItem "*" --> "1" Product : references
    Cart "1" o-- "*" Product : holds

The cardinality labels ("1", "*") show how many instances participate in each relationship. *-- for composition means OrderItems cannot exist without their parent Order. o-- for aggregation means the Cart references Products but does not own them.

Paste this into Mermaid Editor to see it render — then modify it to match your own domain model.

Entity-Relationship Diagrams

ER diagrams model database schemas. They show tables (entities), their columns (attributes), and the relationships between tables. If you are designing a database or documenting an existing one, this is the diagram type you want.

Entity syntax

Define entities with their attributes. Each attribute has a type and a name:

erDiagram
    USER {
        int id PK
        string email
        string name
        datetime created_at
    }

PK marks the primary key. You can also use FK for foreign keys and UK for unique constraints.

Relationship cardinality

Relationships use a compact notation for cardinality:

  • ||--|| one to one
  • ||--o{ one to zero-or-many
  • ||--|{ one to one-or-many
  • }o--o{ zero-or-many to zero-or-many

The symbols break down as: | means exactly one, o means zero, { means many. Read them from left to right.

Relationship labels

Add a label between the entities to describe the relationship:

erDiagram
    USER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains

Full example: blog platform schema

Here is a complete ER diagram for a blog platform with users, posts, comments, and tags:

erDiagram
    USER {
        int id PK
        string email UK
        string username UK
        string password_hash
        datetime created_at
    }

    POST {
        int id PK
        int author_id FK
        string title
        text content
        string slug UK
        boolean published
        datetime published_at
        datetime created_at
    }

    COMMENT {
        int id PK
        int post_id FK
        int author_id FK
        text body
        datetime created_at
    }

    TAG {
        int id PK
        string name UK
        string slug 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 : ""

The junction table POST_TAG implements the many-to-many relationship between posts and tags. This is exactly how you would model it in SQL — Mermaid ER diagrams map one-to-one with real database schemas.

Design your database schema visually in Mermaid Editor — export the diagram for your project docs.

Gantt Charts

Gantt charts visualize project timelines. They show tasks, durations, dependencies, and milestones on a horizontal timeline. Use them for sprint planning, product launch timelines, or any project where you need to communicate what happens when.

Basic structure

A Gantt chart starts with the gantt declaration, followed by metadata and task definitions:

gantt
    title Project Timeline
    dateFormat YYYY-MM-DD

    section Planning
    Requirements gathering  :a1, 2026-04-01, 7d
    Technical spec          :a2, after a1, 5d
    Design mockups          :a3, after a1, 5d

Tasks belong to sections and can have IDs (a1, a2) for referencing in dependencies. The after keyword creates task dependencies — after a1 means "start when a1 finishes."

Task status

Mark tasks with status indicators:

  • done — completed tasks (filled solid)
  • active — currently in progress (highlighted)
  • crit — critical path (red)

Milestones

Create zero-duration milestones to mark key dates:

gantt
    title Product Launch
    dateFormat YYYY-MM-DD

    section Development
    Core features           :done, dev1, 2026-04-01, 21d
    API integration         :active, dev2, after dev1, 14d
    Performance tuning      :dev3, after dev2, 7d

    section Testing
    Unit tests              :test1, after dev1, 14d
    Integration tests       :test2, after dev2, 7d
    UAT                     :crit, test3, after dev3, 5d

    section Launch
    Beta release            :milestone, m1, after test2, 0d
    Marketing prep          :launch1, after m1, 10d
    Production deploy       :crit, launch2, after test3, 2d
    Public launch           :milestone, m2, after launch2, 0d

This example shows a realistic product launch timeline with parallel workstreams, critical path highlighting, and milestone markers. The critical tasks (crit) in red make it immediately clear which tasks cannot slip without delaying the launch.

Map out your project timeline in Mermaid Editor — share the diagram with your team for alignment.

Mind Maps

Mind maps are for brainstorming and hierarchical idea organization. Mermaid renders them as radial trees expanding outward from a central topic. The syntax is indentation-based — no arrows or brackets needed.

Basic syntax

Indentation defines the hierarchy. Each level of indentation creates a child node:

mindmap
    root((Feature Plan))
        UX
            User research
            Wireframes
            Prototype
            Usability testing
        Backend
            API design
            Database schema
            Authentication
            Rate limiting
        Testing
            Unit tests
            Integration tests
            Load testing
        Launch
            Documentation
            Marketing page
            Changelog

The root node uses ((double parentheses)) for a circle shape. Child nodes are plain text by default. You can use the same shape syntax as flowcharts — [rectangle], (rounded), {{hexagon}} — on any node.

Mind maps work best for high-level planning and brainstorming. For anything that needs arrows or flow direction, use a flowchart instead.

Brainstorm your next feature in Mermaid Editor — mind maps render instantly as you type.

More Diagram Types

Mermaid supports over 20 diagram types. Here is a quick reference for the ones not covered in depth above. Each example is a minimal starting point you can expand.

State diagrams

Model state machines with transitions:

stateDiagram-v2
    [*] --> Draft
    Draft --> Review : Submit
    Review --> Published : Approve
    Review --> Draft : Request Changes
    Published --> Archived : Archive
    Archived --> [*]

[*] represents the start and end states. Arrows are labeled with the event that triggers the transition.

Git graphs

Visualize branching and merge strategies:

gitGraph
    commit
    commit
    branch feature
    checkout feature
    commit
    commit
    checkout main
    merge feature
    commit

Git graphs are great for documenting your team's branching strategy in a README or wiki.

Pie charts

Show proportional data:

pie title Traffic Sources
    "Organic Search" : 45
    "Direct" : 25
    "Social Media" : 20
    "Referral" : 10

Timeline

Document chronological events:

timeline
    title Company Milestones
    2024 : Founded
         : Seed funding
    2025 : Product launch
         : 1000 users
    2026 : Series A
         : Enterprise tier

Architecture diagrams

Model cloud infrastructure (beta):

architecture-beta
    group cloud(cloud)[AWS]

    service api(server)[API] in cloud
    service db(database)[RDS] in cloud
    service cache(database)[Redis] in cloud

    api:R --> L:db
    api:B --> T:cache

Sankey diagrams

Show flow quantities between nodes (beta):

sankey-beta

Organic,Signups,400
Paid Ads,Signups,200
Referral,Signups,100
Signups,Free Plan,500
Signups,Pro Plan,150
Signups,Enterprise,50

These diagram types cover increasingly specialized use cases. For full syntax documentation on any of them, check the official Mermaid docs. For a fast way to experiment with any diagram type, use Mermaid Editor.

Theming and Dark Mode

Mermaid ships with four built-in themes that change the entire look of your diagram:

  • default — light background, blue and purple nodes
  • dark — dark background, muted tones (ideal for dark mode UIs)
  • forest — green palette, nature-inspired
  • neutral — grayscale, clean for documentation

Applying a theme

Add a theme directive at the top of any diagram to override the default:

%%{init: {'theme': 'dark'}}%%
graph LR
    A[Request] --> B[Auth Middleware]
    B --> C{Authorized?}
    C -->|Yes| D[Handler]
    C -->|No| E[401 Forbidden]

The %%{init: ...}%% directive must be the first line. Everything inside is a JSON configuration object.

Custom theme variables

For full control over colors, use the base theme with custom variables:

%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#1e40af',
    'primaryTextColor': '#ffffff',
    'primaryBorderColor': '#1e3a8a',
    'lineColor': '#64748b',
    'secondaryColor': '#f1f5f9',
    'tertiaryColor': '#e2e8f0',
    'fontFamily': 'Inter, sans-serif',
    'fontSize': '14px'
  }
}}%%
graph TD
    A[User Signup] --> B[Send Welcome Email]
    B --> C[Onboarding Flow]
    C --> D[Activate Account]

Key variables you can customize:

  • primaryColor — main node background
  • primaryTextColor — text inside primary nodes
  • primaryBorderColor — border around primary nodes
  • lineColor — arrows and connection lines
  • secondaryColor — secondary node backgrounds
  • tertiaryColor — tertiary elements and subgraph backgrounds
  • fontFamily — any web-safe font or system font
  • fontSize — base font size for all text

This lets you match diagrams to your brand or documentation theme. If tweaking JSON variables feels tedious, Mermaid Editor offers 10+ theme presets you can apply with one click and customize from there.

Using AI to Generate Mermaid Diagrams

AI tools like ChatGPT, Claude, and Gemini can generate Mermaid diagrams from plain English descriptions. This is the fastest way to create a first draft — describe what you want, get working code, then refine it.

The workflow

  1. Describe the diagram you need in natural language
  2. AI generates the Mermaid code
  3. Paste the code into a Mermaid editor
  4. Review the output and fix any issues
  5. Refine the diagram — adjust labels, add nodes, change layout direction
  6. Export as PNG, SVG, or PDF

Prompt examples that work well

Here are three prompts that consistently produce good results:

Flowchart prompt:

Create a Mermaid flowchart showing a user authentication flow. Include email/password login and OAuth login as two separate paths. Both paths should converge at a "Create Session" step. Add error handling for invalid credentials and OAuth failures.

ER diagram prompt:

Generate a Mermaid ER diagram for a blog platform with users, posts, comments, and tags. Users can write many posts and comments. Posts can have many tags through a junction table. Include primary keys, foreign keys, and common column types.

Sequence diagram prompt:

Create a Mermaid sequence diagram showing how a REST API handles a payment. Include the client, API gateway, payment service, Stripe API, and database. Show the happy path and a failure path when Stripe returns an error. Use activation bars.

Common AI syntax errors

AI models get Mermaid syntax right most of the time, but they occasionally produce errors. Here are the most common ones and how to fix them:

Wrong arrow syntax. AI sometimes generates -> in sequence diagrams when it should be ->>. If your sequence diagram shows "Parse error," check that request arrows use ->> and responses use -->>.

Missing semicolons in class diagrams. Some AI models add semicolons after class attributes. Mermaid does not use semicolons — remove them.

Unsupported features. AI may generate syntax from older or newer Mermaid versions that your editor does not support. If you see a parse error on a specific line, check whether the feature exists in the current Mermaid version.

Incorrect node IDs. AI sometimes reuses node IDs or uses spaces in IDs. Node IDs must be unique and cannot contain spaces — use camelCase or underscores.

Unbalanced brackets. AI occasionally forgets a closing bracket on node definitions. If only part of your diagram renders, count the opening and closing brackets on the broken line.

The fastest way to debug: paste the code into an editor and read the error message. Mermaid Editor highlights syntax errors automatically and shows which line caused the problem, so you can fix AI-generated code in seconds.

Exporting Mermaid Diagrams

You have written a diagram and it looks right. Now you need it as an image file for a presentation, documentation site, or client deliverable.

Free export options

Online editors. Paste your code into mermaid.live and download a PNG or SVG. The export is standard resolution (1x DPI) with the mermaid.live branding.

Mermaid CLI. The official command-line tool converts .mmd files to images:

npx @mermaid-js/mermaid-cli -i diagram.mmd -o output.png

You can also export to SVG or PDF:

npx @mermaid-js/mermaid-cli -i diagram.mmd -o output.svg
npx @mermaid-js/mermaid-cli -i diagram.mmd -o output.pdf

The CLI uses Puppeteer under the hood, so it needs a Chromium install. It works well in CI/CD pipelines for generating diagrams from Markdown files during builds.

When standard resolution is not enough

1x DPI exports look fine on screen at small sizes, but they become blurry when:

  • Projected on a screen during a presentation
  • Embedded in PDF documentation that gets printed
  • Used in client-facing deliverables where quality matters
  • Displayed on high-DPI retina screens at large sizes

If you need presentation-quality output, Mermaid Editor Pro offers 4x DPI resolution PNG export, no watermark, and direct PDF export. The difference is visible — text stays sharp and lines stay crisp at any zoom level.

Which export method to use

  • Quick screenshot for Slack or a PR comment — mermaid.live PNG is fine
  • Documentation site — SVG export (scales to any size, small file)
  • Presentations and print — 4x DPI PNG or PDF
  • CI/CD pipeline — mermaid-cli for automated generation

Adding Mermaid to GitHub README

GitHub has supported Mermaid natively in Markdown since February 2022. You do not need any plugins, extensions, or build steps. Wrap your Mermaid code in a fenced code block with the mermaid language identifier, push to GitHub, and it renders automatically.

Syntax

In any .md file on GitHub, use this format:

```mermaid
graph LR
    A[Client] --> B[API Gateway]
    B --> C[Auth Service]
    B --> D[User Service]
    B --> E[Payment Service]
```

This works in:

  • README.md files
  • Wiki pages
  • Issue descriptions and comments
  • Pull request descriptions and comments
  • Any Markdown file in the repository

Limitations

GitHub's Mermaid rendering has some constraints:

  • No custom theming. You cannot use %%{init: ...}%% theme directives — GitHub strips them. All diagrams render with GitHub's default theme.
  • Limited diagram types. Not all Mermaid diagram types are supported. Newer features like architecture diagrams and Sankey diagrams may not render.
  • Rendering speed. Complex diagrams with many nodes can be slow to render on page load.
  • No interactive features. Diagrams are rendered as static SVGs — no click handlers, tooltips, or zoom.
  • Mobile rendering. Large diagrams can overflow on mobile screens without horizontal scrolling.

Workaround for full control

If you need custom themes, high-resolution output, or diagram types that GitHub does not support, export the diagram as an image and embed it instead:

![Architecture Diagram](./docs/architecture.png)

The workflow: edit your diagram in Mermaid Editor, export as PNG or SVG, commit the image to your repo, and reference it in Markdown. You lose the text-based editability in the README, but you gain full control over appearance and compatibility.

Best practice

Use native Mermaid code blocks for simple diagrams that do not need theming — flowcharts, sequence diagrams, and ER diagrams work well. For complex diagrams or anything presentation-facing, export as an image.

Best Mermaid Editors Compared

There are four main ways to edit Mermaid diagrams. Here is how they compare:

Featuremermaid.livemermaideditor.ioVS Code Extensionmermaid-cli
PriceFreeFree / ProFreeFree
ThemingBasic10+ presetsN/AConfig file
AI GenerationNoYesNoNo
Export PNGYes (1x)Yes (4x Pro)NoYes
Export PDFNoYes (Pro)NoYes
Dark Mode EditorNoYesN/AN/A
OfflineNoNoYesYes

mermaid.live

The official Mermaid editor. It is free, fast, and supports all diagram types. The interface is minimal — a code panel on the left, a preview on the right. Export is limited to standard-resolution PNG and SVG. No theming presets, no AI features, no dark mode in the editor itself. For quick edits and sharing diagram links, it works well.

mermaideditor.io

A more full-featured editor with dark mode, 10+ built-in theme presets, and AI-powered diagram generation from text descriptions. The free tier covers editing and standard export. The Pro tier adds 4x DPI PNG export, PDF export, and no watermark. If you need custom theming or high-resolution output, this is the editor to use.

Try Mermaid Editor

VS Code Extension

The Markdown Preview Mermaid Support extension renders Mermaid diagrams inline in VS Code's Markdown preview. It is ideal if you write diagrams inside documentation files and want to preview without leaving your editor. No export functionality — you still need an external tool to generate image files.

mermaid-cli

The official command-line tool for batch processing and CI/CD integration. It converts .mmd files to PNG, SVG, and PDF using Puppeteer. Great for automated documentation pipelines where diagrams are generated on every build. Not interactive — you edit in a text editor and run the CLI to see the output.

Which one should you use?

  • Quick one-off diagram — mermaid.live
  • Regular diagramming with theming — mermaideditor.io
  • Diagrams embedded in Markdown docs — VS Code extension
  • CI/CD automated generation — mermaid-cli

Mermaid.js Cheat Sheet

Bookmark this section — it is a quick reference for every Mermaid syntax pattern covered in this guide.

Flowchart nodes

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

Arrow types

SyntaxDescription
-->Solid arrow
-.->Dotted arrow
==>Thick arrow
---Solid line (no arrow)
-.-Dotted line (no arrow)
===Thick line (no arrow)
-->|label|Arrow with label
-- text -->Alternative label syntax

Flowchart directions

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

Sequence diagram messages

SyntaxDescription
->Solid line
-->Dotted line
->>Solid line with arrowhead
-->>Dotted line with arrowhead
-xSolid with cross (lost message)
--xDotted with cross
+ suffixActivate target
- prefixDeactivate source

Sequence diagram control flow

BlockUsage
alt / elseConditional branches
optOptional interaction
loopRepeated exchange
parParallel flows
Note right of ANote on right side
Note over A,BNote spanning participants

ER relationship cardinality

SyntaxMeaning
||--||One to one
||--o{One to zero-or-many
||--|{One to one-or-many
}o--o{Zero-or-many to zero-or-many
|Exactly one
oZero
{Many

ER attribute markers

MarkerMeaning
PKPrimary key
FKForeign key
UKUnique constraint

Gantt task status

KeywordEffect
doneTask completed (filled)
activeCurrently in progress (highlighted)
critCritical path (red)
milestoneZero-duration marker
after taskIdStart after dependency

Class diagram relationships

SyntaxRelationship
<|--Inheritance (extends)
*--Composition (owns)
o--Aggregation (has)
-->Association (uses)
..>Dependency
..|>Implementation (implements)

Class visibility markers

MarkerAccess level
+Public
-Private
#Protected
~Package / Internal

Theme directives

ThemeDescription
defaultLight, blue and purple tones
darkDark background, muted colors
forestGreen palette
neutralGrayscale
baseBare theme for custom variables

Theme directive syntax

%%{init: {'theme': 'dark'}}%%

Custom theme variables

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#hex',
  'primaryTextColor': '#hex',
  'lineColor': '#hex',
  'fontFamily': 'font-name'
}}}%%

That covers every Mermaid.js syntax pattern you will encounter in practice. Keep this page bookmarked as a reference, and when you are ready to build your next diagram, open Mermaid Editor and start typing.

Enjoyed this post? Subscribe for more.
>