# MermaidEditor full LLM index Canonical site: https://mermaideditor.lol MermaidEditor is an independent free online Mermaid.js editor for creating diagrams as code with instant preview, templates, tutorials, and export options. ## Core pages ### MermaidEditor — Free Online Mermaid.js Editor URL: https://mermaideditor.lol/ Free online Mermaid.js editor with instant browser preview, templates, tutorials, and PNG/SVG export. ### Mermaid Diagram Templates URL: https://mermaideditor.lol/templates Copy-paste Mermaid diagram templates for flowcharts, sequence diagrams, Gantt charts, class diagrams, ER diagrams, mindmaps, and more. ### Mermaid Syntax Cheat Sheet URL: https://mermaideditor.lol/cheat-sheet Quick reference for Mermaid.js diagram syntax and examples. ### About MermaidEditor URL: https://mermaideditor.lol/about About the MermaidEditor tool and its creator. ### Gagan Thakur URL: https://mermaideditor.lol/about/gagan-thakur Author and creator profile for MermaidEditor content. ### Contact MermaidEditor URL: https://mermaideditor.lol/contact Contact and support page for MermaidEditor. ## Blog tutorials and guides ### Mermaid Block Diagram Tutorial: Layouts & Examples URL: https://mermaideditor.lol/blog/mermaid-block-diagram-tutorial Published: 2026-05-01 Updated: 2026-05-01 Description: Learn the Mermaid.js block diagram syntax with copy-paste examples. Build system architecture, hardware layouts, and grid-based diagrams in plain text. # Mermaid Block Diagram Tutorial: Layouts, Arrows & Real Examples Mermaid's **block diagram** is one of the most underrated diagram types in the library. Introduced in Mermaid 10.9, it lets you arrange rectangular blocks in flexible grid layouts — perfect for system architecture, hardware schematics, memory maps, network zones, and any "boxes-and-lines" picture that doesn't fit neatly into a flowchart. If you've ever fought with a flowchart trying to make it look like a *layout* instead of a *flow*, this is the diagram type you've been missing. ## What Is a Mermaid Block Diagram? A block diagram is a grid of blocks (rectangles) connected by arrows. Unlike flowcharts, blocks don't try to auto-layout based on connections — **you control the columns and rows directly**. That makes them ideal for diagrams where the *spatial arrangement itself* carries meaning, like: - Microservice architectures - CPU / memory / hardware layouts - Network DMZ and security zones - UI wireframes and dashboard regions - Cloud account / VPC topologies ## Basic Syntax Every block diagram starts with the `block-beta` keyword: ```mermaid block-beta columns 3 A B C D E F ``` That single `columns 3` declaration is the magic. It tells Mermaid to lay out everything in a 3-wide grid. Add more identifiers, and they wrap into new rows automatically. ## Block Shapes Just like flowcharts, blocks support multiple shapes via bracket syntax: ```mermaid block-beta columns 4 A["Rectangle"] B("Rounded") C(("Circle")) D{"Diamond"} E[("Cylinder")] F>"Flag"] G{{"Hexagon"}} H[/"Parallelogram"/] ``` | Syntax | Shape | |--------|-------| | `A["text"]` | Rectangle | | `A("text")` | Rounded rectangle | | `A(("text"))` | Circle | | `A{"text"}` | Diamond | | `A[("text")]` | Cylinder | | `A{{"text"}}` | Hexagon | ## Spanning Columns and Rows This is where block diagrams pull ahead of flowcharts. Use `block:id:width` to make a block span multiple columns: ```mermaid block-beta columns 3 Header["Application Header"]:3 Sidebar["Sidebar"] Main["Main Content"]:2 Footer["Footer"]:3 ``` That single diagram is a complete page layout in five lines of text. Try doing *that* cleanly in a flowchart. ## Composite Blocks (Nested Groups) Use the `block:groupName` syntax to create a container that holds other blocks: ```mermaid block-beta columns 3 block:Frontend Web["Web App"] Mobile["Mobile App"] end API["API Gateway"] block:Backend Auth["Auth Service"] Users["User Service"] Orders["Order Service"] end ``` Nested groups render as labeled containers with their children inside — exactly what you want for microservice or domain-driven architecture diagrams. ## Adding Arrows Connections work the same way they do in flowcharts: ```mermaid block-beta columns 3 A["Client"] space B["Load Balancer"] space C["Server"] A --> B B --> C ``` The `space` keyword inserts an empty cell so arrows have room to breathe. Use `space:2` to skip multiple cells. ## Styling Blocks Block diagrams support the same `style` and `classDef` keywords as flowcharts: ```mermaid block-beta columns 3 A["Critical"] B["Healthy"] C["Warning"] style A fill:#ef4444,color:#fff,stroke:#991b1b style B fill:#22c55e,color:#fff,stroke:#15803d style C fill:#f59e0b,color:#fff,stroke:#b45309 ``` For repeated styles, define a class once and reuse it: ```mermaid block-beta columns 4 classDef service fill:#3b82f6,color:#fff,stroke:#1d4ed8 Web Auth Users Orders class Web,Auth,Users,Orders service ``` ## Real-World Example: AWS Architecture Here's a production-style cloud architecture in Mermaid block syntax: ```mermaid block-beta columns 5 block:Edge:5 CF["CloudFront CDN"] WAF["WAF"] R53["Route 53"] end ALB["Application Load Balancer"]:5 block:Compute:3 ECS1["ECS Task 1"] ECS2["ECS Task 2"] ECS3["ECS Task 3"] end block:Cache:2 Redis["ElastiCache"] Mem["Memcached"] end RDS["RDS Postgres (Multi-AZ)"]:3 S3["S3 Bucket"]:2 ``` Five rows, real components, zero drag-and-drop. And because it's plain text, you can diff it in pull requests, generate it programmatically, or paste it into a GitHub README and it just renders. ## When to Use Block Diagrams vs Flowcharts | Use a **block diagram** when... | Use a **flowchart** when... | |---------------------------------|------------------------------| | Layout itself carries meaning | Flow / sequence is the point | | You're drawing system architecture | You're drawing a process | | You want exact column control | You want auto-layout | | Diagram represents *space* (zones, regions) | Diagram represents *time* (steps) | ## Common Pitfalls - **Forgetting `columns N`** — without it, blocks stack vertically. Always declare your grid width. - **Spans that exceed columns** — `X:5` in a 3-column grid silently breaks layout. Match your spans to your grid. - **Old Mermaid version** — block diagrams need Mermaid **10.9 or newer**. If they don't render, upgrade your renderer (GitHub, Notion, and most modern tools already support them). - **Nested arrows** — arrows between blocks inside different `block:` groups work, but routing can get messy. Keep critical arrows at the top level. ## Conclusion Block diagrams fill the exact gap that flowcharts and ER diagrams leave open: **layout-first visualizations**. Once you've drawn one architecture diagram in `block-beta` syntax, you'll wonder why you ever opened Lucidchart for the same job. The whole syntax fits on a sticky note: `columns N`, blocks, optional spans with `:N`, and `block:group...end` for nesting. That's it. Everything else is the same Mermaid you already know. [Try the Mermaid block diagram syntax in our free editor →](/) ### Mermaid Flowchart Styling: Colors, Classes & Themes URL: https://mermaideditor.lol/blog/mermaid-flowchart-styling-guide Published: 2026-07-23 Updated: 2026-07-23 Description: Master Mermaid.js flowchart styling with inline styles, CSS classes, custom themes, and color schemes. Complete guide with copy-paste examples. # Mermaid.js Flowchart Styling: Colors, Classes & Custom Themes Mermaid.js flowcharts look decent out of the box, but real-world documentation demands custom styling — branded colors, highlighted paths, status indicators, and readable layouts. This guide covers every styling technique available in Mermaid.js flowcharts, from inline styles to reusable CSS classes and full theme customization. ## Why Style Your Mermaid Flowcharts? Default Mermaid diagrams use a generic color palette. Custom styling helps you: - **Highlight critical paths** in workflows - **Match brand guidelines** in documentation - **Indicate status** (success, failure, pending) with color coding - **Improve readability** for complex diagrams - **Create professional documentation** that stands out ## Inline Styles with `style` Keyword The simplest way to style individual nodes is the `style` keyword. Apply it after defining your flowchart: ```mermaid flowchart LR A[Start] --> B[Process] B --> C[End] style A fill:#4CAF50,stroke:#333,stroke-width:2px,color:#fff style B fill:#2196F3,stroke:#333,stroke-width:2px,color:#fff style C fill:#f44336,stroke:#333,stroke-width:2px,color:#fff ``` Available style properties: | Property | Description | Example | |----------|-------------|---------| | `fill` | Background color | `fill:#4CAF50` | | `stroke` | Border color | `stroke:#333` | | `stroke-width` | Border thickness | `stroke-width:2px` | | `color` | Text color | `color:#fff` | | `stroke-dasharray` | Dashed border | `stroke-dasharray:5 5` | | `opacity` | Transparency | `opacity:0.8` | ## Reusable Styles with `classDef` For diagrams with many nodes, inline styles get repetitive. Use `classDef` to define reusable style classes, then apply them with `:::className` or the `class` keyword: ```mermaid flowchart TD A[Deploy to Staging]:::success --> B{Tests Pass?} B -->|Yes| C[Deploy to Prod]:::success B -->|No| D[Rollback]:::danger D --> E[Fix & Retry]:::warning E --> A classDef success fill:#4CAF50,stroke:#2E7D32,color:#fff classDef danger fill:#f44336,stroke:#c62828,color:#fff classDef warning fill:#FF9800,stroke:#E65100,color:#fff ``` You can also assign classes to multiple nodes at once: ```mermaid flowchart LR A[Step 1] --> B[Step 2] --> C[Step 3] D[Step 4] --> E[Step 5] class A,B,C active class D,E inactive classDef active fill:#1a73e8,stroke:#174ea6,color:#fff classDef inactive fill:#e8eaed,stroke:#9aa0a6,color:#5f6368 ``` ## Styling Links (Edges) You can style the connections between nodes using `linkStyle`. Links are zero-indexed in the order they appear: ```mermaid flowchart LR A --> B --> C --> D linkStyle 0 stroke:#f44336,stroke-width:3px linkStyle 1 stroke:#4CAF50,stroke-width:3px linkStyle 2 stroke:#2196F3,stroke-width:3px,stroke-dasharray:5 5 ``` To style all links at once: ```mermaid flowchart LR A --> B --> C linkStyle default stroke:#999,stroke-width:2px ``` ## Real-World Example: Styled Architecture Diagram Here is a practical example showing a microservices architecture with color-coded layers: ```mermaid flowchart TB subgraph Client Layer A[Web App]:::frontend B[Mobile App]:::frontend end subgraph API Layer C[API Gateway]:::api D[Auth Service]:::api end subgraph Services E[User Service]:::service F[Order Service]:::service G[Payment Service]:::service end subgraph Data Layer H[(PostgreSQL)]:::database I[(Redis Cache)]:::cache end A & B --> C C --> D C --> E & F & G E & F --> H G --> H C --> I classDef frontend fill:#42A5F5,stroke:#1565C0,color:#fff classDef api fill:#66BB6A,stroke:#2E7D32,color:#fff classDef service fill:#FFA726,stroke:#E65100,color:#fff classDef database fill:#AB47BC,stroke:#6A1B9A,color:#fff classDef cache fill:#EF5350,stroke:#C62828,color:#fff ``` This pattern makes complex architectures instantly readable by separating concerns visually. ## Subgraph Styling You can also style subgraphs to create visual groupings: ```mermaid flowchart TB subgraph production["Production Environment"] A[Load Balancer] --> B[App Server 1] A --> C[App Server 2] end subgraph staging["Staging Environment"] D[Staging Server] end D -->|promote| A style production fill:#E8F5E9,stroke:#4CAF50,stroke-width:2px style staging fill:#FFF3E0,stroke:#FF9800,stroke-width:2px ``` ## Theme Configuration with `init` For global styling across the entire diagram, use the `init` directive to configure the theme: ```mermaid %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#1a73e8', 'primaryTextColor': '#fff', 'primaryBorderColor': '#174ea6', 'lineColor': '#5f6368', 'secondaryColor': '#e8f0fe', 'tertiaryColor': '#f1f3f4'}}}%% flowchart TD A[Start] --> B[Process 1] B --> C[Process 2] C --> D[End] ``` Built-in themes you can use: - **default** — Standard Mermaid colors - **dark** — Dark background with light text - **forest** — Green-themed - **neutral** — Grayscale, great for printing - **base** — Minimal, best for custom `themeVariables` ## Tips for Better Styled Diagrams 1. **Limit your palette** — Use 3-5 colors maximum. Too many colors create visual noise. 2. **Use semantic colors** — Green for success, red for errors, blue for information. Your readers already know these conventions. 3. **Style subgraphs with soft fills** — Use light background colors (`#E8F5E9`) for subgraphs so node colors remain prominent. 4. **Consistent stroke widths** — Pick one stroke width and stick with it unless highlighting specific paths. 5. **Test in dark mode** — If your docs support dark mode, verify your color choices work on both backgrounds. ## Try It in the Mermaid Editor Experimenting with styles is easiest in a live editor. Head over to [Mermaid Editor](https://mermaideditor.lol) to paste any of these examples, tweak the colors, and see instant results. The live preview makes it simple to fine-tune your palette before embedding diagrams in your documentation. ## Conclusion Mermaid.js flowchart styling transforms basic diagrams into professional, readable documentation. Start with `classDef` for reusable styles, use `linkStyle` for edge customization, and leverage themes for global consistency. Whether you are documenting CI/CD pipelines, microservices, or business workflows, proper styling makes your diagrams significantly more effective. ### How to Create CI/CD Pipeline Diagrams with Mermaid.js URL: https://mermaideditor.lol/blog/mermaid-cicd-pipeline-diagram Published: 2026-04-14 Updated: 2026-04-14 Description: Learn how to visualize CI/CD pipelines using Mermaid.js. Step-by-step examples for GitHub Actions, GitLab CI, Jenkins, and deployment workflows. # How to Create CI/CD Pipeline Diagrams with Mermaid.js CI/CD pipelines are the backbone of modern software delivery. But explaining a pipeline to a new team member or documenting it for an architecture review? That's where a clear diagram beats a wall of YAML every time. Mermaid.js lets you create CI/CD pipeline diagrams as code — no drag-and-drop tools, no image files to keep updated. Just text that lives alongside your pipeline config. In this guide, you'll learn how to diagram real-world CI/CD workflows using Mermaid flowcharts, sequence diagrams, and more. ## Why Diagram Your CI/CD Pipeline? Pipeline configs (GitHub Actions YAML, Jenkinsfiles, .gitlab-ci.yml) describe *what* happens, but they're hard to scan visually. A diagram answers questions instantly: - What runs in parallel vs. sequentially? - Where are the approval gates? - What happens on failure? - Which environments get deployed to? Mermaid diagrams stay in sync because they live in your repo — right next to the pipeline config they describe. ## Basic CI/CD Pipeline Flowchart Let's start with a simple build-test-deploy pipeline: ```mermaid graph LR A[Push to main] --> B[Build] B --> C[Unit Tests] C --> D[Integration Tests] D --> E[Deploy to Staging] E --> F{Manual Approval} F -->|Approved| G[Deploy to Production] F -->|Rejected| H[Rollback] ``` This gives you a left-to-right flow that anyone can understand at a glance. The diamond shape for manual approval makes the decision point obvious. ## Parallel Stages with Subgraphs Real pipelines run jobs in parallel. Mermaid subgraphs are perfect for grouping parallel stages: ```mermaid graph TD A[Code Push] --> B[Build Docker Image] B --> C[Push to Registry] C --> D[Run Tests] subgraph Tests [Parallel Test Suite] D --> E[Unit Tests] D --> F[E2E Tests] D --> G[Security Scan] D --> H[Lint & Format] end E --> I[All Passed?] F --> I G --> I H --> I I -->|Yes| J[Deploy Staging] I -->|No| K[Notify Team] ``` The subgraph labeled "Parallel Test Suite" visually groups the jobs that run concurrently, making it clear which steps block deployment. ## GitHub Actions Workflow Diagram Here's how to diagram a typical GitHub Actions workflow with multiple jobs: ```mermaid graph TD A[PR Opened] --> B[Lint Job] A --> C[Test Job] A --> D[Build Job] B --> E{All Checks Pass?} C --> E D --> E E -->|Yes| F[Merge to main] F --> G[Build & Push Image] G --> H[Deploy to EKS Staging] H --> I[Run Smoke Tests] I -->|Pass| J[Deploy to EKS Production] I -->|Fail| K[Alert on Slack] ``` This maps directly to how GitHub Actions jobs depend on each other, making it easy to compare the diagram against your workflow YAML. ## GitLab CI Pipeline Stages GitLab CI pipelines are organized in stages. Here's a multi-stage deployment diagram: ```mermaid graph LR subgraph Build Stage A[compile] --> B[docker-build] end subgraph Test Stage C[unit-test] D[sast-scan] E[dependency-check] end subgraph Deploy Stage F[deploy-staging] G[deploy-production] end B --> C B --> D B --> E C --> F D --> F E --> F F --> G ``` Each subgraph maps to a GitLab CI stage, and the arrows show job dependencies — exactly matching the `needs:` keyword in your `.gitlab-ci.yml`. ## Deployment Pipeline with Rollback For production deployments, you need to show the rollback path: ```mermaid graph TD A[Release Tagged] --> B[Build Artifacts] B --> C[Deploy to Canary 5%] C --> D{Metrics OK?} D -->|Yes| E[Roll out to 25%] E --> F{Metrics OK?} F -->|Yes| G[Roll out to 100%] F -->|No| H[Rollback to Previous] D -->|No| H H --> I[Post-mortem] G --> J[Monitor 24h] ``` This canary deployment diagram shows progressive rollout percentages and the rollback path — critical for communicating deployment strategy to stakeholders. ## Sequence Diagram for Deployment Approval Sometimes a sequence diagram better captures the interaction between people and systems: ```mermaid sequenceDiagram participant Dev as Developer participant CI as CI Server participant QA as QA Team participant Prod as Production Dev->>CI: Push to release branch CI->>CI: Build & Test CI->>QA: Deploy to staging QA->>QA: Run acceptance tests QA->>Dev: Approve / Request changes Dev->>CI: Trigger production deploy CI->>Prod: Blue-green deployment Prod->>CI: Health check OK CI->>Dev: Deployment successful ``` This shows who is involved at each stage — useful for runbooks and on-call documentation. ## Styling Your Pipeline Diagrams Make critical paths and failure states stand out with Mermaid styling: ```mermaid graph LR A[Build] --> B[Test] B --> C[Deploy] C --> D[Production Live] B --> E[Failed] style D fill:#22c55e,stroke:#16a34a,color:#fff style E fill:#ef4444,stroke:#dc2626,color:#fff style A fill:#3b82f6,stroke:#2563eb,color:#fff ``` Green for success, red for failure, blue for in-progress — your team will instantly understand the pipeline state. ## Best Practices for CI/CD Diagrams 1. **Keep it high-level** — Don't diagram every shell command. Focus on stages and decision points. 2. **Use subgraphs for parallel work** — Group concurrent jobs visually. 3. **Show the unhappy path** — Rollbacks, failures, and alerts are just as important as the happy path. 4. **Put diagrams in your README** — GitHub and GitLab both render Mermaid natively in markdown. 5. **Update with the pipeline** — When you change your CI config, update the diagram in the same PR. ## Where to Use These Diagrams - **README.md** — GitHub and GitLab render Mermaid automatically - **Architecture Decision Records (ADRs)** — Document why your pipeline works this way - **Onboarding docs** — New engineers understand the deploy process in seconds - **Incident runbooks** — Show the rollback path clearly ## Conclusion Mermaid.js turns CI/CD pipeline documentation from a chore into something that actually stays maintained. Because the diagram is text, it can be reviewed in PRs, diffed, and updated alongside the pipeline config it describes. Start with a simple flowchart of your main pipeline, then expand to cover parallel stages, approval gates, and rollback paths. [Create your CI/CD pipeline diagram now →](/) ### Mermaid.js Quadrant Chart: Complete Guide with Examples URL: https://mermaideditor.lol/blog/mermaid-quadrant-chart-guide Published: 2026-04-10 Updated: 2026-04-10 Description: Learn how to create quadrant charts in Mermaid.js for prioritization, risk analysis, and strategic planning. Includes syntax, examples, and best practices. # Mermaid.js Quadrant Chart: Complete Guide with Examples Quadrant charts are one of the most powerful yet underused diagram types in Mermaid.js. They let you plot items across two axes to visualize priorities, risks, strategies, and trade-offs — all with simple text-based syntax. In this guide, you'll learn everything about creating **Mermaid quadrant charts**, from basic syntax to real-world examples you can use today. ## What Is a Quadrant Chart? A quadrant chart divides a two-dimensional space into four sections using two axes. Each quadrant represents a different category or priority level. You've probably seen them used as: - **Eisenhower Matrix** (urgent vs. important) - **BCG Matrix** (market growth vs. market share) - **Risk Matrix** (likelihood vs. impact) - **Feature Prioritization** (effort vs. value) Mermaid.js makes it easy to create these charts with plain text, no drag-and-drop tools required. ## Basic Mermaid Quadrant Chart Syntax Here's the simplest quadrant chart you can create in Mermaid.js: ```mermaid quadrantChart title Feature Prioritization x-axis Low Effort --> High Effort y-axis Low Value --> High Value quadrant-1 Do First quadrant-2 Plan Carefully quadrant-3 Quick Wins quadrant-4 Deprioritize Feature A: [0.8, 0.9] Feature B: [0.2, 0.8] Feature C: [0.7, 0.3] Feature D: [0.3, 0.2] ``` Let's break down the syntax: - **`quadrantChart`** — declares the diagram type - **`title`** — sets the chart title - **`x-axis`** and **`y-axis`** — define axis labels with direction (low → high) - **`quadrant-1`** through **`quadrant-4`** — label each quadrant (numbered top-right, top-left, bottom-left, bottom-right) - **Data points** — each item has a name and `[x, y]` coordinates between 0 and 1 ## Understanding Quadrant Numbering The quadrant numbering in Mermaid.js follows a specific order that's important to understand: | Quadrant | Position | Typical Use | |----------|----------|-------------| | quadrant-1 | Top-Right | High priority / best outcome | | quadrant-2 | Top-Left | High on Y, low on X | | quadrant-3 | Bottom-Left | Lowest priority | | quadrant-4 | Bottom-Right | High on X, low on Y | This numbering follows mathematical convention (counter-clockwise from top-right), so keep it in mind when labeling your quadrants. ## Real-World Mermaid Quadrant Chart Examples ### 1. Eisenhower Priority Matrix The Eisenhower Matrix is perfect for task management and personal productivity: ```mermaid quadrantChart title Eisenhower Matrix x-axis Not Urgent --> Urgent y-axis Not Important --> Important quadrant-1 Do It Now quadrant-2 Schedule It quadrant-3 Eliminate quadrant-4 Delegate Crisis meeting: [0.9, 0.9] Strategic planning: [0.2, 0.85] Email replies: [0.75, 0.2] Social media: [0.15, 0.1] Code review: [0.6, 0.7] Documentation: [0.3, 0.6] ``` This example plots common work tasks across urgency and importance, making it instantly clear what to focus on. ### 2. Technology Risk Assessment Use a quadrant chart to evaluate technology risks in your architecture: ```mermaid quadrantChart title Tech Risk Assessment x-axis Low Likelihood --> High Likelihood y-axis Low Impact --> High Impact quadrant-1 Critical Risk quadrant-2 Monitor Closely quadrant-3 Accept quadrant-4 Mitigate Database failure: [0.3, 0.95] API rate limiting: [0.7, 0.5] CSS regression: [0.6, 0.15] Auth provider outage: [0.2, 0.8] Memory leak: [0.5, 0.7] Typo in config: [0.8, 0.1] ``` ### 3. Product Feature Effort-Impact Matrix Product managers love this one for sprint planning: ```mermaid quadrantChart title Sprint Planning Matrix x-axis Low Effort --> High Effort y-axis Low Impact --> High Impact quadrant-1 Major Projects quadrant-2 Quick Wins quadrant-3 Fill-Ins quadrant-4 Thankless Tasks Dark mode: [0.4, 0.85] Search feature: [0.85, 0.9] Fix typos: [0.1, 0.15] Refactor auth: [0.9, 0.4] Add tooltips: [0.2, 0.5] Export to PDF: [0.6, 0.75] ``` ## Tips for Better Quadrant Charts ### 1. Choose Meaningful Axes Your axes should represent two independent dimensions that create meaningful quadrants. Common axis pairs include: - Effort vs. Value - Risk vs. Reward - Urgency vs. Importance - Cost vs. Benefit - Feasibility vs. Desirability ### 2. Position Points Carefully Coordinates range from 0 to 1. Use the full range to spread your data points and avoid clustering them in one area. Items near quadrant boundaries signal areas that need discussion. ### 3. Keep It Focused Quadrant charts work best with 4–12 data points. Too many items create visual clutter and defeat the purpose of prioritization. ### 4. Use Descriptive Labels Quadrant labels should immediately communicate the action or category. "Do First" is better than "Q1". "Eliminate" is better than "Low-Low". ## Mermaid Quadrant Chart vs. Other Tools Why use Mermaid.js for quadrant charts instead of Excel, Google Sheets, or dedicated tools? - **Version control** — Mermaid charts live in your codebase and are tracked by Git - **Documentation-as-code** — embed charts directly in Markdown files, READMEs, and wikis - **No vendor lock-in** — plain text means you own your diagrams forever - **Fast iteration** — change a number and the chart updates instantly - **Works everywhere** — GitHub, GitLab, Notion, Obsidian, VS Code, and [online editors like MermaidEditor.lol](https://mermaideditor.lol) ## Try It in the Online Editor The fastest way to experiment with Mermaid quadrant charts is to use an online editor. At [MermaidEditor.lol](https://mermaideditor.lol), you can: - Write your quadrant chart syntax with live preview - Export diagrams as PNG or SVG - Share your charts with a link - Access templates to get started quickly Paste any of the examples from this guide into the editor and start customizing them for your own use case. ## Common Mistakes to Avoid 1. **Forgetting the coordinate brackets** — data points need `[x, y]` format 2. **Mixing up quadrant numbers** — remember, numbering starts top-right and goes counter-clockwise 3. **Using coordinates outside 0–1** — Mermaid only accepts values between 0 and 1 4. **Overcrowding the chart** — if you have more than 12 items, consider splitting into multiple charts ## Conclusion Mermaid.js quadrant charts are a simple but powerful way to visualize two-dimensional comparisons. Whether you're prioritizing features, assessing risks, or planning your sprint, the text-based syntax makes it easy to create, update, and share these diagrams. Ready to create your first quadrant chart? Head over to [MermaidEditor.lol](https://mermaideditor.lol) and start building. ### How to Create Timeline Diagrams with Mermaid.js URL: https://mermaideditor.lol/blog/mermaid-timeline-diagram Published: 2026-04-07 Updated: 2026-05-27 Description: Learn how to create mermaid timeline diagrams with simple text syntax. Includes real-world examples for project roadmaps, historical events, and release schedules. ## What Is a Mermaid Timeline Diagram? A **mermaid timeline diagram** lets you visualize events, milestones, and phases in chronological order — using nothing but text. No drag-and-drop tools, no image editing, no external software. Just write the syntax, and Mermaid renders a clean, shareable timeline. Timeline diagrams are perfect for: - Product roadmaps and release schedules - Historical events and project retrospectives - Onboarding docs showing company or project history - Sprint planning visuals embedded in your README In this guide you'll learn the complete Mermaid timeline syntax, see multiple real-world examples, and pick up tips for writing timelines that are easy to maintain. ## Basic Mermaid Timeline Syntax The timeline diagram type was introduced in Mermaid v9.4. The core structure is straightforward: ```mermaid timeline title History of Mermaid.js 2014 : Knut Sveidqvist releases Mermaid on GitHub 2016 : First major adoption in developer docs 2019 : GitHub integration discussions begin 2022 : GitHub natively renders Mermaid in Markdown 2023 : Mermaid v10 released with major improvements 2024 : Over 60,000 GitHub stars ``` Breaking down the syntax: - **`timeline`** — declares the diagram type - **`title`** — optional chart title displayed at the top - **`2014 : Event text`** — a time period followed by `:` and the event label Multiple events can share the same time period by adding more lines with the same period label. ## Adding Multiple Events Per Period One of the most useful features is grouping multiple events under a single time label: ```mermaid timeline title 2025 Product Roadmap Q1 : Launch beta : Onboard first 100 users : Set up analytics Q2 : Public launch : Email campaign Q3 : Mobile app release : Paid tier introduced Q4 : Enterprise plan : Partner integrations ``` Each additional `: event` line (indented, without repeating the period) is added to that period's column. This keeps related events grouped without cluttering the timeline axis. ## Sections — Adding Colour-Coded Groups For longer timelines, you can organise periods into named sections. Each section gets its own colour in the rendered diagram: ```mermaid timeline title Company Growth Timeline section Early Stage 2020 : Company founded : Seed funding ($500K) 2021 : First product shipped : 5-person team section Growth Stage 2022 : Series A ($3M) : 20-person team : First enterprise customer 2023 : Product line expanded : Reached profitability section Scale Stage 2024 : Series B ($15M) : 80-person team 2025 : International expansion : IPO preparation ``` Sections are declared with `section Name` and apply to all subsequent periods until another section is declared. They're great for separating phases of a project, company lifecycle stages, or sprint cycles. ## Real-World Example: Software Release History Here's a mermaid timeline diagram documenting a product's version history — a common use case for developer docs and README files: ```mermaid timeline title My App — Release History section Alpha v0.1 : Core authentication : Basic CRUD operations v0.2 : REST API stabilised : Unit tests added section Beta v0.5 : Public beta launched : Dashboard UI : Email notifications v0.9 : Performance optimisations : Bug fixes from beta feedback section Production v1.0 : General availability : Stripe payments integrated v1.1 : Team collaboration features v2.0 : Real-time sync : Mobile app (iOS + Android) ``` Because the source is plain text, this lives right in your repo. When you ship v2.1, you add two lines — no image exports needed. ## Example: Project Sprint Timeline Timeline diagrams also work well for sprint planning or retrospective documentation: ```mermaid timeline title Q1 Sprint Overview section Sprint 1 (Jan) Week 1 : Kick-off and backlog grooming : Environment setup Week 2 : User auth module Week 3 : Profile management Week 4 : Sprint review and demo section Sprint 2 (Feb) Week 5 : Dashboard v1 : API rate limiting Week 6 : Notifications service Week 7 : Data export feature Week 8 : Sprint review section Sprint 3 (Mar) Week 9 : Mobile-responsive UI Week 10 : Performance profiling Week 11 : Load testing Week 12 : Q1 retrospective ``` ## Example: Historical Technology Timeline Mermaid timeline diagrams aren't just for software projects. They're equally useful for educational content, articles, and documentation that places events in historical context: ```mermaid timeline title Key Moments in Web Development section Web 1.0 1991 : Tim Berners-Lee publishes the first website 1994 : Netscape Navigator launches 1995 : JavaScript created by Brendan Eich : Java applets introduced 1996 : CSS 1 specification released section Web 2.0 2004 : Gmail launches, proving rich web apps are possible 2005 : AJAX popularised by Google Maps : YouTube founded 2006 : jQuery released 2008 : V8 JavaScript engine by Google 2009 : Node.js created by Ryan Dahl section Modern Web 2013 : React released by Facebook 2014 : Vue.js introduced 2016 : Angular 2 released 2017 : WebAssembly becomes a W3C recommendation draft 2020 : Deno 1.0 released 2022 : Bun JavaScript runtime released ``` ## Embedding Timelines in Your Docs Mermaid timeline diagrams render natively in **GitHub Markdown** (wrap in a `mermaid` code fence), **Notion** (paste using the Mermaid block), **Obsidian**, **Docusaurus**, **MkDocs**, and anywhere Mermaid is supported. For GitHub specifically: ``` ```mermaid timeline title My Project Milestones 2024 : MVP shipped 2025 : 1,000 users ``` ``` You can also try and iterate on your timeline syntax in the [Mermaid Live Editor](https://mermaideditor.lol) before committing — it gives instant visual feedback as you type, so you can see how sections and event groupings look before they go into your docs. ## Mermaid Timeline vs Gantt Chart Mermaid offers two diagram types that handle time-based content differently: | Feature | Timeline | Gantt Chart | |---|---|---| | Purpose | Events and milestones | Task durations and schedules | | Shows duration | No | Yes | | Dependencies | No | Yes | | Best for | History, roadmaps, retrospectives | Project planning, scheduling | | Syntax complexity | Simple | Moderate | If you need to show **how long** tasks take, use a Gantt chart. If you want to place **events and milestones** in chronological context, use a timeline diagram. ## Tips for Better Timeline Diagrams **Keep event labels short.** The timeline renders each event as a chip inside a column. Long text wraps awkwardly. Aim for 3-6 words per event. **Use consistent period granularity.** Mixing `Q1 2024` with `Week 3` in the same diagram looks messy. Pick a granularity (quarters, months, sprints) and stick to it. **Use sections for long timelines.** Anything with more than 6-8 periods benefits from section groupings — they add colour contrast and logical separation. **Put the most important events first in a period.** Mermaid displays events top-to-bottom within a period column. Lead with the headline event. **Test in the live editor first.** Before adding a timeline to your repo's README or docs, paste it into [mermaideditor.lol](https://mermaideditor.lol) to see how it renders. Easier to tweak there than after pushing a commit. ## Troubleshooting Common Issues **Timeline not rendering?** Check that you're on Mermaid v9.4+. GitHub, Notion, and most modern integrations are already there, but self-hosted tools may lag behind. **Events appearing in wrong order?** Mermaid renders periods in the order they appear in the source — there's no automatic date sorting. Write them top-to-bottom in chronological order. **Text overflowing?** Shorten event labels or split into multiple sections. **Section colours look off in dark mode?** Mermaid's built-in themes handle dark mode differently. Use the `dark` or `default` theme directive at the top of your diagram if needed. ## Conclusion Mermaid timeline diagrams are a quick, maintainable way to visualise chronological information in your documentation. The syntax is minimal, the output is clean, and because diagrams live as text in your repo, they stay up-to-date as your project evolves. Start with a simple 4-5 period timeline, add sections when it grows, and you'll have professional-looking roadmap and history diagrams without ever opening a design tool. [Try building your timeline diagram for free at mermaideditor.lol →](/) ## Additional Guide: How to Use Mermaid Timeline Diagrams: Complete Instructions Guide (2026) Mermaid timelines are one of the most underused features in the library. Everyone knows flowcharts and sequence diagrams — but timelines? They're clean, readable, and perfect for project overviews, research plans, and historical summaries. This guide covers everything: the full syntax, sections, multi-line events, and real working examples you can copy and run immediately. ## What Is a Mermaid Timeline? A Mermaid timeline (`timeline` diagram type) lets you map events to time periods using plain text. You define time sections, then list events under each one. Mermaid renders it as a horizontal or vertical visual timeline. It's different from a Gantt chart. Gantt tracks duration and dependencies. A timeline is simpler — it's a chronological story. **When to use it:** - Project milestone overviews - Product roadmaps - Research planning (phases of a study) - Historical event summaries - Onboarding sequences ## Basic Syntax — Your First Timeline Here's the minimal structure: ```mermaid timeline title My Project Timeline section Phase 1 Kick-off meeting : 2026-01-01 Requirements done : 2026-01-15 section Phase 2 Design complete : 2026-02-01 Dev complete : 2026-03-01 ``` **What this does:** Creates a timeline with two sections (Phase 1 and Phase 2), each with two events. The colon separates the event label from the date. Key rules: - `timeline` keyword starts the diagram - `title` is optional but recommended - `section` groups related events - Each event: `Event label : date-or-period` ## Understanding Sections Sections are the backbone of Mermaid timelines. They create visual groupings that help readers scan the timeline at a glance. ```mermaid timeline title Software Release History section 2024 v1.0 Launch : Jan 2024 v1.1 Bug fixes : Mar 2024 v1.2 New features : Jun 2024 section 2025 v2.0 Major rewrite : Jan 2025 v2.1 Performance : Apr 2025 section 2026 v3.0 AI features : Feb 2026 v3.1 Mobile app : May 2026 ``` **What this does:** Maps a software product's release history across three years. Each section represents a year, and events inside show individual releases. Sections don't have to be time-based. You can use phases, themes, or any logical grouping. ## Events Without Sections You can skip sections entirely for simple timelines: ```mermaid timeline title Key Dates for Product Launch Idea validated : Week 1 MVP built : Week 3 Beta testers recruited : Week 5 Public launch : Week 8 First 100 users : Week 10 ``` **What this does:** Shows a linear sequence of 5 milestones without any grouping. Best for short timelines where you don't need categories. This is the simplest form — just a title and events. Good for roadmaps where phases aren't needed. ## Multi-Event Entries One of the most useful features: multiple events can share the same time period. This is great for showing parallel tasks. ```mermaid timeline title Q1 2026 Sprint Plan section January Backend API design Database schema finalized Team onboarding : Jan 2026 section February Frontend development API integration Unit testing : Feb 2026 section March QA testing Performance optimization Staging deployment : Mar 2026 ``` **What this does:** Shows parallel workstreams in each month. Multiple items are listed under the same section, making it clear that these tasks happen simultaneously. Notice that only the last item in each section gets the `: date` — the others are just labels. This is valid syntax and renders cleanly. ## Styling Your Timeline You can add themes and customize via Mermaid's `%%{init: ...}%%` directive: ```mermaid %%{init: { 'logLevel': 'debug', 'theme': 'forest' } }%% timeline title Team Milestones — Forest Theme section Founding Company incorporated : 2020 First hire : 2020 section Growth Series A raised : 2022 50 employees : 2023 section Scale International expansion : 2025 IPO filed : 2026 ``` **What this does:** Applies the "forest" color theme to the timeline. Available themes: `default`, `forest`, `dark`, `neutral`, `base`. The `logLevel: debug` helps during development when you need to troubleshoot rendering issues. ## Common Mistakes (and How to Fix Them) **Mistake 1: Forgetting the `timeline` keyword** Every diagram needs the type declaration first. `timeline` must be the first non-comment line. **Mistake 2: Missing colons** Event syntax requires `: period`. Without the colon, Mermaid treats the line as a continuation, not a new event. **Mistake 3: Inconsistent indentation** Mermaid uses indentation to understand structure. Keep sections and events consistently indented (2 or 4 spaces — pick one). **Mistake 4: Overly long event labels** Long labels overflow on narrow screens. Keep event text under 40 characters for clean rendering. ## Full Example: Product Launch Timeline Here's a complete, real-world example combining all the concepts: ```mermaid timeline title SaaS Product Launch — 2026 Roadmap section Discovery (Jan) Customer interviews done Problem validated Competitors analyzed : January section Build (Feb-Mar) MVP development Internal alpha testing Bug fixes complete : Feb-Mar section Launch (Apr) Beta program opens Press release published Product Hunt launch : April section Growth (May+) Paid ads start Content marketing live First 500 customers : May onwards ``` **What this does:** A complete SaaS product launch plan, from discovery to growth, mapped across 4 months. This is production-ready — you could put this in a project README today. ## Tips for Better Timelines **Keep it scannable.** Timelines work best when you can read them in 30 seconds. If you're adding more than 6-8 events per section, consider splitting into multiple diagrams. **Use consistent date formats.** Mixing "Jan 2026", "2026-01-01", and "Q1 2026" in the same timeline looks messy. Pick one format and stick to it. **Pair with a Gantt when needed.** If you need to show duration or dependencies between tasks, a [Mermaid Gantt chart](/templates) is a better fit. Timelines show *when*, Gantts show *how long*. **Embed in docs.** Mermaid works natively in GitHub Markdown, Notion, GitLab, and most modern wikis. Write your timeline in plain text and it renders automatically. ## Want to See More Timeline Examples? Check out our post on [10 Mermaid Timeline Examples with Step-by-Step Code](/blog/mermaid-timeline-diagram) for real use cases including research plans, sprint schedules, and historical timelines. For the full syntax reference, visit the [Mermaid Timeline Syntax guide](/blog/mermaid-timeline-diagram). --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** Paste any of the code blocks above and see your timeline render instantly. No sign-up, no install. Just paste and go. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ## Additional Guide: 10 Mermaid Timeline Examples with Step-by-Step Code (2026) The best way to learn Mermaid timelines is to see real ones — not toy examples, but actual diagrams you'd use in a project. Here are 10 working examples, each with the code and a breakdown of what's happening. Copy any of these, paste into [mermaideditor.lol](https://mermaideditor.lol), and you'll see it render immediately. ## Example 1: Software Sprint Timeline Great for engineering teams doing 2-week sprints. Shows what gets done each sprint without the overhead of a full Gantt chart. ```mermaid timeline title Backend API Project — Sprint Timeline section Sprint 1 (May 1-14) Auth service design DB schema review Auth endpoints live : May 14 section Sprint 2 (May 15-28) User profile API File upload service Integration tests pass : May 28 section Sprint 3 (Jun 1-14) Admin dashboard API Rate limiting Performance benchmarks : Jun 14 section Sprint 4 (Jun 15-30) Security audit Load testing v1.0 shipped : Jun 30 ``` **Step-by-step breakdown:** Four sprints, each 2 weeks. Each section has 2-3 parallel tasks and one milestone (the deliverable). The last event in each section gets the date label — this becomes the anchor point readers scan for. --- ## Example 2: Product Roadmap A high-level roadmap you'd show to stakeholders or put in a pitch deck. ```mermaid timeline title MobileApp Roadmap 2026 section Q1 2026 MVP features defined iOS prototype built Android prototype built : Q1 section Q2 2026 Beta launch (iOS) Beta launch (Android) 1,000 beta users : Q2 section Q3 2026 Public launch App Store featured 10,000 downloads : Q3 section Q4 2026 Premium tier launch Enterprise plan Profitability : Q4 ``` **Step-by-step breakdown:** Quarterly sections, each with 3 events. The last event is always a measurable goal (users, downloads, revenue). This gives stakeholders a story arc, not just a list of tasks. --- ## Example 3: Research Project Plan Academic researchers love this format. See more in our dedicated post on [building a research plan with Mermaid timeline](/blog/mermaid-timeline-diagram). ```mermaid timeline title PhD Research Plan — 3 Year Study section Year 1 Literature review complete Research questions defined Ethics approval received : 2024 section Year 2 Data collection phase 1 Qualitative interviews (n=30) Preliminary analysis done : 2025 section Year 3 Full data analysis Paper submitted to journal Thesis defense : 2026 ``` **Step-by-step breakdown:** Three yearly sections map the arc of a 3-year PhD program. Each section has the key deliverables that supervisors and committees care about. Clean enough to put in a research proposal. --- ## Example 4: Company History Perfect for About pages, investor decks, and onboarding docs. ```mermaid timeline title Acme Corp — Company History section 2018 Founded in garage First product shipped : 2018 section 2019 Seed round ($500K) First 10 employees : 2019 section 2021 Series A ($5M) Opened London office : 2021 section 2023 Series B ($20M) 100 employees milestone : 2023 section 2026 IPO filed Global expansion : 2026 ``` **Step-by-step breakdown:** A company's milestones from founding to IPO. Two events per section keeps it readable. Funding rounds and headcount milestones are the kinds of facts that make company histories scannable. --- ## Example 5: Content Marketing Calendar Editorial teams use this to visualize what's publishing when across channels. ```mermaid timeline title Content Calendar — May 2026 section Week 1 (May 1-7) Blog: SEO fundamentals Newsletter: subscriber growth tips Launch: video series ep.1 : May 7 section Week 2 (May 8-14) Blog: case study Podcast: guest interview Webinar: live Q&A : May 14 section Week 3 (May 15-21) Blog: product update Social: UGC campaign Email: re-engagement : May 21 section Week 4 (May 22-31) Blog: monthly roundup Newsletter: May wrap-up Retrospective: metrics review : May 31 ``` **Step-by-step breakdown:** Weekly sections, each with content across three channels (blog, email, video/social). The last item is either a publish event or a review. Easy to update as the month progresses. --- ## Example 6: Onboarding Journey Map the steps a new user goes through, from sign-up to power user. ```mermaid timeline title New User Onboarding Flow section Day 0 Account created Welcome email sent Profile setup prompt : Day 0 section Day 1 First feature tour Sample project created Invite team prompt : Day 1 section Day 3 Usage tip email Template suggestions Support check-in : Day 3 section Day 7 Power user guide sent Upgrade prompt shown NPS survey triggered : Day 7 section Day 30 Monthly summary email Loyalty reward offered Retention check : Day 30 ``` **Step-by-step breakdown:** Day-based sections show exactly when each touchpoint fires. Product managers use this to spot gaps in onboarding flows. The time labels (Day 0, Day 1, etc.) make the cadence obvious. --- ## Example 7: Event Planning For conferences, launches, or marketing events with multiple workstreams. ```mermaid timeline title Annual Dev Conference — Planning section 6 Months Out Venue booked Speakers recruited Sponsorship packages sent : Nov 2025 section 3 Months Out Agenda published Tickets on sale Marketing campaign live : Feb 2026 section 1 Month Out Catering confirmed AV setup planned Attendee emails sent : Apr 2026 section Event Week Registration opens Keynote rehearsal Conference day 1 : May 2026 ``` **Step-by-step breakdown:** Lead-time sections (6 months, 3 months, 1 month, event week) make this reusable for any event. The approach — counting down instead of counting up — is how event planners actually think. --- ## Example 8: Personal Career Timeline Great for portfolios, LinkedIn "About" sections, or just tracking your own growth. ```mermaid timeline title Career Journey section Early Career Junior Dev at Startup : 2015 First team lead role : 2017 section Mid Career Senior Engineer : 2019 First conference talk : 2020 Open source project (2K stars) : 2021 section Now Principal Engineer : 2023 Started consulting practice : 2025 Author of dev book : 2026 ``` **Step-by-step breakdown:** Three loose phases (early, mid, now) instead of strict years. This gives a narrative arc rather than a flat list of jobs. The standout achievements (conference talk, GitHub stars, book) tell the story better than job titles alone. --- ## Example 9: Security Incident Timeline When a security incident happens, you need a clear timeline for the post-mortem report. ```mermaid timeline title Security Incident — May 5, 2026 section Detection Anomalous login detected Alert triggered in SIEM On-call engineer notified : 02:14 AM section Containment Affected accounts locked API keys rotated External access blocked : 02:45 AM section Investigation Log analysis started Attack vector identified Scope confirmed (3 accounts) : 04:30 AM section Recovery Accounts restored Security patches applied All-clear declared : 09:00 AM ``` **Step-by-step breakdown:** Time-stamped sections (02:14, 02:45, etc.) make incident timelines precise. Four phases — Detection, Containment, Investigation, Recovery — follow the standard incident response framework. This format goes directly into a post-mortem doc. --- ## Example 10: Learning Path / Curriculum For courses, bootcamps, or self-study plans. ```mermaid timeline title Full-Stack Developer Learning Path section Foundations (Month 1) HTML & CSS basics JavaScript fundamentals First static website : Month 1 section Frontend (Month 2-3) React basics State management Built 3 portfolio projects : Month 3 section Backend (Month 4-5) Node.js & Express SQL & databases REST API built : Month 5 section Full Stack (Month 6) Deploy to cloud Auth & security Capstone project shipped : Month 6 ``` **Step-by-step breakdown:** A 6-month bootcamp curriculum in one diagram. Each section ends with a concrete deliverable (website, projects, API, capstone). Instructors can use this as the first slide of an orientation session. --- ## Which Example Should You Start With? - **Engineering teams:** Examples 1 (sprint) or 9 (incident) are immediately practical. - **Product managers:** Examples 2 (roadmap) or 7 (event) give you stakeholder-ready visuals fast. - **Researchers/academics:** Examples 3 (research plan) and 10 (learning path) map directly to your work. - **Content teams:** Example 5 (content calendar) will replace your spreadsheet. Want to dive deeper into the syntax? Read the [complete Mermaid timeline instructions guide](/blog/mermaid-timeline-diagram) or the [timeline syntax reference](/blog/mermaid-timeline-diagram). --- **Try these live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** Paste any example above and watch it render in real-time. No setup, no account needed. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ## Additional Guide: Mermaid Timeline Syntax: Every Element Explained with Examples This is the definitive syntax reference for Mermaid timelines. Not a beginner's intro — a complete element-by-element breakdown of every syntax feature, with working examples and the edge cases you'll actually hit. If you're new to timelines, start with the [Mermaid Timeline Instructions Guide](/blog/mermaid-timeline-diagram). Come back here when you need the specific syntax for something. ## Diagram Declaration Every Mermaid timeline starts with the `timeline` keyword on its own line: ```mermaid timeline title My First Timeline Event 1 : Period 1 Event 2 : Period 2 ``` **What this does:** The simplest valid timeline — a title and two events. `timeline` is the type declaration. Without it, Mermaid doesn't know which diagram type you're writing. **Edge case:** `Timeline` (capital T) does NOT work. The keyword is case-sensitive: `timeline` only. --- ## Title Element ```mermaid timeline title Product Roadmap 2026 Launch MVP : Q1 Beta program : Q2 Public launch : Q3 ``` **Syntax:** `title Your Title Text` **Rules:** - Goes immediately after the `timeline` declaration - Optional — timelines render without a title - One title only — multiple `title` lines cause parse errors - No quotes needed, even with spaces **What this does:** Adds a heading above the timeline. Recommended for any timeline that will be shared or embedded in docs — gives immediate context. --- ## Event Syntax The core building block: ```mermaid timeline title Event Syntax Examples Single event : Period A Another event : Period B Third event : Period C ``` **Syntax:** `EventLabel : TimePeriod` The colon `:` separates the event label from the time period. Both sides are plain text — no quoting needed unless you need special characters. **What this does:** Three events mapped to three periods. The period (right of the colon) is what renders as the time label in the diagram. **Edge cases:** - Missing colon: the line is treated as a multi-event entry (see below), not a new event with a period - Extra spaces around the colon are fine: `Event : Period` and `Event:Period` both work - Long event labels: keep under 50 chars for clean rendering. Longer labels wrap or overflow. --- ## Section Element Sections group events into visual blocks: ```mermaid timeline title Grouped by Phase section Phase 1 Research complete Prototype built : Month 1 section Phase 2 User testing done Feedback analyzed : Month 2 section Phase 3 Final version shipped Documentation done : Month 3 ``` **Syntax:** `section Section Name` **Rules:** - Sections must come before their events (events are indented under the section) - A timeline can mix sections and non-section events — though it's cleaner to use one or the other - Section names appear as visual dividers in the rendered diagram - No `end` keyword needed — the next `section` or end of file closes the current one **What this does:** Adds visual grouping. Three phases, each with two events. The section header acts like a category label for the events underneath. --- ## Multi-Event Entries (Parallel Events) Multiple events can share the same time period: ```mermaid timeline title Parallel Work in Q1 section January Backend API built Frontend prototype Mobile wireframes : January section February API integration Frontend polish Mobile beta build : February ``` **Syntax:** List multiple items under a section. Only the last item gets the `: Period` marker. The others are treated as additional events for the same period. **What this does:** Shows three parallel work streams in each month. January has three simultaneous activities; February has three more. The time period only appears once (on the last item), preventing visual clutter. **Edge case:** All items above the colon-marked one render as events for the same period. If you accidentally omit the colon from every item in a section, Mermaid may render them oddly — always have exactly one `event : period` per section as the anchor. --- ## Date and Period Formats Mermaid timelines are format-agnostic. The period text is just a label — Mermaid doesn't validate or parse dates: ```mermaid timeline title Date Format Flexibility Project kick-off : 2026-01-01 Sprint 1 ends : January 14 Beta launch : Q1 2026 Public launch : Spring 2026 Year-end review : Dec 2026 ``` **What this does:** Shows five different date/period formats in one diagram. ISO dates, natural language months, quarter notation, seasons, and abbreviated months — all valid. Pick the format that matches your audience's expectations. **Best practice:** Be consistent within a single timeline. Mixing formats (ISO dates in section 1, "Q1/Q2" in section 2) looks unprofessional. Choose one convention and stick to it. --- ## Theme Configuration Apply Mermaid's built-in themes via the `%%{init}%%` directive: ```mermaid %%{init: { 'theme': 'forest' } }%% timeline title Forest Theme Timeline section 2024 Planted seeds First growth : 2024 section 2025 Rapid expansion Maturity reached : 2025 section 2026 Full bloom : 2026 ``` **Syntax:** `%%{init: { 'theme': 'THEMENAME' } }%%` on the line before `timeline` **Available themes:** `default`, `forest`, `dark`, `neutral`, `base` **What this does:** Applies the "forest" color theme to the entire diagram. The `%%{init}%%` directive tells the Mermaid renderer to apply these settings before rendering. **Note:** The init directive affects the whole diagram. You can also set `logLevel`, `fontFamily`, and other renderer options in the same object. --- ## Custom Styling via init More advanced customization through the init block: ```mermaid %%{init: { 'theme': 'base', 'themeVariables': { 'primaryColor': '#7B2D8B', 'primaryTextColor': '#fff', 'lineColor': '#7B2D8B' } } }%% timeline title Custom Color Timeline Feature A shipped : Q1 Feature B launched : Q2 Feature C in beta : Q3 Full suite complete : Q4 ``` **What this does:** Sets custom colors using `themeVariables`. `primaryColor` changes the section/event block color. `primaryTextColor` sets text color inside blocks. `lineColor` sets the connecting line color. Use hex codes. --- ## Section-Free Timelines For simple linear sequences, skip sections entirely: ```mermaid timeline title Simple Linear Timeline Idea formed : Week 1 Research done : Week 2 Prototype built : Week 4 Tested with users : Week 6 Shipped : Week 8 ``` **What this does:** A clean 5-event linear timeline with no section grouping. Works best for short timelines (under 8 events) where the events are sequential and don't need categorization. --- ## Long Labels and Wrapping ```mermaid timeline title Labels of Different Lengths Short : Jan A medium-length event label here : Feb This is a much longer event label that will test wrapping behavior : Mar Back to short : Apr ``` **What this does:** Tests how labels of different lengths render. Short labels are clean. Medium labels work fine. Very long labels will wrap or overflow depending on the renderer. **Rule of thumb:** Keep event labels under 50 characters. If you need more context, put it in a supporting document and keep the timeline label concise. --- ## Nesting Sections: What Works and What Doesn't Mermaid timelines do NOT support nested sections. You can't do: ``` section Phase 1 section Sub-phase 1a ``` This will either parse incorrectly or render as a section named "section Sub-phase 1a". If you need hierarchy, use a different diagram type: - For hierarchical breakdowns: use a **mindmap** - For task dependencies: use a **Gantt chart** - For process hierarchy: use a **flowchart** --- ## Complete Syntax Quick Reference | Element | Syntax | Example | |---------|--------|---------| | Diagram start | `timeline` | `timeline` | | Title | `title Text` | `title My Timeline` | | Section | `section Name` | `section Q1 2026` | | Event with period | `Label : Period` | `Launch : June 2026` | | Event without period | `Label` | `Feature built` | | Theme | `%%{init: {'theme': 'x'}}%%` | before `timeline` line | | Comment | `%% comment text` | `%% TODO: add events` | --- ## Common Parse Errors and Fixes **Error: "Diagram not rendered"** Usually means a typo in the `timeline` keyword, or the init directive is malformed. **Error: Events in wrong section** Check your indentation. Section events must be indented relative to the section keyword. **Diagram renders but missing events** A missing colon means the line was parsed as a multi-event item without a period anchor. Add `: period` to the event. **All events show same period** Every event in a section without its own colon inherits the last anchored period. Make sure each period group has exactly one `: period` marker. --- ## Related Timeline Resources - [Mermaid Timeline Instructions: Full Guide](/blog/mermaid-timeline-diagram) — beginner-friendly walkthrough - [10 Timeline Examples with Step-by-Step Code](/blog/mermaid-timeline-diagram) — real use cases - [Research Plan Timeline Examples](/blog/mermaid-timeline-diagram) — academic and UX research --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** Every syntax example on this page works in our editor. Test edge cases, experiment with themes, and export your finished timeline. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ## Additional Guide: Building a Research Plan with Mermaid Timeline: Real Examples A research plan without a timeline is just a list of intentions. Adding a Mermaid timeline turns it into a visual schedule that supervisors, collaborators, and stakeholders can scan in 10 seconds. This post shows how to build research timelines for different contexts: academic studies, UX research, market research, and literature reviews. All examples are ready to copy and use. ## Why Use Mermaid for Research Timelines? Most researchers use Excel Gantt charts or PowerPoint slides for timelines. Both work, but both require manual updates when plans shift. Mermaid timelines live in plain text — change a date, re-render, done. **Practical advantages:** - Embed directly in GitHub READMEs, Notion docs, or Confluence pages - Version-control your timeline alongside your code or notes - Share as markdown — no software required to view - Update in seconds vs. reformatting cells/slides For the underlying syntax, read the [complete Mermaid timeline instructions guide](/blog/mermaid-timeline-diagram). ## Example 1: Academic Research Plan (1-Year Study) ```mermaid timeline title Year 1 Academic Research Plan section Q1 (Jan-Mar) Background reading Gap analysis complete Research questions finalized : March section Q2 (Apr-Jun) Ethics board submission Ethics approval received Pilot study designed : June section Q3 (Jul-Sep) Pilot data collected (n=10) Pilot analysis done Main study protocol set : September section Q4 (Oct-Dec) Main data collection begins Interim analysis Year 1 report submitted : December ``` **What this does:** Maps a full year of academic research across four quarters. The Q structure aligns with how most universities report progress. Ethics approval is correctly placed in Q2 (before any data collection). The deliverable at the end of each quarter is what gets reviewed in supervision meetings. **How to adapt it:** Change the section labels to match your actual timeline. If your ethics board is slow, push Q2 back and compress Q3. The beauty of plain text is you can do this in 30 seconds. --- ## Example 2: UX Research Plan UX research moves faster than academic research. This plan covers a 6-week discovery sprint. ```mermaid timeline title UX Research — Discovery Sprint (6 Weeks) section Week 1-2 Stakeholder interviews (5 sessions) Research brief approved Screener survey live : Week 2 section Week 3-4 User interviews (10 participants) Contextual observation sessions Affinity mapping workshop : Week 4 section Week 5 Theme synthesis Journey map draft Insight statements written : Week 5 section Week 6 Final presentation prepared Readout to product team Research report delivered : Week 6 ``` **What this does:** Shows a 6-week UX research sprint from stakeholder interviews through final delivery. The progression — interviews → synthesis → insights → presentation — follows the standard double-diamond research process. Product managers and designers immediately recognize this structure. **Key detail:** Parallel activities within weeks are shown as multiple events in the same section. "User interviews (10 participants)" and "Contextual observation sessions" both happen in weeks 3-4, which this diagram makes clear. --- ## Example 3: Literature Review Timeline For PhD students and academic researchers, the literature review often takes longer than expected. This timeline forces clarity. ```mermaid timeline title Systematic Literature Review — 12 Weeks section Search Phase (Wk 1-3) Search terms defined Databases selected (5) Initial search run — 847 papers : Week 3 section Screening Phase (Wk 4-6) Title & abstract screening Full-text eligibility check Included papers confirmed — 62 : Week 6 section Extraction Phase (Wk 7-9) Data extraction template built Quality assessment complete All 62 papers extracted : Week 9 section Synthesis Phase (Wk 10-12) Thematic analysis Findings narrative written Literature review submitted : Week 12 ``` **What this does:** A PRISMA-style systematic literature review mapped to 12 weeks. The numbers (847 papers → 62 included) are placeholders you'd replace with your actual PRISMA flow numbers. Supervisors love seeing this level of process rigor in a single diagram. --- ## Example 4: Market Research Plan Businesses doing market research before a product launch typically need to cover primary and secondary research. Here's a 10-week plan: ```mermaid timeline title Market Research Plan — Product Launch Prep section Secondary Research (Wk 1-2) Industry report analysis Competitor matrix built TAM/SAM/SOM calculated : Week 2 section Survey Design (Wk 3-4) Survey questions written Panel vendor selected Survey live (n=500 target) : Week 4 section Primary Research (Wk 5-7) Survey data collected Focus groups (3 sessions) Interview transcripts coded : Week 7 section Analysis (Wk 8-9) Quantitative analysis done Qualitative themes identified Key personas drafted : Week 9 section Deliverables (Wk 10) Executive summary written Presentation slides built Board readout complete : Week 10 ``` **What this does:** Separates secondary research (desk research, reports) from primary research (surveys, focus groups), which is how market research actually gets structured. The board readout at week 10 is the real deliverable this whole plan is working toward. --- ## Example 5: Mixed-Methods Research Design For studies combining quantitative and qualitative data collection: ```mermaid timeline title Mixed-Methods Study — 18 Month Timeline section Phase 1: Quantitative (Month 1-6) Survey instrument validated Random sample recruited (n=200) Survey data collected Statistical analysis complete : Month 6 section Phase 2: Qualitative (Month 7-12) Interview guide developed Purposive sample recruited (n=25) Semi-structured interviews run Thematic analysis complete : Month 12 section Phase 3: Integration (Month 13-18) QUAN + QUAL findings merged Joint display created Meta-inferences written Thesis chapter submitted : Month 18 ``` **What this does:** Shows the sequential QUAN → QUAL → integration structure of a convergent mixed-methods design. The final "integration" phase — where quantitative and qualitative findings are merged — is where mixed-methods studies often get vague. Putting it explicitly in the timeline forces the researcher to plan for it. --- ## Tips for Research Timeline Diagrams **Be specific about deliverables.** "Analysis done" is vague. "All 62 papers extracted" tells you exactly what completion looks like. Concrete deliverables make it easier to know if you're on schedule. **Account for buffer.** Real research always hits delays: ethics board slowdowns, participant no-shows, data quality issues. Build a week of buffer into every major phase. **Version your timeline.** When plans change (and they will), keep the old version in a separate file. Supervisors appreciate seeing how your plan evolved — it shows adaptive thinking. **Link to your protocol.** If your timeline lives in a README or Notion page, link it to your actual research protocol document. The timeline is the overview; the protocol has the detail. --- ## See More Timeline Examples For more timeline patterns — sprints, content calendars, onboarding flows — see [10 Mermaid Timeline Examples with Step-by-Step Code](/blog/mermaid-timeline-diagram). For the full syntax reference, read [Mermaid Timeline Syntax: Every Element Explained](/blog/mermaid-timeline-diagram). --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** Paste any of the research timeline examples above and customize them for your project. Takes 5 minutes to go from blank page to presentation-ready diagram. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ### What is Mermaid.js? A Beginner's Introduction to Diagrams as Code URL: https://mermaideditor.lol/blog/what-is-mermaid-js Published: 2025-12-01 Updated: 2025-12-01 Description: Learn what Mermaid.js is, how it works, and why developers love creating diagrams from simple text. A complete beginner's guide to diagrams as code. ## What is Mermaid.js? Mermaid.js is a JavaScript-based diagramming and charting tool that turns simple text definitions into rich, visual diagrams. Instead of dragging boxes and arrows around in a GUI, you write a few lines of human-readable text, and Mermaid renders the diagram for you. Think of it as **Markdown, but for diagrams**. Just as Markdown lets you write formatted documents without a word processor, Mermaid lets you create flowcharts, sequence diagrams, Gantt charts, and more without a drawing tool. ### A Quick Example Here's how simple it is. This text: ``` graph TD A[Write Code] --> B[Commit] B --> C[Push to GitHub] C --> D[Deploy] ``` Produces a clean flowchart showing a basic deployment pipeline. No mouse dragging, no alignment headaches — just text. ## Why Developers Love Mermaid.js ### 1. Version Control Friendly Because diagrams are plain text, they live in your Git repository alongside your code. You can track changes, review diffs, and merge updates just like any other source file. Try doing that with a PNG exported from a drawing tool. ### 2. Speed of Creation Creating a diagram in Mermaid takes seconds, not minutes. Once you learn the syntax, you can sketch out architectures, flows, and relationships faster than you could open a GUI tool. The mental model stays in text, which is where developers already live. ### 3. Always Up to Date When diagrams live next to the code they describe, they're far more likely to stay current. A diagram in a README file gets updated in the same pull request that changes the architecture. Traditional diagrams in separate files or external tools tend to go stale quickly. ### 4. Platform Support Mermaid diagrams render natively in **GitHub**, **GitLab**, **Notion**, **Obsidian**, **Confluence** (via plugins), and many other platforms. You don't need a special viewer — the platforms render them inline. ### 5. No Account Required Unlike SaaS diagramming tools, Mermaid is open-source and runs in the browser. There's no sign-up, no subscription, no vendor lock-in. Your diagrams are portable text files. ## What Types of Diagrams Can You Create? Mermaid supports a wide variety of diagram types, each suited for different use cases: | Diagram Type | Best For | |---|---| | **Flowchart** | Process flows, decision trees, algorithms | | **Sequence Diagram** | API calls, service interactions, protocols | | **Gantt Chart** | Project timelines, sprint planning | | **Class Diagram** | UML modeling, object-oriented design | | **State Diagram** | State machines, workflow states | | **Entity Relationship** | Database schema, data modeling | | **Pie Chart** | Simple data distribution | | **Mind Map** | Brainstorming, topic organization | | **Git Graph** | Branch visualization | | **Timeline** | Historical events, roadmaps | Each diagram type has its own simple syntax, but they all follow the same pattern: a declaration line followed by relationships. ## Getting Started with Mermaid.js ### Option 1: Use a Live Editor The fastest way to try Mermaid is with an online editor. You type on the left, see the diagram on the right. No installation needed. ### Option 2: Add to Your Website Include Mermaid in any HTML page: ```html
graph LR
    A --> B --> C
``` ### Option 3: Use in Markdown On platforms like GitHub, simply wrap your diagram in a mermaid code fence: ``` ```mermaid graph TD A --> B ``` ``` GitHub will render it automatically — no plugins needed. ### Option 4: Install via npm For programmatic use in Node.js or build tools: ```bash npm install mermaid ``` ## Your First Flowchart Let's build a practical example — a user login flow: ``` graph TD Start([User visits site]) --> Check{Logged in?} Check -- Yes --> Dashboard[Show Dashboard] Check -- No --> Login[Show Login Form] Login --> Submit[User submits credentials] Submit --> Validate{Valid?} Validate -- Yes --> Dashboard Validate -- No --> Error[Show Error] Error --> Login ``` This creates a complete login flow diagram with decision points, loops, and clear labels. Notice how readable the source text is — even without rendering, you can understand the flow. ## Key Syntax Concepts **Nodes** are defined with text in brackets: - `A[Rectangle]` — standard box - `A(Rounded)` — rounded corners - `A{Diamond}` — decision/rhombus - `A([Stadium])` — stadium shape - `A([Circle])` — circle **Edges** connect nodes: - `A --> B` — arrow - `A --- B` — line without arrow - `A -->|label| B` — arrow with label - `A -.-> B` — dotted arrow - `A ==> B` — thick arrow **Direction** is set on the first line: - `graph TD` — top to bottom - `graph LR` — left to right - `graph BT` — bottom to top - `graph RL` — right to left ## Mermaid.js vs Traditional Tools How does Mermaid compare to tools like Draw.io, Lucidchart, or Visio? **Mermaid wins at:** speed, version control, documentation integration, automation, and cost (free). **Traditional tools win at:** pixel-perfect layouts, complex custom styling, non-technical users, and presentation-ready output. The sweet spot for Mermaid is **technical documentation** — README files, architecture docs, design documents, and wikis. For marketing materials or highly styled presentations, a GUI tool may be better. ## Common Use Cases 1. **Architecture diagrams** in project READMEs 2. **API flow documentation** with sequence diagrams 3. **Database schemas** with ER diagrams 4. **Sprint planning** with Gantt charts 5. **Decision trees** for business logic 6. **Onboarding docs** showing system overview 7. **State machines** for UI components or workflows ## Tips for Beginners - **Start simple.** Get a basic flowchart working, then explore other diagram types. - **Use a live editor** to see results instantly as you type. - **Read the official docs** at [mermaid.js.org](https://mermaid.js.org) for syntax details. - **Copy examples** and modify them — it's the fastest way to learn. - **Keep diagrams focused.** One diagram per concept. If it's getting complex, split it. ## Conclusion Mermaid.js bridges the gap between text-based documentation and visual communication. It's fast, free, version-controllable, and increasingly supported across the platforms developers already use. Whether you're documenting an API, planning a project, or modeling a database, Mermaid lets you create professional diagrams without leaving your text editor. [Try it now in our free Mermaid Live Editor →](/) ### How to Create a Flowchart with Mermaid.js — Complete Guide URL: https://mermaideditor.lol/blog/how-to-create-flowchart-mermaid Published: 2025-12-05 Updated: 2025-12-05 Description: Step-by-step guide to creating flowcharts with Mermaid.js. Learn node shapes, edge types, styling, subgraphs, and best practices with copy-paste examples. ## Introduction to Mermaid Flowcharts Flowcharts are the most popular diagram type in Mermaid.js, and for good reason. They're versatile enough to represent everything from simple processes to complex decision trees, and Mermaid makes them incredibly easy to create with just a few lines of text. In this guide, you'll learn every aspect of Mermaid flowcharts — from basic syntax to advanced features like subgraphs, styling, and interaction. ## Basic Flowchart Syntax Every Mermaid flowchart starts with a direction declaration: ``` graph TD A[Start] --> B[Process] B --> C[End] ``` The direction keyword controls layout: - **TD** or **TB** — Top to Bottom (default, most common) - **LR** — Left to Right (great for pipelines) - **BT** — Bottom to Top - **RL** — Right to Left You can also use `flowchart` instead of `graph` for the newer syntax with more features: ``` flowchart LR A[Start] --> B[Process] --> C[End] ``` ## Node Shapes Mermaid provides many node shapes to convey meaning visually: ``` flowchart TD A[Rectangle - Default] B(Rounded Rectangle) C([Stadium Shape]) D[[Subroutine]] E[(Database / Cylinder)] F((Circle)) G{Diamond / Decision} H{{"Hexagon"}} I>Asymmetric / Flag] J[/Parallelogram/] K[\Parallelogram Alt\] L[/Trapezoid\] M[\Trapezoid Alt/] ``` ### When to Use Each Shape - **Rectangle** (`[text]`): Standard process steps - **Rounded** (`(text)`): Start/end terminals - **Diamond** (`{text}`): Decision points (yes/no, true/false) - **Cylinder** (`[(text)]`): Databases or storage - **Circle** (`((text))`): Connectors or junction points - **Stadium** (`([text])`): Terminal events - **Parallelogram** (`[/text/]`): Input/output operations ## Edge Types — Connecting Nodes Edges (arrows and lines) are how you connect nodes. Mermaid offers many styles: ``` flowchart LR A -->|Arrow| B C ---|Line| D E -.->|Dotted arrow| F G ==>|Thick arrow| H I --o|Circle end| J K --x|Cross end| L ``` ### Edge Length You can control edge length by adding extra dashes: ``` flowchart TD A --> B A ----> C A -------> D ``` Longer edges push nodes further apart, which helps with layout. ### Labeled Edges Add labels to describe the relationship: ``` flowchart TD A{Is it raining?} A -->|Yes| B[Take umbrella] A -->|No| C[Enjoy the sun] ``` You can also use this syntax: `A -- "label text" --> B` ## Practical Example: CI/CD Pipeline Let's build a real-world flowchart — a CI/CD deployment pipeline: ``` flowchart LR A([Developer pushes code]) --> B[Run Linter] B --> C[Run Unit Tests] C --> D{Tests pass?} D -->|Yes| E[Build Docker Image] D -->|No| F[Notify Developer] F --> A E --> G[Push to Registry] G --> H{Environment?} H -->|Staging| I[Deploy to Staging] H -->|Production| J[Manual Approval] J --> K[Deploy to Production] I --> L[Run E2E Tests] L --> M{E2E pass?} M -->|Yes| J M -->|No| F ``` This single text block produces a complete CI/CD visualization that's easy to update when the process changes. ## Subgraphs — Grouping Related Nodes Subgraphs let you group nodes into labeled sections: ``` flowchart TB subgraph Frontend A[React App] --> B[API Client] end subgraph Backend C[Express Server] --> D[Business Logic] D --> E[(PostgreSQL)] end B --> C ``` ### Nested Subgraphs You can nest subgraphs for complex architectures: ``` flowchart TB subgraph Cloud["AWS Cloud"] subgraph VPC["VPC"] subgraph Public["Public Subnet"] ALB[Load Balancer] end subgraph Private["Private Subnet"] ECS[ECS Service] RDS[(RDS Database)] end end end User([User]) --> ALB --> ECS --> RDS ``` ### Subgraph Direction Each subgraph can have its own direction: ``` flowchart LR subgraph TOP direction TB A --> B end subgraph BOTTOM direction TB C --> D end TOP --> BOTTOM ``` ## Styling Your Flowcharts ### Inline Styles Apply CSS-like styles directly to nodes: ``` flowchart LR A[Critical]:::critical --> B[Normal] --> C[Success]:::success classDef critical fill:#ff6b6b,stroke:#c0392b,color:white classDef success fill:#51cf66,stroke:#2f9e44,color:white ``` ### Style by Node ID ``` flowchart TD A[Important Node] style A fill:#f9f,stroke:#333,stroke-width:4px ``` ### Common Style Patterns Here's a reusable set of class definitions: ``` flowchart TD A[Start]:::start --> B[Process]:::process --> C{Decision}:::decision C -->|Yes| D[Success]:::success C -->|No| E[Error]:::error classDef start fill:#667eea,stroke:#5a67d8,color:white classDef process fill:#f7fafc,stroke:#cbd5e0 classDef decision fill:#faf089,stroke:#d69e2e classDef success fill:#c6f6d5,stroke:#38a169 classDef error fill:#fed7d7,stroke:#e53e3e ``` ## Advanced Techniques ### Multiple Links from One Node ``` flowchart TD A[Router] --> B[Handler 1] A --> C[Handler 2] A --> D[Handler 3] B & C & D --> E[Response] ``` The `&` operator connects multiple nodes at once. ### Special Characters in Labels Use quotes for special characters: ``` flowchart LR A["Node with (parentheses)"] --> B["Contains {braces}"] B --> C["Has #quot;quotes#quot;"] ``` ### Comments Add comments with `%%`: ``` flowchart TD %% This is a comment A --> B %% Another comment B --> C ``` ## Best Practices for Flowcharts 1. **Choose direction wisely.** Use LR for processes/pipelines, TD for hierarchies and decision trees. 2. **Use meaningful node IDs.** Instead of `A`, `B`, `C`, try `start`, `validate`, `deploy`. It makes the source readable. 3. **Label your edges.** Decision diamonds should always have labeled outputs (Yes/No, True/False, Success/Error). 4. **Keep it focused.** A flowchart with more than 15-20 nodes becomes hard to read. Split complex flows into multiple diagrams. 5. **Use subgraphs** for logical grouping. They make large diagrams scannable. 6. **Apply consistent styling.** Define class definitions once and reuse them. Color-code by category (errors = red, success = green, etc.). 7. **Test incrementally.** Build your flowchart step by step, rendering after each addition. This makes it easy to catch syntax errors. ## Common Mistakes and Fixes **Problem:** Nodes not connecting properly. **Fix:** Make sure node IDs are consistent. `A` and `a` are different nodes. **Problem:** Text with special characters breaks rendering. **Fix:** Wrap text in double quotes: `A["My (special) text"]` **Problem:** Layout is messy with too many crossing lines. **Fix:** Rearrange node order in the source. Mermaid renders top-to-bottom in the order nodes appear. Also try changing direction (LR vs TD). **Problem:** Subgraph edges look wrong. **Fix:** Connect to specific nodes inside subgraphs, not the subgraph itself. ## Conclusion Mermaid flowcharts are powerful enough for real-world documentation yet simple enough to create in seconds. Start with basic nodes and arrows, then progressively add shapes, styles, and subgraphs as needed. The key advantage is maintainability — when your process changes, updating a few lines of text is infinitely easier than rearranging boxes in a drawing tool. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid Sequence Diagram Tutorial with Examples URL: https://mermaideditor.lol/blog/mermaid-sequence-diagram-tutorial Published: 2025-12-08 Updated: 2025-12-08 Description: Learn how to create sequence diagrams with Mermaid.js. Covers participants, messages, loops, alt blocks, notes, and activation with real-world examples. ## What Are Sequence Diagrams? Sequence diagrams show how different components or actors interact over time. They're perfect for documenting API calls, microservice communication, authentication flows, and any process where the **order of messages** matters. Mermaid makes sequence diagrams easy to write and maintain — no drawing tools needed. ## Basic Syntax ``` sequenceDiagram Alice->>Bob: Hello Bob, how are you? Bob-->>Alice: Great! ``` The key elements: - **Participants** are automatically created when first mentioned - **Solid arrow** (`->>`) = synchronous message - **Dashed arrow** (`-->>`) = response / async message - Messages are labeled after the colon ## Arrow Types Mermaid supports several arrow types for different message semantics: ``` sequenceDiagram A->>B: Solid line with arrowhead (sync call) B-->>A: Dotted line with arrowhead (response) A-)B: Solid line with open arrow (async) B--)A: Dotted line with open arrow (async response) A-xB: Solid line with cross (lost message) B--xA: Dotted line with cross ``` ## Defining Participants You can explicitly declare participants to control order and add aliases: ``` sequenceDiagram participant U as User participant F as Frontend participant A as API Server participant D as Database U->>F: Click "Login" F->>A: POST /auth/login A->>D: SELECT user WHERE email=? D-->>A: User record A-->>F: JWT token F-->>U: Redirect to dashboard ``` Use `actor` instead of `participant` to show a stick figure: ``` sequenceDiagram actor User participant API User->>API: Request API-->>User: Response ``` ## Activation Bars Activation bars show when a participant is actively processing: ``` sequenceDiagram Client->>+Server: HTTP Request Server->>+Database: Query Database-->>-Server: Results Server-->>-Client: HTTP Response ``` The `+` activates (starts the bar) and `-` deactivates (ends it). You can also use explicit syntax: ``` sequenceDiagram Client->>Server: Request activate Server Server->>Database: Query activate Database Database-->>Server: Results deactivate Database Server-->>Client: Response deactivate Server ``` ## Real-World Example: OAuth 2.0 Flow ``` sequenceDiagram actor User participant App as Client App participant Auth as Auth Server participant API as Resource Server User->>App: Click "Login with Google" App->>Auth: Redirect to /authorize Auth->>User: Show consent screen User->>Auth: Grant permission Auth-->>App: Authorization code App->>+Auth: Exchange code for token Auth-->>-App: Access token + Refresh token App->>+API: GET /user (Bearer token) API-->>-App: User profile data App-->>User: Show profile ``` ## Loops Show repeated interactions: ``` sequenceDiagram participant Client participant Server Client->>Server: Connect loop Every 30 seconds Client->>Server: Heartbeat ping Server-->>Client: Pong end Client->>Server: Disconnect ``` ## Alt / Else Blocks (Conditionals) Show branching logic: ``` sequenceDiagram participant User participant API participant DB User->>API: POST /login API->>DB: Check credentials alt Valid credentials DB-->>API: User found API-->>User: 200 OK + Token else Invalid credentials DB-->>API: Not found API-->>User: 401 Unauthorized end ``` ## Optional Blocks The `opt` block shows something that may or may not happen: ``` sequenceDiagram participant User participant Cart participant Payment User->>Cart: Add items User->>Cart: Checkout opt Has coupon User->>Cart: Apply coupon code Cart-->>User: Discount applied end Cart->>Payment: Process payment Payment-->>Cart: Confirmation Cart-->>User: Order complete ``` ## Parallel (Par) Blocks Show things happening simultaneously: ``` sequenceDiagram participant App participant UserSvc as User Service participant OrderSvc as Order Service participant NotifSvc as Notification Service App->>App: User places order par Parallel requests App->>UserSvc: Get user details App->>OrderSvc: Create order App->>NotifSvc: Send confirmation end UserSvc-->>App: User data OrderSvc-->>App: Order ID NotifSvc-->>App: Sent OK ``` ## Notes Add notes for extra context: ``` sequenceDiagram participant C as Client participant S as Server Note over C,S: TLS Handshake C->>S: ClientHello S-->>C: ServerHello + Certificate C->>S: Key Exchange Note over C,S: Encrypted connection established C->>S: GET /api/data Note right of S: Validate token, query DB S-->>C: 200 OK + JSON ``` Note positions: `Note left of`, `Note right of`, `Note over A,B` (spans multiple participants). ## Critical Regions Highlight critical sections: ``` sequenceDiagram participant App participant DB App->>DB: BEGIN TRANSACTION critical Database Transaction App->>DB: UPDATE accounts SET balance = balance - 100 WHERE id = 1 App->>DB: UPDATE accounts SET balance = balance + 100 WHERE id = 2 option Transaction fails DB-->>App: ROLLBACK end App->>DB: COMMIT DB-->>App: OK ``` ## Autonumber Automatically number each message for easy reference: ``` sequenceDiagram autonumber Alice->>Bob: Request Bob->>Charlie: Forward Charlie-->>Bob: Response Bob-->>Alice: Response ``` ## Real-World Example: Microservice Order Flow ``` sequenceDiagram autonumber actor Customer participant GW as API Gateway participant OS as Order Service participant IS as Inventory Service participant PS as Payment Service participant NS as Notification Service Customer->>+GW: POST /orders GW->>+OS: Create order OS->>+IS: Check stock IS-->>-OS: In stock OS->>+PS: Charge customer alt Payment success PS-->>-OS: Payment confirmed OS->>NS: Send confirmation email NS-->>OS: Queued OS-->>-GW: Order created (201) GW-->>-Customer: Order confirmation else Payment failed PS-->>OS: Payment declined OS->>IS: Release reservation OS-->>GW: Payment failed (402) GW-->>Customer: Error message end ``` ## Best Practices 1. **Declare participants explicitly** to control the order they appear left-to-right. 2. **Use aliases** for long service names — `participant PS as Payment Service`. 3. **Use activation bars** to show processing duration — it makes timing clear. 4. **Add autonumber** when you'll reference steps in documentation ("In step 3, the server validates..."). 5. **Use alt/else** for error handling flows — document both happy and sad paths. 6. **Keep it focused** — one sequence diagram per use case. Don't try to show every possible flow in one diagram. 7. **Add notes** for non-obvious details like "Token expires in 1 hour" or "Retries 3 times". ## Common Pitfalls - **Forgetting the closing `end`** for loop/alt/opt/par blocks — each needs a matching end. - **Too many participants** — more than 6-7 makes the diagram too wide. Group related services. - **Missing responses** — every request should ideally have a response shown, even if it's async. ## Conclusion Sequence diagrams are essential for documenting how systems communicate. Mermaid's text-based approach means your diagrams stay in sync with your code, live in your repo, and are easy to update. Start with the basic arrow syntax, then add loops, alt blocks, and activation as needed. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid Gantt Chart: Examples & Best Practices URL: https://mermaideditor.lol/blog/mermaid-gantt-chart-examples Published: 2025-12-12 Updated: 2025-12-12 Description: Create Gantt charts with Mermaid.js for project planning. Learn task syntax, dependencies, milestones, sections, and date formatting with practical examples. ## Introduction to Mermaid Gantt Charts Gantt charts visualize project schedules — showing tasks, durations, dependencies, and milestones on a timeline. While dedicated project management tools like Jira or MS Project offer interactive Gantt charts, Mermaid lets you create them as code that lives in your documentation. This is perfect for README files, design docs, and technical proposals where you need a visual timeline without the overhead of a separate tool. ## Basic Gantt Syntax ``` gantt title My Project Plan dateFormat YYYY-MM-DD section Planning Requirements gathering :a1, 2025-01-01, 7d System design :a2, after a1, 5d section Development Backend implementation :b1, after a2, 14d Frontend implementation :b2, after a2, 10d section Testing Integration testing :c1, after b1, 5d UAT :c2, after c1, 3d ``` ### Key Elements - **`title`** — Chart title - **`dateFormat`** — How dates are parsed (YYYY-MM-DD is standard) - **`section`** — Groups related tasks - **Tasks** follow the format: `Task name : id, start, duration` ## Task Definition Formats Tasks can be defined in several ways: ``` gantt dateFormat YYYY-MM-DD section Various Formats Fixed dates :t1, 2025-03-01, 2025-03-10 With duration :t2, 2025-03-01, 10d After dependency :t3, after t1, 5d No ID needed :2025-03-15, 7d ``` ### Duration Units - `d` — days (most common) - `h` — hours - `m` — minutes - `w` — weeks ## Task States Tasks can have different visual states: ``` gantt dateFormat YYYY-MM-DD section Task States Completed task :done, t1, 2025-01-01, 5d Active task :active, t2, after t1, 5d Future task :t3, after t2, 5d Critical task :crit, t4, after t3, 3d Critical & active :crit, active, t5, after t4, 3d ``` - **`done`** — Shown as completed (usually gray) - **`active`** — Currently in progress (highlighted) - **`crit`** — Critical path (usually red) - These can be combined: `crit, done` or `crit, active` ## Milestones Mark key dates with zero-duration milestones: ``` gantt dateFormat YYYY-MM-DD section Sprint 1 User stories :s1, 2025-01-06, 10d Sprint 1 review :milestone, m1, after s1, 0d section Sprint 2 Development :s2, after m1, 10d Sprint 2 review :milestone, m2, after s2, 0d section Release Release prep :r1, after m2, 3d Go live :milestone, m3, after r1, 0d ``` ## Dependencies Tasks can depend on one or more previous tasks: ``` gantt dateFormat YYYY-MM-DD section Backend API design :api, 2025-02-01, 5d Database schema :db, 2025-02-01, 3d API development :apidev, after api db, 10d section Frontend UI mockups :ui, 2025-02-01, 7d Frontend dev :fedev, after ui apidev, 10d section QA Testing :test, after fedev, 5d ``` Notice `after api db` — the task starts after BOTH `api` and `db` are complete. ## Practical Example: Software Release Plan ``` gantt title Q1 2025 Release Plan dateFormat YYYY-MM-DD axisFormat %b %d section Discovery User research :done, ur, 2025-01-06, 10d Competitive analysis :done, ca, 2025-01-06, 7d Requirements doc :done, rd, after ur ca, 5d Requirements sign-off :milestone, done, ms1, after rd, 0d section Design Architecture design :done, ad, after ms1, 7d UI/UX design :active, ux, after ms1, 10d Design review :milestone, ms2, after ad ux, 0d section Development Backend services :be, after ms2, 15d Frontend application :fe, after ms2, 15d API integration :int, after be, 5d section Quality Unit testing :ut, after be fe, 5d Integration testing :it, after int ut, 5d Performance testing :crit, pt, after it, 3d Security audit :crit, sa, after it, 3d section Release Staging deployment :stg, after pt sa, 2d UAT :uat, after stg, 5d Production deployment :milestone, crit, prod, after uat, 0d ``` ## Date Formatting ### Input Date Format Control how Mermaid parses your dates: ``` gantt dateFormat DD-MM-YYYY task1 :01-03-2025, 10d ``` Common formats: - `YYYY-MM-DD` — ISO standard (recommended) - `DD-MM-YYYY` — European - `MM-DD-YYYY` — US ### Axis Display Format Control how the timeline axis looks: ``` gantt dateFormat YYYY-MM-DD axisFormat %Y-%m-%d section Tasks Task 1 :2025-01-01, 30d ``` Common axis formats: - `%Y-%m-%d` — 2025-01-15 - `%b %d` — Jan 15 - `%d/%m` — 15/01 - `%B %Y` — January 2025 ## Excluding Dates Skip weekends or holidays: ``` gantt dateFormat YYYY-MM-DD excludes weekends section Development Task 1 :t1, 2025-03-03, 5d Task 2 :t2, after t1, 5d ``` With weekends excluded, a 5-day task truly means 5 business days. You can also exclude specific dates: ``` excludes weekends, 2025-12-25, 2025-12-26 ``` ## Sections as Swim Lanes Use sections to organize by team, phase, or component: ``` gantt title Cross-Team Project dateFormat YYYY-MM-DD section Team Alpha Feature A :a1, 2025-03-01, 14d Feature B :a2, after a1, 7d section Team Beta Feature C :b1, 2025-03-01, 10d Feature D :b2, after b1, 10d section Team Gamma Feature E :g1, 2025-03-08, 14d Integration :g2, after a2 b2 g1, 5d ``` ## Best Practices 1. **Use ISO date format** (`YYYY-MM-DD`) — it's unambiguous and sorts correctly. 2. **Give tasks meaningful IDs** — `api_design` is clearer than `a1` when reading dependencies. 3. **Mark the critical path** — use `crit` on tasks that directly impact the delivery date. 4. **Use milestones** for key dates — they provide clear visual checkpoints. 5. **Exclude weekends** with `excludes weekends` for realistic business-day planning. 6. **Keep sections logical** — group by team, phase, or component. Don't mix organizational patterns. 7. **Update the `done`/`active` states** as work progresses — this makes the chart a living document. 8. **Add `axisFormat`** to make the timeline readable. `%b %d` (Jan 15) is usually the best balance of information and space. ## Limitations - Mermaid Gantt charts are **read-only** — you can't drag tasks or interact with them. - Complex projects with hundreds of tasks are better served by dedicated PM tools. - Resource assignment and workload balancing aren't supported. - The layout engine may struggle with many overlapping dependencies. Mermaid Gantt charts shine for **documentation** — embedding a project timeline in a README, proposal, or design doc where the audience needs to understand the plan but doesn't need to interact with it. ## Conclusion Mermaid Gantt charts turn project timelines into maintainable code. They're perfect for technical documentation, sprint planning overviews, and release plans that live alongside your source code. Start simple with sections and tasks, then add dependencies, milestones, and critical path markers as your planning matures. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid Class Diagrams for UML — Developer Guide URL: https://mermaideditor.lol/blog/mermaid-class-diagram-uml Published: 2025-12-15 Updated: 2025-12-15 Description: Create UML class diagrams with Mermaid.js. Learn classes, attributes, methods, relationships, inheritance, interfaces, and design patterns with examples. ## What Are Class Diagrams? Class diagrams are the backbone of UML (Unified Modeling Language) and the most common diagram for modeling object-oriented systems. They show classes, their attributes and methods, and the relationships between them. Mermaid lets you create class diagrams from text, making them perfect for documenting codebases, planning architectures, and communicating designs in pull requests. ## Basic Class Syntax ``` classDiagram class Animal { +String name +int age +makeSound() void +move(distance) void } ``` ### Visibility Modifiers Mermaid follows UML conventions: - `+` Public - `-` Private - `#` Protected - `~` Package/Internal ``` classDiagram class User { +String username -String passwordHash #String email ~int loginAttempts +login(password) bool -hashPassword(raw) String #validateEmail() bool } ``` ## Relationships ### Inheritance (Generalization) ``` classDiagram Animal <|-- Dog Animal <|-- Cat Animal <|-- Bird class Animal { +String name +makeSound() void } class Dog { +fetch() void } class Cat { +purr() void } class Bird { +fly() void } ``` ### All Relationship Types ``` classDiagram classA <|-- classB : Inheritance classC *-- classD : Composition classE o-- classF : Aggregation classG --> classH : Association classI -- classJ : Link classK ..> classL : Dependency classM ..|> classN : Realization ``` **When to use each:** - **Inheritance** (`<|--`): "is a" — Dog is an Animal - **Composition** (`*--`): "owns, can't exist without" — Car owns Engine - **Aggregation** (`o--`): "has, can exist independently" — Department has Employees - **Association** (`-->`): "uses" — Order references Customer - **Dependency** (`..>`): "temporarily uses" — Service depends on Logger - **Realization** (`..|>`): "implements" — UserService implements IUserService ## Cardinality (Multiplicity) Show how many instances relate: ``` classDiagram Customer "1" --> "*" Order : places Order "1" --> "1..*" OrderItem : contains OrderItem "*" --> "1" Product : references ``` Common multiplicities: - `1` — exactly one - `0..1` — zero or one - `*` or `0..*` — zero or more - `1..*` — one or more ## Interfaces and Abstract Classes ``` classDiagram class IRepository { <> +findById(id) Entity +save(entity) void +delete(id) void } class AbstractRepository { <> #DataSource connection +findById(id) Entity #getConnection() DataSource } class UserRepository { +findById(id) User +findByEmail(email) User +save(user) void +delete(id) void } IRepository <|.. AbstractRepository AbstractRepository <|-- UserRepository ``` ### Annotations Use `<>` for stereotypes: ``` classDiagram class PaymentService { <> } class UserDTO { <> } class Colors { <> RED GREEN BLUE } ``` ## Practical Example: E-Commerce Domain Model ``` classDiagram class Customer { +String id +String name +String email +Address[] addresses +placeOrder(items) Order +getOrderHistory() Order[] } class Order { +String id +Date createdAt +OrderStatus status +Customer customer +OrderItem[] items +getTotal() Decimal +cancel() void } class OrderItem { +Product product +int quantity +Decimal unitPrice +getSubtotal() Decimal } class Product { +String id +String name +String description +Decimal price +int stockCount +isInStock() bool } class Address { +String street +String city +String state +String zipCode +String country } class OrderStatus { <> PENDING CONFIRMED SHIPPED DELIVERED CANCELLED } Customer "1" --> "*" Order : places Customer "1" --> "*" Address : has Order "1" --> "1..*" OrderItem : contains Order --> OrderStatus OrderItem "*" --> "1" Product : references ``` ## Design Pattern: Repository Pattern ``` classDiagram class IRepository~T~ { <> +findById(id) T +findAll() T[] +save(entity) T +delete(id) void } class UserRepository { -DataSource db +findById(id) User +findAll() User[] +save(user) User +delete(id) void +findByEmail(email) User } class ProductRepository { -DataSource db +findById(id) Product +findAll() Product[] +save(product) Product +delete(id) void +findByCategory(cat) Product[] } class UserService { -UserRepository userRepo +getUser(id) User +createUser(data) User +updateUser(id, data) User } IRepository~T~ <|.. UserRepository IRepository~T~ <|.. ProductRepository UserService --> UserRepository : uses ``` ## Generics Mermaid supports generic types with tilde syntax: ``` classDiagram class List~T~ { +add(item T) void +get(index int) T +size() int } class Map~K, V~ { +put(key K, value V) void +get(key K) V } ``` ## Namespaces Group related classes: ``` classDiagram namespace Domain { class User { +String name } class Order { +Date date } } namespace Infrastructure { class Database { +connect() void } class Cache { +get(key) String } } User --> Order Order ..> Database ``` ## Styling ``` classDiagram class Service { +process() void } class Entity { +String id } style Service fill:#e1f5fe,stroke:#0288d1 style Entity fill:#f3e5f5,stroke:#7b1fa2 ``` ## Best Practices 1. **Focus on the domain.** Don't diagram every utility class — show the important domain entities and their relationships. 2. **Use correct relationship types.** Composition vs. aggregation vs. association matters for communicating intent. 3. **Include cardinality** on associations — it clarifies the data model significantly. 4. **Show key methods only.** Skip getters/setters and boilerplate. Show the methods that define behavior. 5. **Use interfaces** to show contracts. This communicates the architecture's extension points. 6. **Group with namespaces** for large models. Separate domain, infrastructure, and application layers. 7. **Add annotations** (`<>`, `<>`, `<>`) to clarify the role of each class. 8. **Keep diagrams focused.** One diagram per bounded context or module. A single diagram with 30+ classes helps nobody. ## Conclusion Mermaid class diagrams bring UML into your codebase. They're ideal for documenting domain models, communicating design decisions in pull requests, and maintaining architecture docs that stay current. The text-based format means they're diffable, reviewable, and version-controlled — everything a developer needs. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid vs Draw.io vs Lucidchart: Honest Comparison (2026) URL: https://mermaideditor.lol/blog/mermaid-vs-drawio-vs-lucidchart Published: 2025-12-18 Updated: 2025-12-18 Description: Mermaid vs Draw.io vs Lucidchart compared — pricing, features, collaboration, version control. Find the right diagramming tool in 2 minutes. ## The Diagramming Landscape Developers and teams need diagrams for architecture docs, flowcharts, sequence diagrams, database schemas, and project planning. But with dozens of tools available, choosing the right one matters. This comparison focuses on three popular options that represent different approaches: - **Mermaid.js** — Diagrams as code (text-based) - **Draw.io (diagrams.net)** — Free GUI-based diagramming - **Lucidchart** — Premium collaborative diagramming platform ## Quick Comparison ### Mermaid.js **Approach:** Write text, get diagrams. **Price:** Free and open-source. **Best for:** Developers who want diagrams in docs, READMEs, and wikis. **Runs:** Browser, CLI, or embedded in platforms (GitHub, GitLab, Notion, etc.) ### Draw.io (diagrams.net) **Approach:** Drag-and-drop GUI in the browser. **Price:** Free (open-source). **Best for:** Teams that need flexible, visual diagram editing without paying for a SaaS tool. **Runs:** Browser, desktop app, or VS Code extension. ### Lucidchart **Approach:** Premium SaaS with real-time collaboration. **Price:** Free tier (3 documents), paid plans from $7.95/month. **Best for:** Cross-functional teams, enterprise environments, non-technical stakeholders. **Runs:** Browser-based SaaS. ## Feature Comparison ### Diagram Types **Mermaid** supports: flowcharts, sequence diagrams, Gantt charts, class diagrams, state diagrams, ER diagrams, pie charts, mind maps, git graphs, timelines, and more. New types are added regularly. **Draw.io** supports virtually any diagram type through its extensive shape libraries. Flowcharts, UML, network diagrams, floor plans, mockups — if you can draw it, Draw.io can handle it. **Lucidchart** has the broadest template library with hundreds of pre-built templates. It also supports data-linked diagrams that update automatically from external data sources. **Winner:** Draw.io and Lucidchart for variety. Mermaid for structured, code-based diagrams. ### Version Control **Mermaid** is the clear winner here. Diagrams are plain text, so they work perfectly with Git. You can diff changes, review in PRs, and track history like any source file. **Draw.io** saves as XML, which can be committed to Git. However, diffs are hard to read since XML changes don't map intuitively to visual changes. The VS Code extension helps by letting you edit .drawio files in your repo. **Lucidchart** has its own version history within the platform, but it's not Git-integrated. Exporting and committing is a manual process. **Winner:** Mermaid, by a wide margin. ### Collaboration **Mermaid** collaborates through your existing workflow — Git branches, pull requests, and code review. Multiple people can work on diagrams through normal merge processes. **Draw.io** supports real-time collaboration when using the web version. Multiple users can edit simultaneously. When using the file-based version (VS Code, desktop), collaboration is through your file sharing system. **Lucidchart** has the best real-time collaboration — multiple cursors, comments, @mentions, team folders, and fine-grained permissions. It's built for teams. **Winner:** Lucidchart for real-time collaboration. Mermaid for async/developer workflows. ### Learning Curve **Mermaid** requires learning its syntax, which takes an hour or two for basics. The payoff is speed — once learned, you create diagrams faster than any GUI. Non-technical users may find it intimidating. **Draw.io** is intuitive for anyone who's used a drawing tool. Drag shapes, connect them, add text. Very low barrier to entry. **Lucidchart** is polished and user-friendly, with guided templates and an intuitive interface. Slightly steeper learning curve than Draw.io due to more features. **Winner:** Draw.io for immediate usability. Mermaid for long-term speed. ### Platform Integration **Mermaid** renders natively in GitHub, GitLab, Notion, Obsidian, Docusaurus, MkDocs, Confluence (plugins), Slack (via links), and more. It's the most embeddable option. **Draw.io** integrates with Confluence, Jira, Google Drive, OneDrive, and has a VS Code extension. Files can be embedded in many platforms. **Lucidchart** integrates with Google Workspace, Microsoft 365, Confluence, Jira, Slack, and many enterprise tools. Deep integrations but requires a Lucidchart account. **Winner:** Mermaid for developer platforms. Lucidchart for enterprise/business platforms. ### Styling and Customization **Mermaid** offers themes and basic CSS-like styling. You can change colors, shapes, and fonts, but pixel-perfect control is limited. The auto-layout engine decides positioning. **Draw.io** gives you full control over every element — position, size, color, gradient, shadow, font, and more. You can create presentation-quality diagrams. **Lucidchart** offers the most polished styling with professional themes, brand kits, and pixel-perfect control. Diagrams look great out of the box. **Winner:** Lucidchart for polish. Draw.io for free pixel-perfect control. Mermaid accepts "good enough" layout. ### Export Options **Mermaid** exports to SVG and PNG. Through CLI tools, you can also generate PDF. **Draw.io** exports to PNG, SVG, PDF, JPEG, XML, HTML, and VSDX (Visio format). **Lucidchart** exports to PNG, PDF, SVG, CSV, Visio, and can publish interactive web links. **Winner:** Draw.io for format variety. All three cover the essentials. ## When to Use Each Tool ### Choose Mermaid When: - You're a **developer** documenting code or architecture - Diagrams need to live in **Git** alongside source code - You want diagrams in **README files** or documentation sites - **Speed** matters more than pixel-perfect styling - You need diagrams that are **easy to update** as code changes - Budget is **$0** and you don't want account lock-in - You're working with **technical audiences** who read code ### Choose Draw.io When: - You need **free** visual diagramming with full control - You're creating **network diagrams**, **floor plans**, or **mockups** that need precise positioning - Your team includes **non-technical members** who can't write code - You want to store diagram files **locally or in your repo** without a SaaS dependency - You need **Visio compatibility** without paying for Visio ### Choose Lucidchart When: - Your team needs **real-time collaboration** on diagrams - You're in an **enterprise environment** with compliance requirements - **Non-technical stakeholders** (PMs, executives) need to create and view diagrams - You want **templates** for every conceivable diagram type - You need **data-linked diagrams** that update from external sources - Budget allows $8-10/user/month ## The Hybrid Approach Many teams use multiple tools: - **Mermaid** for technical docs and README diagrams (version-controlled) - **Draw.io** for ad-hoc diagrams and complex visual layouts (free) - **Lucidchart** for executive presentations and cross-team collaboration (polished) There's no rule saying you must pick one. Use the right tool for each context. ## Cost Summary | Tool | Free Tier | Paid Plans | |---|---|---| | Mermaid.js | Fully free, open-source | N/A | | Draw.io | Fully free, open-source | Confluence/Jira plugins are paid | | Lucidchart | 3 documents, 60 shapes | $7.95+/user/month | ## Conclusion **Mermaid** is the best choice for developers who want maintainable, version-controlled diagrams embedded in their documentation. **Draw.io** is the best free visual diagramming tool for teams that need GUI flexibility. **Lucidchart** is the best premium option for collaborative, cross-functional teams. The "best" tool depends on your audience, workflow, and budget. For technical documentation that lives in code repositories, Mermaid is hard to beat. [Try creating diagrams as code in our free Mermaid Live Editor →](/) ### Add Mermaid Diagrams to GitHub README (2026 Guide) URL: https://mermaideditor.lol/blog/mermaid-in-github-readme Published: 2025-12-20 Updated: 2025-12-20 Description: Add beautiful Mermaid diagrams to your GitHub README in minutes. Copy-paste examples, rendering tips, and fixes for common issues. ## GitHub Supports Mermaid Natively Since February 2022, GitHub renders Mermaid diagrams directly in Markdown files. No plugins, no extensions, no build steps — just wrap your Mermaid code in a mermaid code fence and GitHub does the rest. This is a game-changer for documentation. Instead of maintaining separate image files that go stale, your diagrams live as text in your repo and render automatically. ## Basic Usage Add a Mermaid diagram to any Markdown file (.md) by using a code fence with the `mermaid` language identifier: ``` ```mermaid graph LR A[User] --> B[Frontend] B --> C[API] C --> D[(Database)] ``` ``` GitHub will render this as an interactive SVG diagram instead of showing the raw text. ### Where It Works Mermaid rendering works in: - **README.md** and all Markdown files - **Issues** and **Pull Requests** (description and comments) - **Discussions** - **Wikis** - **Gist files** (with .md extension) ## Common Diagram Types for READMEs ### Architecture Overview Every project should have an architecture diagram. Here's a typical web app: ``` ```mermaid graph TB subgraph Client React[React SPA] end subgraph Server API[Express API] Auth[Auth Middleware] Cache[Redis Cache] end subgraph Data DB[(PostgreSQL)] S3[S3 Storage] end React -->|HTTPS| API API --> Auth API --> Cache API --> DB API --> S3 ``` ``` ### Contribution Workflow Help contributors understand your process: ``` ```mermaid graph TD Fork([Fork the repo]) --> Clone[Clone locally] Clone --> Branch[Create feature branch] Branch --> Code[Make changes] Code --> Test[Run tests] Test --> Commit[Commit changes] Commit --> Push[Push to fork] Push --> PR[Open Pull Request] PR --> Review{Code review} Review -->|Approved| Merge[Merge to main] Review -->|Changes requested| Code ``` ``` ### API Flow Documentation Document your API interactions: ``` ```mermaid sequenceDiagram participant Client participant Gateway as API Gateway participant Auth as Auth Service participant User as User Service Client->>Gateway: POST /api/login Gateway->>Auth: Validate credentials Auth->>User: Get user profile User-->>Auth: User data Auth-->>Gateway: JWT token Gateway-->>Client: 200 OK + token ``` ``` ### Database Schema Document your data model: ``` ```mermaid erDiagram USER ||--o{ POST : creates USER ||--o{ COMMENT : writes POST ||--o{ COMMENT : has POST ||--o{ TAG : tagged_with USER { int id PK string username string email datetime created_at } POST { int id PK string title text content int author_id FK datetime published_at } ``` ``` ### Project Roadmap Show your planned timeline: ``` ```mermaid gantt title Project Roadmap 2025 dateFormat YYYY-MM-DD axisFormat %b section v1.0 Core features :done, 2025-01-01, 2025-03-01 Beta release :milestone, 2025-03-01, 0d section v1.1 User feedback :active, 2025-03-01, 2025-04-01 Bug fixes :2025-04-01, 2025-04-15 v1.1 release :milestone, 2025-04-15, 0d section v2.0 New features :2025-05-01, 2025-08-01 v2.0 release :milestone, 2025-08-01, 0d ``` ``` ## Best Practices for GitHub READMEs ### 1. Keep Diagrams Simple GitHub's Mermaid renderer handles most features, but very complex diagrams with 50+ nodes can be slow to render or hard to read on small screens. Split complex systems into multiple focused diagrams. ### 2. Test Before Pushing Use a live editor to verify your diagram renders correctly before committing. GitHub's renderer occasionally has quirks with newer Mermaid features since it may not run the latest version. ### 3. Provide Alt Text for Accessibility Unfortunately, GitHub doesn't support alt text for Mermaid diagrams directly. Consider adding a text description below complex diagrams: ```markdown ```mermaid graph LR A --> B --> C ``` *The diagram shows data flowing from component A through B to C.* ``` ### 4. Use Consistent Direction Pick a direction (TD or LR) and stick with it throughout your README. Mixing directions is visually jarring. ### 5. Place Diagrams Strategically - **Top of README:** Architecture overview - **After setup instructions:** How the system works - **In CONTRIBUTING.md:** Contribution workflow - **In docs/ folder:** Detailed technical docs ### 6. Fallback for Non-GitHub Platforms If your README might be viewed outside GitHub (npm, PyPI, etc.), platforms that don't support Mermaid will show the raw code. This is acceptable — the text is still human-readable. Alternatively, render to an image and include both: ```markdown ![Architecture](./docs/architecture.png)
Diagram source ```mermaid graph TD A --> B ```
``` ## Common Issues and Fixes ### Diagram Shows as Raw Text **Cause:** The code fence language must be exactly `mermaid` (lowercase). `Mermaid` or `MERMAID` won't work. ### Syntax Errors **Cause:** A typo in the Mermaid syntax. GitHub shows a red error message instead of the diagram. **Fix:** Test in a live editor first, then copy the working code. ### Special Characters Breaking the Diagram **Cause:** Characters like `<`, `>`, `&`, or quotes can interfere with rendering. **Fix:** Wrap labels in double quotes: `A["Label with (special) chars"]` ### Diagram Too Wide or Cramped **Cause:** GitHub's rendering area is fixed-width. **Fix:** Use `TD` (top-down) direction for wide diagrams, or split into smaller diagrams. ### Old Mermaid Features Not Working **Cause:** GitHub may run an older version of Mermaid than the latest release. **Fix:** Stick to well-established features. Check the Mermaid changelog if something doesn't render. ## Advanced: Mermaid in GitHub Actions You can automatically render Mermaid diagrams to images in CI: ```yaml name: Render Diagrams on: [push] jobs: render: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Render Mermaid uses: mermaid-js/mermaid-cli-action@v1 with: input: docs/diagrams/ output: docs/images/ ``` This generates PNG/SVG files from your .mmd files, useful for platforms that don't support Mermaid natively. ## Real README Example Here's how a well-structured README uses diagrams: ```markdown # My Awesome API A RESTful API for managing tasks. ## Architecture ```mermaid graph TB Client[Client Apps] --> LB[Load Balancer] LB --> API1[API Server 1] LB --> API2[API Server 2] API1 & API2 --> DB[(PostgreSQL)] API1 & API2 --> Cache[(Redis)] ``` ## Getting Started ... ## API Endpoints ### Authentication Flow ```mermaid sequenceDiagram Client->>API: POST /auth/login API-->>Client: JWT Token Client->>API: GET /tasks (Bearer token) API-->>Client: Task list ``` ``` ## Conclusion Mermaid in GitHub READMEs is one of the most impactful documentation improvements you can make. Diagrams that live as code stay current, are version-controlled, and render beautifully without any extra tooling. Start with an architecture diagram in your main README, then expand to contribution guides, API docs, and database schemas. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid State Diagrams — Complete Tutorial URL: https://mermaideditor.lol/blog/mermaid-state-diagram-guide Published: 2025-12-22 Updated: 2025-12-22 Description: Create state machine diagrams with Mermaid.js. Learn states, transitions, guards, composite states, forks, joins, and real-world examples. ## What Are State Diagrams? State diagrams (also called state machine diagrams or statecharts) show the different states an object or system can be in, and the transitions between those states. They're essential for modeling: - UI component states (loading, error, success) - Order lifecycles (pending, processing, shipped, delivered) - Authentication flows (logged out, logging in, authenticated, expired) - Game states (menu, playing, paused, game over) - Network connections (disconnected, connecting, connected) ## Basic Syntax ``` stateDiagram-v2 [*] --> Idle Idle --> Processing : Start Processing --> Completed : Success Processing --> Failed : Error Failed --> Idle : Retry Completed --> [*] ``` Key elements: - `[*]` — Start state (filled circle) or end state - `-->` — Transition arrow - Text after `:` is the trigger/event label - State names are automatically rendered as rounded rectangles ## Defining States ### Simple States ``` stateDiagram-v2 [*] --> Active Active --> Inactive : Deactivate Inactive --> Active : Activate Active --> [*] : Delete ``` ### States with Descriptions ``` stateDiagram-v2 state "Waiting for Payment" as WFP state "Order Confirmed" as OC state "Shipped to Customer" as STC [*] --> WFP WFP --> OC : Payment received OC --> STC : Dispatched STC --> [*] : Delivered ``` Use the `state "description" as alias` syntax for multi-word state names. ## Transitions ### Labeled Transitions ``` stateDiagram-v2 Idle --> Running : start() Running --> Idle : stop() Running --> Running : process(item) Running --> Error : exception thrown Error --> Idle : reset() ``` ### Self-Transitions A state can transition to itself (like "Running → Running" above). This represents an event that's handled without changing state. ## Composite (Nested) States Group related states inside a parent state: ``` stateDiagram-v2 [*] --> Active state Active { [*] --> Idle Idle --> Processing : Request Processing --> Idle : Complete Processing --> Error : Fail Error --> Idle : Retry } Active --> Suspended : Suspend Suspended --> Active : Resume Active --> [*] : Terminate ``` This shows that Active has its own internal states. The system can be suspended from any Active sub-state and resume back. ### Deeply Nested States ``` stateDiagram-v2 [*] --> App state App { [*] --> Auth state Auth { [*] --> LoggedOut LoggedOut --> LoggingIn : Enter credentials LoggingIn --> LoggedIn : Valid LoggingIn --> LoggedOut : Invalid } state LoggedIn { [*] --> Dashboard Dashboard --> Settings : Open settings Settings --> Dashboard : Back } Auth --> LoggedIn : Authenticated LoggedIn --> Auth : Logout } ``` ## Practical Example: Order Lifecycle ``` stateDiagram-v2 [*] --> Draft Draft --> Submitted : Customer places order Submitted --> PaymentPending : Order validated state PaymentPending { [*] --> AwaitingPayment AwaitingPayment --> ProcessingPayment : Payment initiated ProcessingPayment --> PaymentConfirmed : Success ProcessingPayment --> PaymentFailed : Declined PaymentFailed --> AwaitingPayment : Retry } PaymentPending --> Cancelled : Customer cancels PaymentConfirmed --> Fulfillment state Fulfillment { [*] --> Picking Picking --> Packing : Items collected Packing --> ReadyToShip : Packed } ReadyToShip --> Shipped : Carrier pickup Shipped --> Delivered : Delivery confirmed Delivered --> [*] Shipped --> ReturnRequested : Customer requests return ReturnRequested --> Returned : Return received Returned --> [*] Draft --> Cancelled : Customer cancels Submitted --> Cancelled : Validation failed Cancelled --> [*] ``` ## Choice (Decision) States Show conditional branching: ``` stateDiagram-v2 [*] --> RequestReceived RequestReceived --> ValidatingInput ValidatingInput --> CheckAuth state CheckAuth <> CheckAuth --> Authorized : Token valid CheckAuth --> Unauthorized : Token invalid Authorized --> Processing Processing --> Success Success --> [*] Unauthorized --> [*] ``` ## Fork and Join (Parallel States) Show concurrent execution: ``` stateDiagram-v2 [*] --> OrderPlaced state fork_state <> OrderPlaced --> fork_state fork_state --> SendEmail fork_state --> ProcessPayment fork_state --> UpdateInventory state join_state <> SendEmail --> join_state ProcessPayment --> join_state UpdateInventory --> join_state join_state --> OrderComplete OrderComplete --> [*] ``` This models three activities happening in parallel after an order is placed, with all three needing to complete before the order is marked complete. ## Notes Add context with notes: ``` stateDiagram-v2 [*] --> Active Active --> Inactive note right of Active System is processing requests in this state end note note left of Inactive All connections closed. Resources released. end note ``` ## Practical Example: UI Component States ``` stateDiagram-v2 [*] --> Initial state Initial { [*] --> Empty } Initial --> Loading : fetch() Loading --> Success : Data received Loading --> Error : Request failed state Success { [*] --> DisplayingData DisplayingData --> Refreshing : Pull to refresh Refreshing --> DisplayingData : Updated } state Error { [*] --> ShowError ShowError --> ShowError : Display message } Error --> Loading : Retry Success --> Loading : Refresh Success --> [*] : Unmount Error --> [*] : Unmount ``` ## Styling Apply CSS-like styles: ``` stateDiagram-v2 [*] --> Active Active --> Error Error --> Active classDef errorState fill:#ff6b6b,color:white,stroke:#c0392b classDef activeState fill:#51cf66,color:white,stroke:#2f9e44 class Error errorState class Active activeState ``` ## Direction Control layout direction: ``` stateDiagram-v2 direction LR [*] --> A --> B --> C --> [*] ``` Options: `TB` (top-bottom, default), `LR` (left-right), `BT`, `RL`. ## Best Practices 1. **Always include start and end states** (`[*]`) to clearly show entry and exit points. 2. **Name states as nouns or adjectives** — "Processing", "Active", "WaitingForApproval" — not verbs. 3. **Label transitions as events or actions** — "click submit", "payment received", "timeout" — verbs or events that trigger the change. 4. **Use composite states** to manage complexity. A 20-state flat diagram becomes readable when grouped into 3-4 composite states. 5. **Model error states explicitly.** Don't just show the happy path — document how the system handles failures and recovers. 6. **Use choice states** for conditional branching instead of multiple transitions from one state with the same trigger. 7. **Keep it focused.** One state diagram per concern. Don't try to model your entire application in a single diagram. ## Conclusion State diagrams are invaluable for documenting system behavior — especially for anything with a lifecycle (orders, sessions, UI states, workflows). Mermaid's text syntax makes them easy to create and maintain in your documentation. Start with the basic states and transitions, then add composite states and parallel execution as complexity grows. [Try it now in our free Mermaid Live Editor →](/) ### Entity Relationship Diagrams with Mermaid.js URL: https://mermaideditor.lol/blog/mermaid-er-diagram-database Published: 2025-12-25 Updated: 2025-12-25 Description: Design database schemas with Mermaid.js ER diagrams. Learn entities, attributes, relationships, cardinality, and best practices for data modeling. ## What Are ER Diagrams? Entity Relationship Diagrams (ERDs) visualize database structure — the tables (entities), their columns (attributes), and how they relate to each other. They're essential for: - Designing new databases - Documenting existing schemas - Communicating data models to team members - Planning migrations and refactors Mermaid's ER diagram syntax lets you create these diagrams as code, keeping your data documentation in sync with your actual schema. ## Basic Syntax ``` erDiagram CUSTOMER { int id PK string name string email } ORDER { int id PK date created_at int customer_id FK } CUSTOMER ||--o{ ORDER : places ``` Key elements: - **Entities** are defined with their name and attributes in curly braces - **Attributes** have a type, name, and optional constraint (PK, FK, UK) - **Relationships** use special notation for cardinality ## Attribute Syntax Each attribute follows the pattern: `type name constraint "comment"` ``` erDiagram USER { int id PK "Auto-increment primary key" string username UK "Unique username" string email UK "Unique email address" string password_hash "Bcrypt hashed" datetime created_at "Default: now()" datetime updated_at "Updated on change" boolean is_active "Default: true" } ``` ### Supported Constraints - **PK** — Primary Key - **FK** — Foreign Key - **UK** — Unique Key ## Relationship Cardinality Mermaid uses a notation combining two symbols — one for each end: ``` erDiagram A ||--|| B : "one to one" C ||--o{ D : "one to many" E }o--o{ F : "many to many" G ||--o| H : "one to zero or one" ``` ### Notation Guide Left/right symbols: - `||` — exactly one - `o|` — zero or one - `}|` — one or more - `}o` — zero or more The line style: - `--` — solid line (identifying relationship) - `..` — dashed line (non-identifying relationship) ### Common Patterns ``` erDiagram %% One-to-many (most common) AUTHOR ||--o{ BOOK : writes %% Many-to-many (via junction table) STUDENT }o--o{ COURSE : enrolls_in %% One-to-one USER ||--|| PROFILE : has %% Optional relationship EMPLOYEE ||--o| PARKING_SPOT : assigned ``` ## Practical Example: Blog Platform ``` erDiagram USER { int id PK string username UK string email UK string password_hash string avatar_url text bio datetime created_at } POST { int id PK string title string slug UK text content string status "draft|published|archived" int author_id FK datetime published_at datetime created_at datetime updated_at } COMMENT { int id PK text body int post_id FK int author_id FK int parent_id FK "For nested comments" datetime created_at } TAG { int id PK string name UK string slug UK } POST_TAG { int post_id FK int tag_id FK } LIKE { int id PK int user_id FK int post_id FK datetime created_at } USER ||--o{ POST : writes USER ||--o{ COMMENT : writes POST ||--o{ COMMENT : has COMMENT ||--o{ COMMENT : replies_to POST ||--o{ POST_TAG : has TAG ||--o{ POST_TAG : tagged USER ||--o{ LIKE : gives POST ||--o{ LIKE : receives ``` ## Practical Example: E-Commerce Database ``` erDiagram CUSTOMER { int id PK string first_name string last_name string email UK string phone datetime created_at } ADDRESS { int id PK int customer_id FK string street string city string state string zip_code string country boolean is_default } PRODUCT { int id PK string name string sku UK text description decimal price int stock_quantity int category_id FK boolean is_active } CATEGORY { int id PK string name int parent_id FK "Self-referencing for hierarchy" } ORDERS { int id PK int customer_id FK int shipping_address_id FK string status decimal subtotal decimal tax decimal total datetime ordered_at } ORDER_ITEM { int id PK int order_id FK int product_id FK int quantity decimal unit_price decimal subtotal } PAYMENT { int id PK int order_id FK string method string status decimal amount string transaction_id UK datetime paid_at } CUSTOMER ||--o{ ADDRESS : has CUSTOMER ||--o{ ORDERS : places ORDERS ||--|{ ORDER_ITEM : contains ORDERS ||--|| PAYMENT : paid_by ORDERS }o--|| ADDRESS : ships_to ORDER_ITEM }o--|| PRODUCT : references PRODUCT }o--|| CATEGORY : belongs_to CATEGORY ||--o{ CATEGORY : parent_of ``` ## Practical Example: SaaS Multi-Tenant ``` erDiagram TENANT { int id PK string name string subdomain UK string plan "free|pro|enterprise" datetime created_at } USER { int id PK int tenant_id FK string email string role "admin|member|viewer" datetime last_login } PROJECT { int id PK int tenant_id FK string name text description int owner_id FK } TASK { int id PK int project_id FK string title text description string status "todo|doing|done" int assignee_id FK date due_date } TENANT ||--o{ USER : has TENANT ||--o{ PROJECT : owns USER ||--o{ PROJECT : manages PROJECT ||--o{ TASK : contains USER ||--o{ TASK : assigned ``` ## Tips for Data Modeling with Mermaid ### 1. Start with Entities List your main entities first without attributes. Map out the relationships. Then add attributes. ### 2. Name Relationships Clearly The label after the colon describes the relationship: `CUSTOMER ||--o{ ORDER : places`. Use active verbs: "places", "contains", "belongs_to", "writes". ### 3. Show Junction Tables For many-to-many relationships, explicitly show the junction table: ``` erDiagram STUDENT }o--o{ COURSE : enrolls_in ``` Or with the junction table visible: ``` erDiagram STUDENT ||--o{ ENROLLMENT : has COURSE ||--o{ ENROLLMENT : has ENROLLMENT { int student_id FK int course_id FK date enrolled_at string grade } ``` The second approach is better when the junction table has its own attributes. ### 4. Include Data Types Always specify types — it makes the diagram useful for actual implementation: - `int`, `bigint` — IDs, counts - `string` or `varchar` — text fields - `text` — long content - `decimal` — money, precise numbers - `boolean` — flags - `datetime`, `date`, `timestamp` — temporal data - `json` or `jsonb` — flexible structured data ### 5. Mark Constraints Always mark PK, FK, and UK. These are the most important structural information in a schema diagram. ### 6. Use Comments for Business Rules Add comments in quotes to document constraints that aren't visible in the structure: ``` erDiagram ORDER { string status "Enum: pending|processing|shipped|delivered|cancelled" decimal total "Computed: sum of line items + tax" } ``` ## Common Mistakes - **Missing foreign keys** — Every relationship line should have a corresponding FK attribute. - **Wrong cardinality** — Think carefully: can a customer have zero orders? Then it's `||--o{` not `||--|{`. - **Tables without relationships** — If an entity has no relationships, it might not belong in the diagram, or you're missing a connection. - **Too many entities** — Focus on one bounded context. A diagram with 30+ tables is overwhelming. ## Conclusion Mermaid ER diagrams are perfect for documenting database schemas in your project repository. They render on GitHub, stay version-controlled, and are easy to update when your schema evolves. Start with the core entities and relationships, then progressively add attributes and constraints as your model matures. [Try it now in our free Mermaid Live Editor →](/) ### Creating Pie Charts with Mermaid.js URL: https://mermaideditor.lol/blog/mermaid-pie-chart-tutorial Published: 2025-12-28 Updated: 2025-12-28 Description: Learn how to create pie charts with Mermaid.js. Simple syntax, customization options, real-world examples, and when to use pie charts in documentation. ## Introduction to Mermaid Pie Charts Pie charts are the simplest diagram type in Mermaid — and sometimes simple is exactly what you need. They're perfect for showing proportions, distributions, and breakdowns in your documentation. While pie charts aren't suited for every data visualization scenario, they excel at showing how parts make up a whole — technology distributions, budget allocations, survey results, and more. ## Basic Syntax ``` pie title Technology Stack Distribution "JavaScript" : 45 "Python" : 25 "Go" : 15 "Rust" : 10 "Other" : 5 ``` That's it. Three elements: 1. `pie` keyword (optionally followed by `title Your Title`) 2. Labels in double quotes 3. Values after the colon Mermaid automatically calculates percentages and assigns colors. ## Practical Examples ### Project Language Breakdown ``` pie title Lines of Code by Language "TypeScript" : 42000 "CSS/SCSS" : 15000 "HTML" : 8000 "Python (scripts)" : 3000 "Shell" : 1500 ``` ### Sprint Task Distribution ``` pie title Sprint 14 Tasks by Category "Feature Development" : 12 "Bug Fixes" : 8 "Technical Debt" : 5 "Documentation" : 3 "DevOps" : 2 ``` ### Browser Market Share ``` pie title Browser Usage - Our App Analytics "Chrome" : 64 "Safari" : 19 "Firefox" : 8 "Edge" : 6 "Other" : 3 ``` ### Budget Allocation ``` pie title Engineering Budget Q1 2025 "Personnel" : 65 "Infrastructure (AWS)" : 18 "Tools & Licenses" : 8 "Training" : 5 "Misc" : 4 ``` ### Test Coverage ``` pie title Test Suite Composition "Unit Tests" : 340 "Integration Tests" : 85 "E2E Tests" : 42 "Performance Tests" : 15 ``` ### Error Distribution ``` pie title Production Errors Last 30 Days "4xx Client Errors" : 156 "5xx Server Errors" : 23 "Timeout Errors" : 45 "Network Errors" : 12 ``` ## Display Options ### Show Data (Values) By default, Mermaid shows percentages. You can add `showData` to display raw values: ``` pie showData title Response Time Buckets "< 100ms" : 450 "100-500ms" : 230 "500ms-1s" : 80 "> 1s" : 40 ``` ## When to Use Pie Charts ### Good Use Cases - **Showing composition** — What makes up a whole? (Language distribution, budget breakdown) - **Small number of categories** — 3 to 7 slices work best - **Documentation snapshots** — Quick visual in a README or report - **Comparing proportions** — When relative size matters more than exact values ### Avoid Pie Charts When - **Comparing precise values** — Bar charts are better for exact comparisons - **Many categories** — More than 7-8 slices become unreadable - **Showing trends over time** — Line charts are the right tool - **Similar-sized slices** — Humans are bad at comparing similar angles; use a bar chart instead ## Tips for Effective Pie Charts ### 1. Limit to 5-7 Slices If you have more categories, group the small ones into "Other": ``` pie title API Endpoints by Usage "GET /api/users" : 40 "POST /api/auth" : 25 "GET /api/products" : 20 "Other (15 endpoints)" : 15 ``` ### 2. Order by Size List items from largest to smallest for easier reading: ``` pie title Deploy Frequency by Service "API Gateway" : 45 "User Service" : 25 "Order Service" : 15 "Notification Service" : 10 "Analytics" : 5 ``` ### 3. Use Descriptive Labels Don't use abbreviations. Make labels self-explanatory: Bad: `"JS" : 45` Good: `"JavaScript/TypeScript" : 45` ### 4. Include Context in the Title The title should tell the reader what they're looking at and ideally when: Bad: `pie title Data` Good: `pie title Monthly Active Users by Platform (March 2025)` ### 5. Use Meaningful Numbers Use actual values when they matter, percentages when they don't: ``` pie showData title Incident Severity (Last Quarter) "Critical (P0)" : 3 "High (P1)" : 12 "Medium (P2)" : 45 "Low (P3)" : 89 ``` ## Pie Charts in README Files Pie charts work well in GitHub README files for quick project overviews: ```markdown ## Project Stats ```mermaid pie title Codebase Composition "Application Code" : 60 "Tests" : 25 "Configuration" : 10 "Documentation" : 5 ``` ``` They're also great in: - **Architecture Decision Records** — showing trade-off analysis - **Sprint retrospectives** — visualizing time spent - **Status reports** — quick visual summaries - **Incident postmortems** — error categorization ## Combining with Other Diagrams Pie charts work best alongside other diagram types. In a project README: 1. **Flowchart** for architecture overview 2. **Pie chart** for technology distribution 3. **Gantt chart** for roadmap 4. **Sequence diagram** for API flows Each diagram type serves a different purpose — use the right one for each piece of information. ## Limitations - **No custom colors** — Mermaid assigns colors automatically from its theme palette - **No legends** — Labels are shown directly on or near slices - **No donut charts** — Only standard pie charts - **No interactivity** — Static rendering only - **Limited formatting** — You can't control label position, font size, or slice explosion For advanced data visualization, consider dedicated charting libraries like Chart.js, D3.js, or Recharts. Mermaid pie charts are for **documentation**, not data dashboards. ## Conclusion Mermaid pie charts are the simplest way to add data visualization to your text-based documentation. They're perfect for quick overviews and composition breakdowns — just a keyword, some labels, and values. Keep them simple, limit slices to 5-7, and use them where proportional comparison adds value to your docs. [Try it now in our free Mermaid Live Editor →](/) ### Mermaid.js Cheat Sheet: Every Syntax You Need (2026) URL: https://mermaideditor.lol/blog/mermaid-syntax-cheat-sheet Published: 2026-01-02 Updated: 2026-01-02 Description: Every Mermaid.js syntax in one place — flowcharts, sequence, Gantt, class, ER, mindmap & more. Copy-paste ready. Bookmark this page. ## Flowcharts ### Direction ``` graph TD %% Top to Bottom graph LR %% Left to Right graph BT %% Bottom to Top graph RL %% Right to Left ``` Use `flowchart` instead of `graph` for extended features. ### Node Shapes ``` flowchart TD A[Rectangle] B(Rounded) C([Stadium]) D[[Subroutine]] E[(Cylinder/DB)] F((Circle)) G{Diamond} H{{Hexagon}} I>Flag/Asymmetric] J[/Parallelogram/] K[\Parallelogram Alt\] L[/Trapezoid\] ``` ### Edge Types ``` flowchart LR A --> B %% Arrow A --- B %% Line A -.-> B %% Dotted arrow A ==> B %% Thick arrow A --o B %% Circle end A --x B %% Cross end A -->|label| B %% Labeled arrow A -- "label" --- B %% Labeled line ``` ### Subgraphs ``` flowchart TB subgraph Group Name A --> B end subgraph Another["Custom Title"] direction LR C --> D end Group Name --> Another ``` ### Styling ``` flowchart TD A:::myClass --> B classDef myClass fill:#f9f,stroke:#333,color:black style B fill:#bbf,stroke:#33f ``` ## Sequence Diagrams ### Basics ``` sequenceDiagram participant A as Alice actor U as User A->>B: Solid arrow (sync) B-->>A: Dotted arrow (response) A-)B: Open arrow (async) A-xB: Cross (lost message) ``` ### Features ``` sequenceDiagram autonumber A->>+B: Request (activate) B-->>-A: Response (deactivate) Note over A,B: Spanning note Note right of B: Side note loop Every 5s A->>B: Ping end alt Success B-->>A: 200 OK else Failure B-->>A: 500 Error end opt Optional step A->>B: Maybe this happens end par Parallel A->>B: Request 1 and A->>C: Request 2 end critical Critical section A->>B: Important operation option Failure case B-->>A: Rollback end rect rgb(200, 220, 255) A->>B: Highlighted section end ``` ## Gantt Charts ``` gantt title Project Timeline dateFormat YYYY-MM-DD axisFormat %b %d excludes weekends section Phase 1 Task 1 :done, t1, 2025-01-01, 7d Task 2 :active, t2, after t1, 5d Milestone :milestone, m1, after t2, 0d section Phase 2 Task 3 :t3, after m1, 10d Critical task :crit, t4, after t3, 3d ``` ### Task States - `done` — completed - `active` — in progress - `crit` — critical path - Combine: `crit, done` or `crit, active` ## Class Diagrams ### Classes ``` classDiagram class ClassName { +String publicAttr -int privateAttr #bool protectedAttr ~float internalAttr +publicMethod() void -privateMethod(param) String +staticMethod()$ int +abstractMethod()* void } ``` ### Relationships ``` classDiagram A <|-- B : Inheritance C *-- D : Composition E o-- F : Aggregation G --> H : Association I ..> J : Dependency K ..|> L : Realization (implements) M "1" --> "*" N : Cardinality ``` ### Annotations ``` classDiagram class MyInterface { <> } class MyAbstract { <> } class MyEnum { <> VALUE_A VALUE_B } class MyService { <> } ``` ### Generics ``` classDiagram class List~T~ { +add(item T) void } ``` ## State Diagrams ``` stateDiagram-v2 direction LR [*] --> Active Active --> Inactive : disable Inactive --> Active : enable Active --> [*] : delete state Active { [*] --> Running Running --> Paused : pause Paused --> Running : resume } state check <> Active --> check check --> Error : if failed check --> Success : if passed state fork_state <> state join_state <> Active --> fork_state fork_state --> Task1 fork_state --> Task2 Task1 --> join_state Task2 --> join_state join_state --> Done note right of Active This is a note end note ``` ## ER Diagrams ``` erDiagram CUSTOMER { int id PK string name string email UK } ORDER { int id PK int customer_id FK date ordered_at } CUSTOMER ||--o{ ORDER : places ``` ### Cardinality - `||` — exactly one - `o|` — zero or one - `}|` — one or more - `}o` — zero or more ### Relationship lines - `--` — solid (identifying) - `..` — dashed (non-identifying) ## Pie Charts ``` pie title Distribution "Category A" : 40 "Category B" : 30 "Category C" : 20 "Other" : 10 ``` Add `showData` after `pie` to show raw values. ## Mind Maps ``` mindmap root((Central Topic)) Branch 1 Sub-topic A Sub-topic B Branch 2 Sub-topic C Detail 1 Detail 2 Branch 3 ``` ## Git Graphs ``` gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop commit ``` ## Timeline ``` timeline title History of Our Product 2020 : Founded : MVP launched 2021 : Series A funding : Reached 10k users 2022 : Series B : International expansion 2023 : 1M users milestone ``` ## Quadrant Charts ``` quadrantChart title Priority Matrix x-axis Low Effort --> High Effort y-axis Low Impact --> High Impact quadrant-1 Do First quadrant-2 Plan quadrant-3 Delegate quadrant-4 Eliminate Feature A: [0.8, 0.9] Feature B: [0.3, 0.7] Feature C: [0.6, 0.3] ``` ## Global Configuration ### Theme Set theme at the top of any diagram: ``` %%{init: {'theme': 'dark'}}%% graph TD A --> B ``` Available themes: `default`, `dark`, `forest`, `neutral`, `base`. ### Custom Theme Variables ``` %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#ff6b6b', 'edgeLabelBackground':'#ffffff'}}}%% graph TD A --> B ``` ## Tips - Use `%%` for comments in any diagram - Wrap special characters in quotes: `A["Text with (parens)"]` - Use `
` for line breaks in labels - HTML entities work: `#amp;`, `#lt;`, `#gt;` - Test diagrams in a live editor before committing ## Resources - [Official Mermaid Documentation](https://mermaid.js.org) - [Mermaid GitHub Repository](https://github.com/mermaid-js/mermaid) [Try all these diagrams in our free Mermaid Live Editor →](/) ### Mermaid.js Mindmap Tutorial: Syntax + Examples (2026) URL: https://mermaideditor.lol/blog/mermaid-mindmap-tutorial Published: 2026-01-05 Updated: 2026-05-26 Description: Learn Mermaid.js mindmap syntax in 5 minutes. Node shapes, icons, hierarchy — with copy-paste examples you can render instantly. ## What Are Mind Maps? Mind maps are radial diagrams that start from a central concept and branch outward into related topics, sub-topics, and details. They're excellent for: - **Brainstorming** — Exploring ideas non-linearly - **Planning** — Breaking down projects into components - **Learning** — Organizing knowledge hierarchically - **Documentation** — Showing topic relationships at a glance Mermaid's mind map syntax uses indentation to define the hierarchy, making it incredibly intuitive to write. ## Basic Syntax ``` mindmap root((Project Plan)) Design Wireframes Mockups User Testing Development Frontend Backend Database Launch Marketing Documentation Monitoring ``` The rules are simple: 1. Start with `mindmap` 2. The first indented item is the root node 3. Deeper indentation creates child branches 4. Siblings share the same indentation level ## Node Shapes Mind map nodes support different shapes: ``` mindmap root((Circle Root)) (Rounded Rectangle) [Square] Default shape ))Bang(( {{Hexagon}} ``` ### Shape Reference - **Default** — Just text, no brackets (rectangle with rounded corners) - **`[Square]`** — Square/rectangle - **`(Rounded)`** — Rounded rectangle - **`((Circle))`** — Circle - **`))Bang((`** — Explosion/bang shape - **`{{Hexagon}}`** — Hexagon ## Practical Example: Software Architecture ``` mindmap root((Web Application)) Frontend React SPA Components State Management Routing Styling Tailwind CSS Design System Build Vite TypeScript Backend API Server Express.js REST endpoints Authentication Database PostgreSQL Redis Cache Migrations Services Email Service File Storage Search Engine DevOps CI/CD GitHub Actions Automated Tests Infrastructure AWS Docker Kubernetes Monitoring Logging Alerting APM ``` ## Practical Example: Learning Path ``` mindmap root((Learn Web Development)) HTML & CSS Semantic HTML Flexbox & Grid Responsive Design Accessibility JavaScript ES6+ Syntax DOM Manipulation Async/Await Fetch API Frameworks React Components Hooks Next.js Vue Composition API Nuxt Backend Node.js Express Authentication Databases SQL Basics PostgreSQL MongoDB Tools Git & GitHub VS Code Chrome DevTools Terminal/CLI ``` ## Practical Example: Product Feature Map ``` mindmap root((SaaS Product)) Authentication Email/Password OAuth (Google, GitHub) Two-Factor Auth SSO (Enterprise) Dashboard Analytics Charts Activity Feed Quick Actions Notifications Projects Create/Edit Team Members Permissions Templates Billing Plans & Pricing Payment Processing Invoices Usage Tracking Settings Profile Team Management Integrations API Keys ``` ## Practical Example: Content Strategy ``` mindmap root((Content Strategy 2025)) Blog Technical Tutorials Case Studies Industry Analysis Product Updates Social Media Twitter/X Dev Tips Thread Content LinkedIn Company Updates Thought Leadership YouTube Video Tutorials Product Demos Email Weekly Newsletter Product Announcements Onboarding Sequence Community Discord Server GitHub Discussions Meetups & Webinars ``` ## Practical Example: Sprint Retrospective ``` mindmap root((Sprint 14 Retro)) What Went Well Shipped auth feature on time Good code review process Zero production incidents What Could Improve Standup meetings too long Unclear acceptance criteria Late design handoffs Action Items Timebox standups to 10 min Add AC template to tickets Include design in sprint planning ``` ## Tips for Effective Mind Maps ### 1. Keep the Hierarchy Shallow 3-4 levels deep is ideal. More than that becomes hard to read and defeats the purpose of a quick visual overview. ### 2. Use Concise Labels Mind map nodes should be short — 1-4 words each. If you need detailed descriptions, link to separate documents. ### 3. Balance the Branches Try to have 3-7 main branches from the root, each with a similar number of children. Lopsided mind maps are hard to scan. ### 4. Start with the Root Concept The root should be the core topic. Not a generic label like "Stuff" but a specific concept like "Q1 Marketing Plan" or "Microservice Architecture". ### 5. Use Shapes for Emphasis Use circles `((...))` for the root, and default shapes for branches. Reserve special shapes like bangs `))...((` for items that need attention. ### 6. Order Matters Put the most important branches first (left side in the rendered output). Mermaid renders branches in the order you write them. ## Mind Maps vs Flowcharts **Use a mind map when:** - You're brainstorming or exploring ideas - The hierarchy is the main relationship - You want a quick, non-linear overview - There's no specific flow or sequence **Use a flowchart when:** - There's a process with steps - Decision points exist - The sequence/order matters - Loops or feedback paths exist ## Mind Maps in Documentation Mind maps are particularly useful in: - **Project READMEs** — Feature overview at a glance - **Architecture docs** — System component breakdown - **Onboarding guides** — "Here's everything you need to know" - **Meeting notes** — Capturing discussion topics and decisions - **Planning docs** — Breaking down work into categories ### GitHub README Example ```markdown ## Feature Overview ```mermaid mindmap root((MyApp)) Auth Login Register OAuth Dashboard Charts Export API REST GraphQL ``` ``` ## Limitations - **No custom colors** — Mermaid assigns colors automatically by branch - **No icons** — Unlike GUI mind map tools, you can't add icons to nodes - **Limited layout control** — The auto-layout engine decides positioning - **No folding/expanding** — All branches are always visible - **Relatively new** — Mind maps were added in Mermaid v9.3, so older platforms may not support them For complex, interactive mind maps with custom styling, consider dedicated tools like XMind, MindMeister, or Coggle. Mermaid mind maps are best for **documentation** — quick, text-based, and version-controlled. ## Conclusion Mermaid mind maps let you create visual hierarchies with nothing but indented text. They're perfect for brainstorming, planning, and documentation where you need a quick overview of how topics relate. Start with the central concept, branch out 3-4 levels, and keep labels concise. [Try it now in our free Mermaid Live Editor →](/) ## Additional Guide: Mermaid Mindmap Examples: 12 Copy-Paste Diagrams [2026 Syntax Guide] ## Why Mermaid.js Mindmaps Are a Game-Changer Mindmaps are one of the most effective ways to visually organize ideas, and Mermaid.js brings them into the world of **code-based diagramming**. Unlike traditional drag-and-drop mindmap tools, Mermaid mindmaps are text-defined, version-controllable, and embeddable anywhere Markdown is supported — from GitHub READMEs to Notion pages to your team's documentation platform. If you've already explored the [basics of Mermaid mindmaps](/blog/mermaid-mindmap-tutorial), this guide takes you further with **advanced patterns, real-world examples, and practical use cases** that you can copy, adapt, and integrate into your workflow today. ## Quick Syntax Refresher Mermaid mindmaps use **indentation** to define hierarchy. Each level of indentation creates a child node: ``` mindmap root((Central Topic)) Branch A Sub-topic 1 Sub-topic 2 Branch B Sub-topic 3 ``` Node shapes add meaning: - `((text))` — Cloud shape (great for root nodes) - `(text)` — Rounded rectangle - `[text]` — Square - `)text(` — Bang shape (for emphasis) - `{{text}}` — Hexagon Now let's put this into practice. ## Use Case 1: Brainstorming Sessions Mindmaps shine brightest during brainstorming. Instead of messy whiteboard photos or lost sticky notes, capture ideas in a structured, shareable format. ### Example: Product Feature Brainstorming ``` mindmap root((Mobile App v2.0)) User Experience Onboarding Flow Interactive Tutorial Skip Option Progress Indicator Navigation Bottom Tab Bar Gesture Support Search Everywhere Performance Load Time Lazy Loading Image Compression CDN Integration Offline Mode Local Cache Sync Queue Conflict Resolution Monetization Freemium Model Free Tier Limits Premium Features Annual Discount In-App Purchases Cosmetic Items Power-Ups ``` This mindmap captures the output of an entire brainstorming session in a format that can live in your project repo. Anyone joining the team later can instantly understand the thinking behind your feature decisions. ### Why This Beats Traditional Tools - **Version history** — Git tracks every change to the brainstorm - **Async collaboration** — Team members add branches via pull requests - **No tool lock-in** — It's just text; move it anywhere - **Searchable** — `grep` through your brainstorms across projects ## Use Case 2: Project Planning & Breakdown Work breakdown structures (WBS) map naturally to mindmaps. Use them to decompose large projects into manageable pieces. ### Example: Website Redesign Project Plan ``` mindmap root((Website Redesign)) Discovery Stakeholder Interviews Analytics Review Competitor Analysis User Surveys Design Wireframes Homepage Product Pages Checkout Flow Visual Design Color Palette Typography Component Library Prototyping Interactive Mockups Usability Testing Development Frontend React Components Responsive Layout Accessibility Audit Backend API Migration Database Schema Authentication Infrastructure CI/CD Pipeline Staging Environment CDN Setup Launch QA Testing Content Migration SEO Redirects Monitoring Setup ``` Each branch becomes a workstream. Each leaf becomes a task. This single diagram replaces a lengthy project plan document and gives everyone an at-a-glance view of the full scope. ## Use Case 3: Note-Taking & Knowledge Organization Mermaid mindmaps are exceptional for organizing notes from meetings, courses, or research. The hierarchical structure forces you to identify relationships between concepts. ### Example: Meeting Notes — Quarterly Planning ``` mindmap root((Q2 Planning)) Goals Revenue +20% Launch 3 Features Reduce Churn 5% Key Decisions Hire 2 Engineers Pause Marketing Spend Partner with Agency X Risks Supply Chain Delays Competitor Launch Team Burnout Action Items )Draft Hiring JDs( )Update Roadmap( )Schedule Partner Call( ``` Notice the use of `)text(` (bang shape) for action items — this visually distinguishes them from informational nodes. Small formatting choices like this make mindmaps scannable. ## Use Case 4: Technical Architecture Overview Mindmaps offer a lighter alternative to formal architecture diagrams when you need a quick, high-level view. ### Example: Microservices Architecture ``` mindmap root((E-Commerce Platform)) API Gateway Rate Limiting Authentication Request Routing Services User Service Registration Profile Management OAuth Integration Product Service Catalog Search Index Recommendations Order Service Cart Management Payment Processing Order Tracking Data Layer PostgreSQL Users Orders Redis Session Cache Rate Limits Elasticsearch Product Search Infrastructure Kubernetes Datadog Monitoring AWS S3 Storage ``` This isn't a replacement for detailed system design documents, but it's perfect for onboarding new team members or presenting to non-technical stakeholders. ## Use Case 5: Decision Making & Analysis Structure your thinking around complex decisions using mindmaps. ### Example: Technology Stack Decision ``` mindmap root((Frontend Framework)) React Pros Huge Ecosystem Strong Job Market Meta Backing Cons Boilerplate Heavy Decision Fatigue Vue Pros Gentle Learning Curve Great Documentation Single File Components Cons Smaller Ecosystem Fewer Enterprise Adopters Svelte Pros No Virtual DOM Less Code Built-in Animations Cons Smaller Community Fewer Libraries Less Battle Tested ``` Laying out pros and cons visually helps teams move past analysis paralysis and make informed decisions. ## Best Practices for Effective Mindmaps 1. **Keep the root node focused.** A single, clear central topic produces better mindmaps than a vague one. "Q2 Marketing Plan" beats "Marketing Stuff." 2. **Limit depth to 4 levels.** Beyond four levels, mindmaps become hard to read. If a branch is too deep, consider breaking it into a separate mindmap. 3. **Use node shapes intentionally.** Reserve special shapes (clouds, bangs, hexagons) for specific meanings — don't use them randomly. 4. **Combine with other diagram types.** Start with a mindmap for brainstorming, then create flowcharts or sequence diagrams for the detailed processes you identify. 5. **Store mindmaps alongside code.** Keep them in `docs/` folders in your repos so they stay current with the codebase. 6. **Review and prune regularly.** Mindmaps should evolve. Remove completed items, add new branches, and keep them as living documents. ## Mermaid Mindmap Limitations to Know - **No cross-links** — You can't connect nodes across branches (use flowcharts for that) - **No icons on all renderers** — Icon support (`::icon()`) varies by platform - **Fixed layout** — You can't control node positioning; Mermaid handles layout automatically - **No color per node** — Styling is applied at the branch level, not individual nodes - **Large mindmaps get crowded** — Keep them focused; split large topics into multiple diagrams ## Conclusion Mermaid.js mindmaps bring the power of visual thinking into your text-based workflow. Whether you're brainstorming features, planning projects, organizing meeting notes, or evaluating technology decisions, mindmaps provide a fast, versionable, and shareable way to structure your thoughts. The key is matching the use case to the tool: use mindmaps for **hierarchical exploration** and switch to flowcharts, sequence diagrams, or Gantt charts when you need **process flows or timelines**. [Try building your own mindmap in our free Mermaid editor →](/) ## Additional Guide: Mermaid Mindmap Examples: 15 Real Use Cases with Code Mindmaps are underused in technical documentation. Most people reach for flowcharts when a mindmap would actually communicate the structure better. These 15 examples cover the real use cases where Mermaid mindmaps shine — all with copy-paste code. For the complete syntax reference, see the [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial). ## 1. Project Planning Overview ```mermaid mindmap root((Project Alpha)) Scope Feature list defined Out-of-scope documented Team Frontend: 2 devs Backend: 2 devs Design: 1 designer Timeline Q1: Discovery Q2: Build Q3: Launch Risks Key person dependency Third-party API reliability ``` **What this does:** A project overview mindmap with four branches: Scope, Team, Timeline, Risks. Good for project kick-off meetings — paste this into a presentation or Notion page and it renders instantly. --- ## 2. Software Architecture Overview ```mermaid mindmap root((System Architecture)) Frontend React SPA Mobile app Admin dashboard Backend REST API GraphQL layer Background jobs Data PostgreSQL Redis cache S3 file storage Infrastructure AWS ECS CloudFront CDN Route53 DNS ``` **What this does:** A high-level architecture map showing four layers of a system. Useful for onboarding new engineers or explaining the system to non-technical stakeholders. Faster to create and update than an architecture diagram. --- ## 3. Learning Curriculum ```mermaid mindmap root((Web Dev Curriculum)) Foundations HTML semantics CSS layouts Git basics Frontend JavaScript ES6+ features DOM manipulation React Components Hooks State management Backend Node.js REST APIs Databases Deployment Docker CI/CD Cloud platforms ``` **What this does:** A 4-level deep curriculum map. The React branch goes 3 levels deep (Frontend → React → subtopics). This is the maximum depth you'd want in a readable mindmap. Instructors use this as a course outline overview. --- ## 4. Business Strategy Map ```mermaid mindmap root((2026 Strategy)) Revenue Growth Upsell to Pro tier New market entry Enterprise deals Product Mobile app launch API marketplace Integrations Marketing SEO content engine Paid acquisition Partnerships Team Hire 5 engineers Hire Head of Sales Advisory board ``` **What this does:** A strategy map that a CEO or founder could build in a board meeting. Four pillars — Revenue, Product, Marketing, Team — each with 3 strategic initiatives. Much faster to update than a strategy slide deck. --- ## 5. Technical Debt Map ```mermaid mindmap root((Tech Debt)) Critical Auth system rewrite Database migration High Priority Test coverage below 40% Outdated dependencies Medium Priority Inconsistent API responses Missing error handling Low Priority Old README files Console.log statements ``` **What this does:** A tech debt categorization mindmap. Instead of a spreadsheet, this gives an instant visual of the debt landscape. Engineering managers use this in quarterly planning to decide what to tackle and when. --- ## 6. Competitive Analysis ```mermaid mindmap root((Competitor Map)) Direct Competitors Competitor A Strong: UI Weak: Pricing Competitor B Strong: Integrations Weak: Support Indirect Competitors Notion Draw.io Our Advantages Mermaid-native Zero friction Free tier Market Gaps Mobile editing Team collaboration Template library ``` **What this does:** A competitive landscape mindmap. Direct competitors get sub-branches for strengths and weaknesses. Indirect competitors, our advantages, and market gaps are also captured. Good for product strategy sessions. --- ## 7. Meeting Agenda ```mermaid mindmap root((Weekly Sync)) Updates Engineering Product Design Blockers Active blockers Needs decision Decisions Needed Budget approval Launch date Action Items Owners identified Deadlines set ``` **What this does:** A meeting agenda as a mindmap. Works better than a bullet list for recurring meetings because the visual structure makes it easy to see at a glance what section you're in. Paste into a shared Notion doc before the meeting. --- ## 8. SaaS Pricing Model ```mermaid mindmap root((Pricing Tiers)) Free 5 diagrams Export PNG No team features Starter $9/mo 50 diagrams Export SVG Shareable links Pro $29/mo Unlimited diagrams All export formats Team workspace Priority support Enterprise Custom limits SSO SLA guarantee Dedicated support ``` **What this does:** A pricing tier mindmap. Good for planning a SaaS pricing structure or explaining it to investors/advisors. Each tier branch has its feature list as leaf nodes. --- ## 9. Research Question Breakdown ```mermaid mindmap root((Research Question)) What we know Previous studies Industry reports Internal data What we don't know User motivations Long-term behavior Edge case scenarios Research Methods Surveys Interviews Usage analytics Expected Outputs Insight report Journey map Recommendations ``` **What this does:** Frames a research question from four angles — what's known, what's unknown, methods, and outputs. Researchers use this to structure proposals and explain their study design to non-research stakeholders. --- ## 10. API Documentation Map ```mermaid mindmap root((Payments API)) Authentication API keys OAuth 2.0 Webhooks Endpoints POST /charges GET /charges/{id} POST /refunds GET /customers Error Handling 4xx client errors 5xx server errors Retry logic SDKs JavaScript Python Ruby PHP ``` **What this does:** An API documentation structure map. Before writing the full API docs, build this mindmap to ensure all sections are covered. Also useful as a navigation index at the top of a docs page. --- ## 11. Personal Knowledge Management ```mermaid mindmap root((My Knowledge Base)) Engineering System design patterns Code review notes Useful libraries Business Product frameworks Growth tactics Books read Side Projects Ideas backlog Active projects Completed work Learning Queue Courses in progress Books to read Videos saved ``` **What this does:** A personal knowledge base structure. If you use Notion, Obsidian, or Logseq for notes, this mindmap can represent your entire folder/tag structure. Build this first, then create the actual notes. --- ## 12. Content Strategy Map ```mermaid mindmap root((Content Strategy)) Audience Developers Product managers Technical writers Content Types Blog posts Video tutorials Newsletter Twitter threads Topics Diagram how-tos Use case examples Tool comparisons Distribution SEO organic Email subscribers Social sharing Dev community ``` **What this does:** A content strategy overview for a technical blog. The four branches — audience, content types, topics, distribution — are the pillars of any content strategy. This maps out the whole strategy in one view. --- ## 13. Bug Report Classification ```mermaid mindmap root((Bug Tracker)) Critical P0 Data loss Security vulnerability Payment failure High P1 Core feature broken Auth issues Performance < 1s Medium P2 UI glitches Edge case failures Slow queries Low P3 Cosmetic issues Minor UX friction Outdated docs ``` **What this does:** A bug priority classification system as a mindmap. Engineering teams use this to align on what P0/P1/P2/P3 means before sprint planning. Consistent definitions reduce debate over priorities. --- ## 14. Hiring Plan ```mermaid mindmap root((Hiring Plan Q3)) Engineering Senior Backend Dev Must: Node.js, PostgreSQL Nice: Kubernetes Frontend Dev Must: React, TypeScript Product Product Manager Must: B2B SaaS exp Nice: Data-driven background Marketing Content Writer Must: Technical writing SEO experience ``` **What this does:** A structured hiring plan. Each role branch shows requirements split into "Must have" and "Nice to have". Much clearer than a spreadsheet when reviewing with leadership. --- ## 15. Post-Mortem Analysis ```mermaid mindmap root((Incident Post-Mortem)) Timeline Detection Response Resolution Root Causes Primary cause Contributing factors Impact Users affected Revenue impact SLA breach Action Items Immediate fixes Process improvements Monitoring additions What Went Well Fast detection Clear comms Team collaboration ``` **What this does:** A post-mortem structure mindmap. After any significant incident, this ensures you cover all five post-mortem categories. The "What Went Well" branch is important — post-mortems should reinforce good practices, not just catalog failures. --- ## Which Examples Are Most Useful? The most immediately practical examples by role: - **Engineers:** Examples 2 (architecture), 5 (tech debt), 10 (API docs), 15 (post-mortem) - **Product managers:** Examples 1 (project planning), 4 (strategy), 6 (competitive), 8 (pricing) - **Content teams:** Examples 12 (content strategy), 7 (meeting agenda) - **Researchers:** Examples 9 (research question), 11 (knowledge base) --- **Try these live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** All 15 examples above work directly in the editor. Pick one relevant to your work and customize it in 5 minutes. --- *Related: [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial) · [Mermaid Cheat Sheet](/cheat-sheet) · [Templates](/templates) · [Home](/)* ## Additional Guide: Mermaid Mindmap Syntax Cheat Sheet (2026 Edition) Mindmaps in Mermaid are fast to write and render beautifully. This cheat sheet covers the complete syntax — node shapes, nesting, icons, classes, and styling — so you can look up exactly what you need without wading through the official docs. Bookmark this page. You'll use it every time you build a mindmap. ## The Core Structure Every Mermaid mindmap starts with `mindmap` and a root node. Everything else branches off from there. ```mermaid mindmap root((Central Topic)) Branch 1 Sub-item A Sub-item B Branch 2 Sub-item C Sub-item D Branch 3 Sub-item E ``` **What this does:** Creates a basic mindmap with one root and three branches, each with child nodes. Indentation defines the hierarchy — deeper indent = child node. This is the skeleton every mindmap starts from. **Key rule:** Root node is always the first item after `mindmap`. It can use any shape syntax (see below). Everything else is positioned by indentation level. --- ## Node Shapes Quick Reference This is the part most people don't know. Mermaid mindmaps support 6 different node shapes: | Shape | Syntax | Renders As | |-------|--------|------------| | Default | `Node text` | Rounded rectangle | | Circle | `((Node text))` | Circle | | Bang | `)Node text(` | Explosion/burst | | Cloud | `)Node text)` | Cloud shape | | Hexagon | `{{Node text}}` | Hexagon | | Square | `[Node text]` | Square | Here's all of them in one diagram: ```mermaid mindmap root((Project Planning)) [Requirements] Define scope Stakeholder input ((Research)) Competitor audit User interviews {{Technical}} Architecture Stack choice )Risks( Timeline slippage Budget overrun ``` **What this does:** Shows four different node shapes in a single mindmap. Root is a circle `(())`, "Requirements" is a square `[]`, "Research" is a circle `(())`, "Technical" is a hexagon `{{}}`, and "Risks" uses the bang/burst shape `)text(`. The shape helps categorize node types visually. --- ## Nesting: How Deep Can You Go? Mermaid supports unlimited nesting depth. In practice, 3-4 levels is readable. Beyond that, the diagram gets cramped. ```mermaid mindmap root((Learning Plan)) Frontend HTML Semantic tags Forms Accessibility CSS Flexbox Grid Animations JavaScript ES6+ syntax Async/await DOM manipulation Backend Node.js Express Middleware Databases SQL NoSQL ``` **What this does:** Shows a 4-level deep mindmap (root → category → topic → subtopic). The learning plan covers Frontend and Backend, each branching into technologies and their sub-skills. This is about the maximum useful depth before labels start overlapping. --- ## Icons (FontAwesome Support) You can add FontAwesome icons to nodes using `::icon(fa fa-iconname)` syntax: ```mermaid mindmap root((Tech Stack)) ::icon(fa fa-server) Frontend ::icon(fa fa-code) React Vue Backend ::icon(fa fa-database) Node.js Python DevOps ::icon(fa fa-cloud) Docker Kubernetes Mobile ::icon(fa fa-mobile) iOS Android ``` **What this does:** Adds icons to branch nodes. The `::icon()` line goes *below* the node it belongs to, indented one level. FontAwesome 5 class names work (fa, fas, fab). Note: icon rendering depends on your viewer — it works in mermaideditor.lol but may not show in all markdown renderers. --- ## Classes: Custom Styling Classes let you apply CSS styling to specific nodes. Define the class with `classDef`, apply it with `:::classname`: ```mermaid mindmap root((Goals 2026)) Revenue:::urgent Hit $10K MRR Launch paid tier Product:::inprogress Mobile app API v2 Marketing:::planned SEO content Paid ads Team:::planned Hire designer Hire dev classDef urgent fill:#ff4444,color:#fff,font-weight:bold classDef inprogress fill:#ff9900,color:#fff classDef planned fill:#4CAF50,color:#fff ``` **What this does:** Applies color-coded styles to branches based on priority/status. `urgent` gets red, `inprogress` gets orange, `planned` gets green. This turns a plain mindmap into a status dashboard. The `classDef` block goes at the bottom of the diagram. **Note:** Class syntax in mindmaps uses triple-colon `:::` (not double `::` like in flowcharts). Easy to mix up. --- ## Complete Syntax Summary Here's everything in one reference diagram: ```mermaid mindmap root((Mermaid Mindmap Syntax)) Node Types Default text [Square brackets] ((Double parens = circle)) {{Hexagon}} )Bang shape( Nesting Level 1 Level 2 Level 3 Level 4 Features ::icon(fa fa-star) Icons with fa classes Classes with triple colon Unlimited depth Tips Keep labels short Max 4 levels deep Use shapes for categories Icons for visual scanning ``` **What this does:** A self-referential mindmap that documents its own syntax. Good for sharing with teammates who are new to Mermaid. --- ## Common Mistakes to Avoid **Wrong indentation:** Mermaid is strict about consistent indentation. Mix tabs and spaces and the diagram will break or render weirdly. Stick to spaces (2 or 4, consistent throughout). **Root node not on the first line:** The root must be the first node after `mindmap`. Any blank lines or comments before it can cause parse errors. **Wrong class syntax:** Flowchart classes use `:::` or `:::` but mindmaps specifically need `:::`. Double-check this if styling doesn't apply. **Too many levels:** Past level 4, most renderers start wrapping or overlapping labels. If your content needs more depth, split into multiple diagrams. **Icon names wrong:** FontAwesome 4 icons (just `fa-icon-name`) and FA5 icons (`fas fa-icon-name`) have different prefixes. Check [fontawesome.com](https://fontawesome.com) if an icon isn't showing. --- ## Combining Mindmaps with Other Diagram Types Mindmaps are great for structure and brainstorming, but they don't replace other diagram types. Here's when to switch: **Use a mindmap when:** - You need to show hierarchy or categories at a glance - You're brainstorming and don't know the exact structure yet - Your audience needs a quick mental model, not a process **Switch to a flowchart when:** - You need arrows showing direction or flow between items - There are decision points (yes/no branches) - The order of steps matters **Switch to a timeline when:** - Your branches represent time periods or phases - You want to show progress over time - See the [Mermaid Timeline Instructions guide](/blog/mermaid-timeline-diagram) A common pattern: use a mindmap to explore and structure ideas, then turn the structured branches into a flowchart or timeline for execution planning. ## Real-World Workflow: From Blank to Rendered Mindmap Here's the typical flow when building a mindmap from scratch: **Step 1:** Open [mermaideditor.lol](https://mermaideditor.lol) in your browser. **Step 2:** Type `mindmap` and define your root — usually the central topic: ``` mindmap root((Your Topic)) ``` **Step 3:** Add your main branches. Don't overthink — just braindump: ``` mindmap root((Your Topic)) Branch 1 Branch 2 Branch 3 ``` **Step 4:** Expand each branch with sub-nodes. Add shapes, icons, or classes as needed. **Step 5:** Clean up — remove redundant items, merge overlapping branches, and check that the depth doesn't exceed 4 levels. **Step 6:** Export SVG or copy the code into your docs. Most mindmaps take 5-10 minutes from blank to finished. That's the power of text-based diagramming — no drag-and-drop, no alignment issues. ## More Mindmap Resources Want to see these patterns in action? Check out our post on [15 Mermaid Mindmap Examples with Real Use Cases](/blog/mermaid-mindmap-tutorial). It has project planning, learning paths, business strategy maps, and more — all with working code. For the full advanced techniques (custom themes, exported SVGs, integrating with docs tools), see our [Mermaid Mindmap Advanced Examples](/blog/mermaid-mindmap-tutorial). --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** All the code blocks in this cheat sheet work directly in our editor. Copy, paste, tweak. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ### How to Use Mermaid Diagrams in Obsidian URL: https://mermaideditor.lol/blog/mermaid-in-obsidian Published: 2025-12-30 Updated: 2025-12-30 Description: Complete guide to creating and using Mermaid diagrams in Obsidian. Learn how to enable Mermaid, create diagrams, customize rendering, and publish compatibility. ## Introduction Obsidian is one of the most popular knowledge management tools, and one of its best features is **native Mermaid.js support**. You don't need any plugins — Mermaid diagrams render directly in your notes out of the box. This makes Obsidian an incredibly powerful tool for developers and knowledge workers who want to combine written notes with visual diagrams. In this guide, you'll learn everything about using Mermaid in Obsidian, from basic setup to advanced tips. ## Enabling Mermaid in Obsidian Great news: **there's nothing to enable**. Obsidian supports Mermaid natively since version 0.15. Simply create a code block with the `mermaid` language identifier, and Obsidian will render it automatically in Reading View and Live Preview. If you're on an older version of Obsidian, update to the latest version to get Mermaid support. The latest versions of Obsidian typically ship with a recent version of Mermaid.js, giving you access to most diagram types. ## Creating Your First Diagram In any Obsidian note, type: ```mermaid graph TD A[Idea] --> B[Research] B --> C[Draft] C --> D[Review] D --> E[Publish] ``` Switch to **Reading View** (or use **Live Preview**) and you'll see the diagram rendered inline with your notes. It's that simple. ## Supported Diagram Types Obsidian supports all major Mermaid diagram types: - **Flowcharts** — Process flows, decision trees - **Sequence Diagrams** — API calls, interactions - **Gantt Charts** — Project timelines - **Class Diagrams** — UML modeling - **State Diagrams** — State machines, workflows - **ER Diagrams** — Database schemas - **Pie Charts** — Data distribution - **Mind Maps** — Brainstorming, topic hierarchies - **Git Graphs** — Branch visualization - **Timeline** — Historical events, roadmaps The exact feature support depends on which version of Mermaid is bundled with your Obsidian version. ## Practical Examples for Obsidian Notes ### Project Planning Note Combine text and diagrams in a single note: ```markdown # Project Alpha — Planning ## Overview Project Alpha aims to rebuild our authentication system with OAuth 2.0 support. ## Architecture ```mermaid graph TB subgraph Frontend React[React App] --> AuthSDK[Auth SDK] end subgraph Backend API[API Server] --> AuthService[Auth Service] AuthService --> UserDB[(User DB)] AuthService --> Redis[(Session Store)] end AuthSDK --> API ``` ## Timeline ```mermaid gantt title Project Alpha Timeline dateFormat YYYY-MM-DD section Phase 1 Research & Design :a1, 2025-01-06, 10d section Phase 2 Implementation :a2, after a1, 20d section Phase 3 Testing & Launch :a3, after a2, 10d ``` ``` ### Daily Notes with Diagrams Add quick process diagrams to your daily notes: ```mermaid sequenceDiagram participant Me participant PM participant Design Me->>PM: Proposed API changes PM->>Design: Request UI review Design-->>PM: Approved with changes PM-->>Me: Go ahead with modifications ``` ### Knowledge Base Entries Document systems with ER diagrams: ```mermaid erDiagram NOTE ||--o{ TAG : has NOTE ||--o{ LINK : links_to NOTE { string title text content date created date modified } TAG { string name } LINK { string source_id string target_id } ``` ## Tips for Mermaid in Obsidian ### 1. Use Live Preview Obsidian's Live Preview mode renders Mermaid diagrams inline as you type. This gives you instant feedback without switching between edit and reading modes. ### 2. Keep Diagrams Small Large Mermaid diagrams can slow down Obsidian's rendering, especially with many notes open. Aim for diagrams with fewer than 20-30 nodes. If you need a complex diagram, consider putting it in its own note and linking to it. ### 3. Use Obsidian Linking with Diagrams While you can't make diagram nodes clickable links in Obsidian, you can place diagrams alongside `[[wiki links]]` to create a powerful combination of visual and textual navigation. ### 4. Theming Obsidian applies its own CSS theme to Mermaid diagrams. If you're using a dark theme, diagrams will automatically adjust. However, if you use explicit colors in your Mermaid code (via `classDef` or `style`), make sure they work with both light and dark themes. You can also use Mermaid's built-in theming: ```mermaid %%{init: {'theme': 'dark'}}%% graph TD A --> B --> C ``` ### 5. CSS Snippets for Custom Styling Obsidian allows CSS snippets that can style Mermaid diagrams. Create a CSS file in your vault's `.obsidian/snippets/` folder: ```css .mermaid svg { max-width: 100%; font-family: var(--font-text); } .mermaid .node rect { rx: 8px; ry: 8px; } ``` ### 6. Templates Create Obsidian templates with pre-built Mermaid diagrams. For example, a "Meeting Notes" template could include: ```markdown # Meeting: {{title}} Date: {{date}} ## Action Items ```mermaid graph LR A[Action 1] --> B[Owner: TBD] C[Action 2] --> D[Owner: TBD] ``` ``` ## Obsidian Publish Compatibility If you use **Obsidian Publish** to share your notes as a website, Mermaid diagrams **are fully supported**. They render on published pages just as they do in the app. This makes it easy to create documentation sites with embedded diagrams — no extra build steps or plugins needed. Your readers see the same rendered diagrams you see in your vault. ### Tips for Published Diagrams - Test your diagrams in Reading View before publishing — what you see is what your readers get. - Keep diagram complexity reasonable for mobile readers. - Use descriptive text alongside diagrams since some readers may have rendering issues on older browsers. ## Community Plugins While native Mermaid support is sufficient for most use cases, there are community plugins that extend the experience: - **Mermaid Tools** — Adds a toolbar for inserting Mermaid templates. - **Obsidian Enhancing Export** — Exports notes with rendered Mermaid diagrams to PDF. - **Diagrams** — Provides an alternative rendering engine with additional options. Search for these in Obsidian's community plugin browser (Settings → Community Plugins → Browse). ## Common Issues ### Diagram Not Rendering - Make sure you're using ```mermaid``` (lowercase) as the code fence language. - Switch to Reading View or Live Preview — Source mode shows raw code. - Check for syntax errors in your Mermaid code. ### Diagram Looks Different Than Expected - Obsidian may use a slightly different version of Mermaid than the latest release. Some newer features might not work. - Your theme's CSS might affect colors and fonts. Try switching to a default theme to test. ### Performance Issues - Large diagrams (30+ nodes) can slow down rendering. - Many diagrams on a single page can cause lag. Consider splitting into linked notes. ## Best Practices 1. **One diagram per concept.** Don't try to show everything in one diagram. 2. **Label your diagrams.** Add a heading above each diagram explaining what it shows. 3. **Use consistent notation.** Pick a direction (TD or LR) and stick with it in your vault. 4. **Keep the source readable.** Even in code blocks, format your Mermaid code neatly with proper indentation. 5. **Version your vault.** Since Mermaid diagrams are plain text, they work perfectly with Git for version control. ## Conclusion Obsidian's native Mermaid support makes it one of the best environments for combining structured notes with visual diagrams. Whether you're documenting architectures, planning projects, or building a knowledge base, Mermaid diagrams add a powerful visual dimension to your notes — all without leaving your text editor. [Try creating Mermaid diagrams in our free online editor →](/) ### Creating Mermaid Diagrams in Notion URL: https://mermaideditor.lol/blog/mermaid-in-notion Published: 2026-01-10 Updated: 2026-01-10 Description: How to create and use Mermaid diagrams in Notion. Learn the code block method, understand limitations, and discover workarounds for the best diagramming experience. ## Introduction Notion has become one of the most popular workspace tools for teams and individuals. While it doesn't have native Mermaid rendering like GitHub or Obsidian, there are effective ways to create and display Mermaid diagrams in Notion. This guide covers the available methods, their limitations, and the best workarounds. ## Does Notion Support Mermaid Natively? As of early 2026, Notion has **added native Mermaid support** through its code block feature. You can create a code block, select "Mermaid" as the language, and Notion will render the diagram inline. Here's how to add a Mermaid diagram in Notion: 1. Type `/code` in any Notion page to insert a code block. 2. Click the language selector in the top-right of the code block. 3. Search for and select **"Mermaid"**. 4. Paste or type your Mermaid code. 5. The diagram renders automatically below the code. ### Example Paste this into a Mermaid code block in Notion: ```mermaid graph TD A[Task Created] --> B{Assigned?} B -->|Yes| C[In Progress] B -->|No| D[Backlog] C --> E{Done?} E -->|Yes| F[Complete] E -->|No| C ``` You should see a rendered flowchart directly in your Notion page. ## Supported Diagram Types in Notion Notion's Mermaid integration supports the most common diagram types: - **Flowcharts** (`graph` / `flowchart`) - **Sequence Diagrams** (`sequenceDiagram`) - **Gantt Charts** (`gantt`) - **Class Diagrams** (`classDiagram`) - **State Diagrams** (`stateDiagram-v2`) - **ER Diagrams** (`erDiagram`) - **Pie Charts** (`pie`) Mind maps, git graphs, and some newer diagram types may have limited support depending on the Mermaid version Notion uses. ## Practical Use Cases in Notion ### Team Wiki — Architecture Docs Create a page in your team wiki with architecture diagrams: ```mermaid graph TB subgraph "Client Layer" Web[Web App] Mobile[Mobile App] end subgraph "API Layer" Gateway[API Gateway] Auth[Auth Service] end subgraph "Data Layer" DB[(PostgreSQL)] Cache[(Redis)] end Web & Mobile --> Gateway Gateway --> Auth Gateway --> DB Gateway --> Cache ``` ### Sprint Planning Add a Gantt chart to your sprint page: ```mermaid gantt title Sprint 16 — March 3-14 dateFormat YYYY-MM-DD excludes weekends section Frontend Search feature :f1, 2026-03-03, 3d Filter UI :f2, after f1, 2d section Backend Search API :b1, 2026-03-03, 4d Indexing :b2, after b1, 2d section QA Testing :q1, after f2 b2, 2d Release :milestone, m1, after q1, 0d ``` ### Meeting Notes Document decisions with sequence diagrams: ```mermaid sequenceDiagram participant PM as Product Manager participant Dev as Dev Lead participant Design as Designer PM->>Dev: Propose feature X Dev->>PM: Estimate: 2 sprints PM->>Design: Request mockups Design-->>PM: Mockups ready PM->>Dev: Approved — start Sprint 17 ``` ### Database Documentation Use ER diagrams to document your data model: ```mermaid erDiagram WORKSPACE ||--o{ PROJECT : contains PROJECT ||--o{ PAGE : has PAGE ||--o{ BLOCK : contains WORKSPACE ||--o{ MEMBER : has MEMBER { string id PK string name string email string role } PAGE { string id PK string title string content datetime updated } ``` ## Limitations of Mermaid in Notion ### 1. Version Lag Notion may not run the latest version of Mermaid.js. This means some newer features or diagram types might not be available. If a diagram works in an online editor but not in Notion, this is likely the reason. ### 2. Limited Styling Custom CSS styling through `classDef` and `style` directives may not render exactly as expected. Notion applies its own styling layer, which can affect colors, fonts, and spacing. ### 3. No Click Interaction Mermaid diagrams in Notion are static images — you can't click on nodes or add links within the diagram. For interactive diagrams, you'll need a dedicated tool. ### 4. Dark Mode Compatibility If you or your team uses Notion in dark mode, some Mermaid color schemes may not look great. Test your diagrams in both modes if your team uses both. Using Mermaid's built-in theme configuration can help: ```mermaid %%{init: {'theme': 'neutral'}}%% graph TD A --> B --> C ``` The `neutral` theme tends to work well in both light and dark modes. ### 5. Export Limitations When exporting Notion pages to PDF or Markdown, Mermaid diagrams may export as code blocks rather than rendered images. Keep this in mind if you need to share pages outside of Notion. ## Workarounds for Better Diagrams ### Method 1: External Editor + Image Embed For complex diagrams or when you need precise control: 1. Create your diagram in an online Mermaid editor. 2. Export as SVG or PNG. 3. Upload the image to your Notion page. 4. Keep the Mermaid source code in a collapsed toggle block for future editing. This gives you the best visual quality and full Mermaid feature support. ### Method 2: Embed with URL Use an embeddable Mermaid viewer: 1. Encode your diagram. 2. Create a URL with the encoded diagram. 3. Use Notion's /embed block to embed the URL. This approach keeps the diagram live and editable through the URL. ### Method 3: Use Notion API + Mermaid For teams that want automated diagrams, you can use the Notion API to programmatically insert and update Mermaid code blocks. This is useful for: - Auto-generating architecture diagrams from code - Updating project timelines from your PM tool - Syncing database schemas with documentation ## Tips for Mermaid in Notion 1. **Keep diagrams simple.** Notion's rendering area is narrower than a full browser window. Stick to 10-15 nodes max. 2. **Use `graph LR`** (left-to-right) for wider diagrams that fit Notion's column layout better than top-to-bottom. 3. **Add context with text.** Always include a text description above or below the diagram explaining what it shows. 4. **Use toggle blocks.** Put complex diagrams inside Notion toggle blocks (callouts) so they don't dominate the page. 5. **Test in both themes.** If your team uses both light and dark mode, check that your diagrams look acceptable in both. 6. **Use the `neutral` theme.** It provides the best compatibility across Notion's light and dark modes. 7. **Keep source code accessible.** If you embed an image instead of using a code block, store the source Mermaid code in a toggle block nearby so anyone can update it. ## Notion vs. Other Platforms for Mermaid | Platform | Native Support | Quality | Collaboration | |---|---|---|---| | **Notion** | Yes (code block) | Good | Excellent | | **GitHub** | Yes (Markdown) | Excellent | Good (via PRs) | | **Obsidian** | Yes (native) | Excellent | Limited | | **Confluence** | Plugin required | Good | Excellent | | **Google Docs** | No (image only) | N/A | Excellent | Notion strikes a good balance between diagram support and collaboration features. While its Mermaid rendering may not be as polished as GitHub's, the collaborative editing and rich surrounding content make it a strong choice for team documentation. ## Conclusion Mermaid diagrams in Notion are a practical way to add visual documentation to your workspace. While there are some limitations compared to dedicated diagramming tools, the convenience of having diagrams alongside your team's notes, wikis, and project management makes it worthwhile. Start with simple flowcharts and sequence diagrams, and use the workarounds for more complex visualization needs. [Create and test your Mermaid diagrams in our free online editor →](/) ### Adding Mermaid Diagrams to Docusaurus Documentation URL: https://mermaideditor.lol/blog/mermaid-in-docusaurus Published: 2026-01-18 Updated: 2026-01-18 Description: Complete guide to integrating Mermaid.js diagrams in Docusaurus. Learn plugin setup, MDX usage, theming, configuration, and practical examples for documentation sites. ## Introduction Docusaurus is a popular documentation framework built by Meta, used by many open-source projects and companies. Adding Mermaid diagrams to your Docusaurus site enhances documentation with visual architecture overviews, API flows, and system diagrams — all maintained as code. This guide covers the complete setup process, from installing the plugin to advanced theming and practical examples. ## Setting Up the Mermaid Plugin Docusaurus has an official Mermaid theme package that integrates seamlessly with its MDX-based content system. ### Step 1: Install the Package ```bash npm install @docusaurus/theme-mermaid ``` Or if you're using yarn: ```bash yarn add @docusaurus/theme-mermaid ``` ### Step 2: Configure docusaurus.config.js Add the Mermaid theme to your configuration: ```javascript // docusaurus.config.js module.exports = { // Enable Mermaid markdown support markdown: { mermaid: true, }, // Add the Mermaid theme themes: ['@docusaurus/theme-mermaid'], // Optional: configure Mermaid themeConfig: { mermaid: { theme: { light: 'neutral', dark: 'dark', }, options: { maxTextSize: 50000, }, }, }, }; ``` ### Step 3: Restart Your Dev Server ```bash npm run start ``` That's it! Mermaid diagrams will now render in your documentation. ## Using Mermaid in MDX Files Once configured, use Mermaid in any `.md` or `.mdx` file with standard code fences: ```markdown ## System Architecture ```mermaid graph TB Client --> API API --> Database API --> Cache ``` ``` The diagram renders automatically in both development and production builds. ### In MDX Components You can also use Mermaid inside MDX components: ```jsx import Mermaid from '@theme/Mermaid'; export const ArchitectureDiagram = () => ( B[API Gateway] B --> C[Service A] B --> D[Service B] `} /> ); ``` ## Practical Examples for Documentation ### API Reference with Sequence Diagrams In your API documentation, show request flows: ```mermaid sequenceDiagram participant Client participant Gateway as API Gateway participant Auth as Auth Service participant API as Core API participant DB as Database Client->>Gateway: POST /api/v1/users Gateway->>Auth: Validate API key Auth-->>Gateway: Valid Gateway->>API: Forward request API->>DB: INSERT user DB-->>API: Created API-->>Gateway: 201 Created Gateway-->>Client: 201 + User object ``` ### Architecture Overview For your project's landing documentation page: ```mermaid graph TB subgraph "Client Applications" Web[Web Dashboard] CLI[CLI Tool] SDK[SDKs] end subgraph "API Layer" Gateway[API Gateway] RateLimit[Rate Limiter] end subgraph "Services" UserSvc[User Service] DataSvc[Data Service] NotifSvc[Notification Service] end subgraph "Data Stores" PG[(PostgreSQL)] Redis[(Redis)] S3[(S3 Storage)] end Web & CLI & SDK --> Gateway Gateway --> RateLimit RateLimit --> UserSvc & DataSvc & NotifSvc UserSvc --> PG DataSvc --> PG & S3 NotifSvc --> Redis ``` ### Database Schema Documentation Document your data model in the schema reference section: ```mermaid erDiagram ORGANIZATION ||--o{ TEAM : has TEAM ||--o{ USER : contains USER ||--o{ API_KEY : owns USER ||--o{ PROJECT : creates PROJECT ||--o{ RESOURCE : manages ORGANIZATION { uuid id PK string name string plan datetime created_at } USER { uuid id PK string email UK string role uuid org_id FK } API_KEY { uuid id PK string key_hash UK string name datetime expires_at uuid user_id FK } ``` ### Plugin Architecture Document your plugin or extension system: ```mermaid classDiagram class PluginManager { +register(plugin) void +unregister(name) void +getPlugin(name) Plugin +executeHook(hook, data) any } class Plugin { <> +name: string +version: string +initialize() void +destroy() void } class AuthPlugin { +name: "auth" +initialize() void +validateToken(token) bool } class LoggingPlugin { +name: "logging" +initialize() void +log(level, message) void } PluginManager "1" --> "*" Plugin : manages Plugin <|.. AuthPlugin Plugin <|.. LoggingPlugin ``` ## Theming Mermaid Diagrams ### Matching Docusaurus Themes Docusaurus supports light and dark modes, and the Mermaid plugin can automatically switch themes: ```javascript themeConfig: { mermaid: { theme: { light: 'neutral', dark: 'dark', }, }, }, ``` Available Mermaid themes: - **default** — Blue and gray palette - **neutral** — Monochrome, professional (recommended for docs) - **dark** — Dark background (for dark mode) - **forest** — Green palette - **base** — Minimal, customizable with CSS variables ### Custom Theme Variables For brand-aligned diagrams: ```javascript themeConfig: { mermaid: { theme: { light: 'base', dark: 'dark', }, options: { themeVariables: { primaryColor: '#4f46e5', primaryTextColor: '#ffffff', primaryBorderColor: '#3730a3', lineColor: '#6366f1', secondaryColor: '#e0e7ff', tertiaryColor: '#f5f3ff', }, }, }, }, ``` ### Per-Diagram Themes Override the global theme for specific diagrams: ```mermaid %%{init: {'theme': 'forest'}}%% graph TD A[This diagram] --> B[uses forest theme] B --> C[regardless of global config] ``` ## Advanced Configuration ### Custom Fonts Match your documentation's font: ```javascript mermaid: { options: { fontFamily: 'Inter, system-ui, sans-serif', fontSize: 14, }, }, ``` ### Security Configuration For documentation sites that accept user-contributed content: ```javascript mermaid: { options: { securityLevel: 'strict', maxTextSize: 10000, }, }, ``` Security levels: - **strict** — HTML tags are encoded (recommended for public docs) - **loose** — HTML tags are allowed in labels - **antiscript** — HTML tags allowed but script tags removed - **sandbox** — Maximum security, renders in iframe ### Handling Large Diagrams For documentation with complex architecture diagrams: ```javascript mermaid: { options: { maxTextSize: 100000, flowchart: { useMaxWidth: true, htmlLabels: true, curve: 'basis', }, sequence: { useMaxWidth: true, wrap: true, }, }, }, ``` ## Versioned Documentation Docusaurus supports documentation versioning, which works perfectly with Mermaid diagrams. Since diagrams are text-based, they're automatically included in version snapshots. When your architecture changes between versions, the corresponding diagrams in each version remain accurate: - `docs/v1.0/architecture.md` → Old architecture diagram - `docs/v2.0/architecture.md` → Updated architecture diagram Each version maintains its own diagrams without any extra configuration. ## Performance Considerations ### Build Time Mermaid diagrams are rendered client-side (in the browser), not during the build process. This means: - Build times aren't affected by the number of diagrams. - Diagrams render after page load, which may cause a brief flash. - Complex diagrams may take a moment to render on slower devices. ### Lazy Loading For pages with many diagrams, consider using Docusaurus's tab components to lazy-load diagram sections: ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Overview diagram here Detailed diagram here ``` ## Common Issues ### Diagram Not Rendering 1. Ensure `markdown.mermaid: true` is set in your config. 2. Verify `@docusaurus/theme-mermaid` is in the themes array. 3. Check that the code fence language is exactly `mermaid`. 4. Restart the dev server after configuration changes. ### Theme Mismatch If diagrams look wrong in dark mode, make sure you've configured both light and dark themes in your config. The `neutral` and `dark` combination works well for most documentation sites. ### Syntax Errors Mermaid will show an error message if the syntax is invalid. Test your diagrams in an online Mermaid editor before adding them to your docs. ## Best Practices for Docusaurus Documentation 1. **Use the `neutral` theme** for light mode — it's the most professional-looking for documentation. 2. **Place architecture diagrams early** in your docs. The "Overview" or "Getting Started" page should include a high-level system diagram. 3. **Add diagrams to API references.** Sequence diagrams showing request/response flows are invaluable for API consumers. 4. **Document your database schema** with ER diagrams. Keep them in a dedicated "Data Model" page. 5. **Use consistent styling.** Pick a Mermaid theme and stick with it across all your documentation pages. 6. **Add text descriptions.** Don't rely solely on diagrams. Include text explaining what the diagram shows for accessibility and SEO. 7. **Keep diagrams up to date.** Since they're text-based and live in your docs repo, update them in the same PR that changes the code. ## Conclusion Mermaid diagrams in Docusaurus transform technical documentation from walls of text into visual, scannable references. The setup is straightforward, theming is flexible, and because diagrams are code, they version and review just like any other documentation change. Start with an architecture overview diagram and expand to API flows, data models, and state machines as your documentation grows. [Test your Mermaid diagrams in our free online editor →](/) ### Mermaid Git Graph Tutorial — Visualize Branch Strategies URL: https://mermaideditor.lol/blog/mermaid-git-graph-tutorial Published: 2026-02-05 Updated: 2026-02-05 Description: Learn to create git graph diagrams with Mermaid.js. Visualize branching strategies, merge workflows, cherry-picks, and popular models like GitFlow and trunk-based development. ## Introduction Understanding Git branching strategies is crucial for development teams, and visualizing them makes the concepts much clearer. Mermaid's git graph diagram type lets you create visual representations of commits, branches, merges, and cherry-picks with simple text commands. Whether you're documenting your team's workflow, teaching Git concepts, or planning a migration between branching strategies, Mermaid git graphs are the perfect tool. ## Basic Syntax ```mermaid gitGraph commit commit commit ``` This creates a simple linear history with three commits on the default `main` branch. Each `commit` command adds a new commit node to the graph. ### Commit Options You can customize each commit: ```mermaid gitGraph commit id: "init" commit id: "feat-1" type: HIGHLIGHT commit id: "fix-1" tag: "v1.0" ``` Commit properties: - **`id`** — Custom label (displayed on the commit node) - **`tag`** — Version tag (shown above the commit) - **`type`** — Visual type: `NORMAL` (default), `HIGHLIGHT`, `REVERSE` ## Branching and Merging The core of any git graph is branching: ```mermaid gitGraph commit id: "initial" commit id: "add readme" branch feature checkout feature commit id: "add login" commit id: "add tests" checkout main commit id: "hotfix" merge feature id: "merge feature" commit id: "release" tag: "v1.0" ``` Key commands: - **`branch `** — Create a new branch - **`checkout `** — Switch to a branch - **`merge `** — Merge a branch into the current branch - **`cherry-pick id: ""`** — Cherry-pick a specific commit ## Cherry-Pick Demonstrate cherry-picking: ```mermaid gitGraph commit id: "A" commit id: "B" branch feature checkout feature commit id: "C" commit id: "D" type: HIGHLIGHT commit id: "E" checkout main commit id: "F" cherry-pick id: "D" commit id: "G" ``` This shows commit `D` being cherry-picked from the `feature` branch to `main`. ## GitFlow Strategy GitFlow is one of the most popular branching models. Here's how to visualize it: ```mermaid gitGraph commit id: "init" tag: "v0.1" branch develop checkout develop commit id: "dev setup" branch feature/auth checkout feature/auth commit id: "login page" commit id: "auth API" commit id: "auth tests" checkout develop merge feature/auth id: "merge auth" branch feature/dashboard checkout feature/dashboard commit id: "dashboard UI" commit id: "widgets" checkout develop merge feature/dashboard id: "merge dashboard" branch release/v1.0 checkout release/v1.0 commit id: "bump version" commit id: "fix typos" checkout main merge release/v1.0 id: "release" tag: "v1.0" checkout develop merge release/v1.0 id: "back-merge" checkout main branch hotfix/security commit id: "patch CVE" checkout main merge hotfix/security id: "hotfix" tag: "v1.0.1" checkout develop merge hotfix/security id: "hotfix to dev" ``` ### GitFlow Branch Purposes - **main** — Production-ready code. Every commit is a release. - **develop** — Integration branch for features. Always ahead of main. - **feature/*** — Individual features. Branch from develop, merge back to develop. - **release/*** — Release preparation. Branch from develop, merge to both main and develop. - **hotfix/*** — Emergency fixes. Branch from main, merge to both main and develop. ## Trunk-Based Development A simpler strategy where everyone works on short-lived branches off main: ```mermaid gitGraph commit id: "init" commit id: "CI setup" branch feat-1 checkout feat-1 commit id: "small change" checkout main merge feat-1 commit id: "direct fix" branch feat-2 checkout feat-2 commit id: "refactor" commit id: "tests" checkout main merge feat-2 branch feat-3 checkout feat-3 commit id: "update API" checkout main merge feat-3 commit id: "deploy" tag: "v1.1" ``` ### Key Principles of Trunk-Based - **Short-lived branches** — 1-2 days maximum - **Small, frequent merges** — Reduce merge conflicts - **Feature flags** — Instead of long-lived feature branches - **Continuous integration** — Every merge triggers CI/CD ## GitHub Flow A simplified model used by many teams: ```mermaid gitGraph commit id: "v1.0" tag: "v1.0" branch feature/search checkout feature/search commit id: "search UI" commit id: "search API" commit id: "search tests" checkout main merge feature/search id: "PR #42 merged" commit id: "deploy" tag: "v1.1" branch fix/bug-123 checkout fix/bug-123 commit id: "fix null check" checkout main merge fix/bug-123 id: "PR #43 merged" commit id: "deploy" tag: "v1.1.1" ``` GitHub Flow rules: 1. `main` is always deployable 2. Create feature branches from main 3. Open a pull request for discussion 4. Merge to main after review 5. Deploy immediately after merge ## Release Branch Strategy For teams that maintain multiple release versions: ```mermaid gitGraph commit id: "init" commit id: "feature A" commit id: "feature B" tag: "v1.0" branch release/v1 checkout release/v1 commit id: "v1 patch 1" commit id: "v1 patch 2" tag: "v1.0.2" checkout main commit id: "feature C" commit id: "feature D" tag: "v2.0" branch release/v2 checkout release/v2 commit id: "v2 patch 1" tag: "v2.0.1" checkout main commit id: "feature E" commit id: "feature F" ``` This shows how teams can maintain v1.x patches while continuing v2.x development. ## Comparing Strategies Side by Side Here's when to use each strategy: ### GitFlow — Best For: - Teams with scheduled releases - Products with multiple supported versions - When you need a staging/integration branch ### Trunk-Based — Best For: - Teams practicing continuous deployment - Mature CI/CD pipelines - Small, experienced teams - Microservice architectures ### GitHub Flow — Best For: - Open-source projects - Small to medium teams - Web applications with continuous deployment - Teams that want simplicity ## Styling Git Graphs ### Custom Branch Colors You can customize how branches appear using Mermaid themes: ```mermaid %%{init: { 'theme': 'base', 'themeVariables': { 'git0': '#4f46e5', 'git1': '#10b981', 'git2': '#f59e0b', 'git3': '#ef4444', 'gitBranchLabel0': '#ffffff', 'gitBranchLabel1': '#ffffff', 'gitBranchLabel2': '#000000', 'gitBranchLabel3': '#ffffff' }}}%% gitGraph commit branch develop checkout develop commit branch feature commit checkout develop merge feature checkout main merge develop tag: "v1.0" ``` ### Branch Ordering Mermaid renders branches in the order they're created. Plan your branch creation order to get a clean layout: 1. Create the main branch first (automatic) 2. Create long-lived branches (develop, release) early 3. Create feature branches when needed ## Documenting Your Team's Workflow Use git graphs in your team's CONTRIBUTING.md or development guide: ```markdown ## Our Branching Strategy We use a simplified GitFlow model: ```mermaid gitGraph commit tag: "latest release" branch develop checkout develop commit id: "feature work" branch feature/your-feature commit id: "your changes" checkout develop merge feature/your-feature id: "PR merged" checkout main merge develop tag: "next release" ``` ### Steps to Contribute: 1. Branch from `develop` 2. Name your branch `feature/description` 3. Open a PR to `develop` 4. After review, it'll be merged 5. Releases are cut from `develop` to `main` ``` ## Best Practices 1. **Keep git graphs focused.** Show one strategy or workflow per diagram. Don't try to illustrate every possible scenario. 2. **Use meaningful commit IDs.** Instead of auto-generated IDs, use descriptive labels like `"add auth"`, `"fix bug"`, `"deploy"`. 3. **Add version tags.** Use `tag: "v1.0"` on release commits to clearly mark version milestones. 4. **Highlight important commits.** Use `type: HIGHLIGHT` for commits you want to draw attention to. 5. **Document the strategy, not the history.** Git graphs in documentation should show the ideal workflow, not your actual messy commit history. 6. **Combine with text explanations.** Not everyone reads diagrams intuitively. Add bullet points explaining each step. ## Limitations - **No detached HEAD** — You can't show detached HEAD states - **No rebasing** — Mermaid git graphs don't support rebase visualization - **No squash merges** — All merges are shown as merge commits - **Limited branch count** — More than 4-5 branches makes the diagram hard to read - **No stashing** — Stash operations can't be visualized For these advanced scenarios, consider using a whiteboard or specialized Git visualization tools alongside your Mermaid documentation. ## Conclusion Mermaid git graphs are invaluable for documenting branching strategies, teaching Git workflows, and communicating development processes. Whether your team uses GitFlow, trunk-based development, or GitHub Flow, visualizing the strategy makes it accessible to everyone — from junior developers to stakeholders who need to understand the release process. [Create git graph diagrams in our free Mermaid Live Editor →](/) ### Creating User Journey Maps with Mermaid.js URL: https://mermaideditor.lol/blog/mermaid-user-journey-map Published: 2026-02-20 Updated: 2026-02-20 Description: Learn how to create user journey maps with Mermaid.js. Understand the syntax, add sections and scoring, and apply journey mapping to UX research and product design. ## What Are User Journey Maps? User journey maps are visual representations of the steps a user takes to accomplish a goal with your product or service. They document the user's experience at each step, including their satisfaction level, pain points, and emotional response. Journey maps are essential tools for: - **UX research** — Understanding current user experience - **Product design** — Identifying improvement opportunities - **Stakeholder communication** — Making user pain points visible - **Onboarding optimization** — Smoothing the new user experience - **Service design** — Mapping end-to-end customer journeys Mermaid.js provides a `journey` diagram type that lets you create these maps as code — quick to write, easy to update, and version-controllable. ## Basic Syntax ```mermaid journey title My Working Day section Morning Wake up: 3: Me Commute to work: 1: Me Arrive at office: 5: Me section Afternoon Lunch meeting: 3: Me, PM Code review: 4: Me, Dev section Evening Leave office: 5: Me Dinner: 5: Me, Family ``` ### Key Elements - **`title`** — The journey map's title - **`section`** — Groups steps into phases (shown as labeled sections) - **Steps** — Format: `Task name: score: actors` - **Score** — Satisfaction rating from 1 (worst) to 5 (best) - **Actors** — Who's involved in this step (comma-separated) ## Scoring Guide The score (1-5) represents the user's experience at each step: - **5** — Delighted, exceeded expectations, wow moment - **4** — Satisfied, smooth experience, no issues - **3** — Neutral, acceptable but unremarkable - **2** — Frustrated, encountering friction or confusion - **1** — Very unhappy, major pain point, might abandon Mermaid visualizes these scores with color coding — higher scores appear in green tones, lower scores in red/orange tones. This makes pain points immediately visible. ## Practical Example: E-Commerce Purchase Journey ```mermaid journey title Online Shopping Experience section Discovery Google search for product: 3: Customer Land on product page: 4: Customer Browse similar items: 4: Customer Read reviews: 5: Customer section Decision Compare prices: 3: Customer Check shipping options: 2: Customer Calculate total with tax: 2: Customer section Purchase Add to cart: 5: Customer Create account: 1: Customer Enter payment details: 3: Customer Confirm order: 4: Customer section Post-Purchase Receive confirmation email: 5: Customer Track shipment: 4: Customer Receive package: 5: Customer Unbox product: 5: Customer ``` ### Insights from This Journey Looking at the scores, we can immediately identify: - **Pain points**: Account creation (1), shipping options (2), tax calculation (2) - **Delight moments**: Reviews (5), add to cart (5), confirmation email (5), unboxing (5) - **Improvement opportunities**: Simplify account creation (guest checkout), be transparent about total costs earlier ## Practical Example: SaaS Onboarding Journey ```mermaid journey title New User Onboarding section Sign Up Visit landing page: 4: User Click Sign Up: 5: User Fill registration form: 3: User Verify email: 2: User Complete profile: 2: User section First Use See empty dashboard: 1: User Find tutorial: 3: User Create first project: 4: User, App Import data: 2: User, App See first results: 5: User section Activation Invite team member: 3: User Set up integration: 2: User, Admin Configure settings: 3: User, Admin Complete onboarding: 4: User section Retention Daily usage: 4: User Discover advanced feature: 5: User Hit usage limit: 1: User Upgrade decision: 3: User ``` ### Analysis - The **empty dashboard** (score: 1) is a critical moment — new users who see nothing are likely to churn. - **Email verification** (score: 2) creates friction before the user sees any value. - **Hitting usage limits** (score: 1) is a conversion moment but needs careful handling to avoid frustration. ## Practical Example: Developer API Integration ```mermaid journey title API Integration Journey section Research Find API documentation: 3: Developer Read getting started guide: 4: Developer Review API reference: 3: Developer Check pricing/limits: 4: Developer section Setup Create developer account: 3: Developer Generate API key: 5: Developer Install SDK: 4: Developer Configure environment: 3: Developer section Integration Make first API call: 5: Developer Handle authentication: 3: Developer Implement error handling: 2: Developer Parse response data: 4: Developer section Production Test under load: 3: Developer, DevOps Deploy to production: 4: Developer, DevOps Monitor performance: 3: Developer, DevOps Handle rate limits: 2: Developer ``` ## Multiple Actors Journey maps can track multiple actors to show different perspectives: ```mermaid journey title Restaurant Dining Experience section Arrival Find restaurant: 3: Customer Welcome guests: 5: Customer, Host Show to table: 4: Customer, Host section Ordering Browse menu: 4: Customer Take order: 4: Customer, Waiter Send to kitchen: 3: Waiter, Chef section Dining Prepare food: 3: Chef Serve food: 5: Customer, Waiter Enjoy meal: 5: Customer Check on table: 4: Customer, Waiter section Payment Request bill: 3: Customer, Waiter Process payment: 3: Customer, Waiter Leave tip: 4: Customer Say goodbye: 5: Customer, Host ``` This multi-actor view helps identify where interactions between roles create friction or delight. ## Using Journey Maps in UX Research ### Step 1: Gather Data Before creating a journey map, collect data through: - User interviews and surveys - Analytics data (funnel analysis, drop-off rates) - Customer support tickets and common complaints - Session recordings (Hotjar, FullStory, etc.) - NPS and satisfaction surveys ### Step 2: Map the Current State Create a journey map reflecting the actual user experience: ```mermaid journey title Current Checkout Experience section Cart Review View cart: 4: User Update quantities: 3: User Apply coupon: 1: User section Shipping Enter address: 3: User Choose shipping: 2: User See delivery estimate: 4: User section Payment Enter card details: 3: User See order summary: 4: User Click purchase: 5: User section Confirmation See confirmation: 5: User Get email receipt: 5: User ``` ### Step 3: Identify Opportunities Look for steps with scores of 1-2 — these are your improvement opportunities: - Coupon application (1): Make the UI more intuitive - Shipping options (2): Simplify choices, show costs upfront ### Step 4: Map the Desired State Create a target journey map showing the ideal experience: ```mermaid journey title Improved Checkout Experience section Cart Review View cart: 5: User Update quantities: 5: User Apply coupon (auto-suggest): 4: User section Shipping Auto-fill address: 5: User Smart shipping recommendation: 4: User Real-time delivery estimate: 5: User section Payment Saved payment method: 5: User Clear order summary: 5: User One-click purchase: 5: User section Confirmation Instant confirmation: 5: User Rich email receipt: 5: User ``` Compare the current vs. desired maps to build your product roadmap. ## Journey Maps in Documentation Add journey maps to your product documentation: ### In README Files ```markdown ## User Experience ```mermaid journey title Getting Started with OurTool section Setup Install CLI: 5: Developer Run init command: 5: Developer Configure project: 4: Developer section First Use Create first item: 5: Developer See preview: 5: Developer Deploy: 4: Developer ``` ``` ### In Design Documents Include journey maps in your product design docs to: - Show the current user experience - Highlight pain points that justify the proposed changes - Illustrate the expected improved journey ### In Sprint Retrospectives Map the team's development experience: ```mermaid journey title Sprint 14 Developer Experience section Planning Sprint planning meeting: 3: Team Ticket breakdown: 4: Team Estimation: 2: Team section Development Pick up tickets: 5: Dev Local development: 4: Dev Code review turnaround: 2: Dev section Deployment CI pipeline: 3: Dev, DevOps Staging deploy: 4: Dev, DevOps Production deploy: 5: Dev, DevOps ``` ## Tips for Effective Journey Maps 1. **Base scores on data, not assumptions.** Use analytics, surveys, and user feedback to assign scores. 2. **Keep it focused.** Map one journey (one user goal) per diagram. Don't try to map every possible path. 3. **Use sections meaningfully.** Sections should represent distinct phases of the journey, not arbitrary groupings. 4. **Include all relevant actors.** If a support agent is involved in a step, include them — it reveals handoff points. 5. **Update regularly.** Journey maps should evolve as you ship improvements. Update scores when you fix pain points. 6. **Pair with metrics.** Link journey map steps to actual metrics: "Cart Review (score: 4) — 85% proceed to next step." 7. **Keep scores honest.** A journey map full of 5s isn't useful. The whole point is to reveal where the experience needs improvement. 8. **Share widely.** Journey maps are communication tools. Share them with engineering, design, product, and leadership. ## Limitations of Mermaid Journey Maps - **No custom icons or images** — Steps are text-only - **Linear flow only** — You can't show branching paths or loops - **Limited styling** — Colors are determined by scores, not customizable - **No annotations** — You can't add detailed notes to individual steps - **Simple scoring** — Only integer scores 1-5 are supported For more sophisticated journey mapping with detailed annotations, emotional curves, and branching paths, consider dedicated UX tools like Figma, Miro, or Smaply. Mermaid journey maps excel at **quick, version-controlled documentation** that lives alongside your code. ## Conclusion Mermaid journey maps bring user experience visualization into your development workflow. They're quick to create, easy to update, and version-controllable — making them perfect for documenting user journeys in README files, design documents, and sprint retrospectives. Start by mapping your most important user journey, identify the low-scoring steps, and use that data to drive product improvements. [Create journey maps in our free Mermaid Live Editor →](/) ### Mermaid.js Themes & Dark Mode Customization Guide URL: https://mermaideditor.lol/blog/mermaid-themes-dark-mode Published: 2026-03-17 Updated: 2026-03-17 Description: Learn how to apply built-in themes, enable dark mode, and customize Mermaid.js diagrams with themeVariables and CSS. Includes copy-paste examples for every theme. ## Why Customize Mermaid Diagrams? Mermaid.js renders diagrams using a default blue-and-gray palette that works fine for most documentation. But there are plenty of reasons to go further: - Your company has a **brand color palette** to match - You're embedding diagrams in a **dark mode** documentation site - You want **color-coded diagrams** that communicate meaning (red = error, green = success) - The default theme doesn't match your project's aesthetic Mermaid gives you three layers of customization: **built-in themes**, **theme variables**, and **CSS overrides**. This guide covers all three. ## Built-In Themes Mermaid ships with five built-in themes. Switching between them requires just one line of configuration. ### The 5 Built-In Themes **`default`** — The standard Mermaid look. Blue primary color, light background, clean lines. Works well for technical documentation on white backgrounds. **`neutral`** — Muted grays and desaturated colors. Professional and understated. A great choice for documentation sites where the diagram shouldn't compete with the content. **`dark`** — Inverted palette for dark backgrounds. White text, dark backgrounds, bright accent colors. Perfect for dark mode documentation sites or terminal-style presentations. **`forest`** — Green-accented theme. Calming, organic feel. Popular for environmental projects, health-related documentation, and anyone who finds the default blue palette monotonous. **`base`** — A minimal starting point designed for customization via theme variables. Almost no default styling — you build on top of it. Best when you need full brand control. ### How to Apply a Theme **Method 1: Per-diagram init directive** Add a `%%{init: ...}%%` comment at the very top of your diagram: ``` %%{init: {'theme': 'dark'}}%% graph TD A[Start] --> B[Process] B --> C[End] ``` This overrides the global theme for just this one diagram. Great for mixing themes on the same page. **Method 2: Global JavaScript configuration** When embedding Mermaid in a webpage or configuring it via your documentation framework: ```javascript mermaid.initialize({ startOnLoad: true, theme: 'dark', }); ``` **Method 3: Docusaurus / MkDocs config** In Docusaurus (`docusaurus.config.js`): ```javascript themeConfig: { mermaid: { theme: { light: 'neutral', dark: 'dark', }, }, }, ``` This automatically switches between light and dark Mermaid themes based on the user's Docusaurus theme preference. ## Dark Mode — The Right Way Dark mode is often requested for diagrams embedded in dark documentation themes or developer portals. Here's how to handle it properly in different contexts. ### Standalone Dark Diagram ``` %%{init: {'theme': 'dark'}}%% flowchart LR Client([Client]) --> Gateway[API Gateway] Gateway --> Auth[Auth Service] Gateway --> API[Core API] API --> DB[(PostgreSQL)] API --> Cache[(Redis)] ``` ### Auto-Switch with CSS Media Query For a webpage that supports both light and dark OS preferences, use CSS to select the right diagram: ```html
%%{init: {'theme': 'default'}}%% graph TD A --> B --> C
%%{init: {'theme': 'dark'}}%% graph TD A --> B --> C
``` ### Dark Mode in GitHub GitHub automatically detects the user's system theme and renders Mermaid diagrams appropriately. If a user has dark mode enabled, GitHub applies its own dark styling to your Mermaid diagrams. No configuration needed on your end. ## Theme Variables — Deep Customization Theme variables let you customize specific aspects of any theme without writing CSS. They're applied via the `themeVariables` key inside the `init` directive. ### Core Theme Variables ``` %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#4f46e5', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#3730a3', 'secondaryColor': '#e0e7ff', 'tertiaryColor': '#f5f3ff', 'lineColor': '#6366f1', 'background': '#ffffff', 'mainBkg': '#4f46e5', 'nodeBorder': '#3730a3', 'clusterBkg': '#e0e7ff', 'titleColor': '#1e1b4b', 'edgeLabelBackground': '#f5f5f5', 'fontFamily': 'Inter, sans-serif', 'fontSize': '14px' }}}%% graph TD A[Initialize] --> B[Process] B --> C{Success?} C -->|Yes| D[Complete] C -->|No| E[Retry] E --> B ``` ### Variable Reference | Variable | Controls | |---|---| | `primaryColor` | Node fill color | | `primaryTextColor` | Text color inside nodes | | `primaryBorderColor` | Node border color | | `secondaryColor` | Secondary node fill (alt nodes) | | `tertiaryColor` | Tertiary fill (subgraphs, etc.) | | `lineColor` | Arrow and edge color | | `background` | Diagram background | | `mainBkg` | Main background for some elements | | `titleColor` | Title text color | | `edgeLabelBackground` | Label box background on edges | | `fontFamily` | Font for all text | | `fontSize` | Base font size | ### Sequence Diagram Variables ``` %%{init: {'theme': 'base', 'themeVariables': { 'actorBkg': '#4f46e5', 'actorTextColor': '#ffffff', 'actorBorderColor': '#3730a3', 'actorLineColor': '#6366f1', 'signalColor': '#374151', 'signalTextColor': '#111827', 'labelBoxBkgColor': '#e0e7ff', 'labelBoxBorderColor': '#4f46e5', 'labelTextColor': '#1e1b4b', 'loopTextColor': '#4338ca', 'noteBorderColor': '#6366f1', 'noteBkgColor': '#f5f3ff', 'noteTextColor': '#1e1b4b', 'activationBorderColor': '#4f46e5', 'activationBkgColor': '#c7d2fe' }}}%% sequenceDiagram Client->>+Server: POST /api/login Server->>+DB: SELECT user DB-->>-Server: User found Server-->>-Client: 200 OK + JWT ``` ### Class Diagram Variables ``` %%{init: {'theme': 'base', 'themeVariables': { 'classText': '#1e1b4b', 'lineColor': '#6366f1', 'attributeBackgroundColorEven': '#f5f3ff', 'attributeBackgroundColorOdd': '#e0e7ff' }}}%% classDiagram class User { +String id +String email +login() void } class Admin { +deleteUser(id) void } User <|-- Admin ``` ## CSS Overrides — Surgical Precision For full control, you can target Mermaid's SVG elements with CSS. This works best in documentation frameworks and custom web pages. ### Basic Node Styling ```css /* Style all nodes in a specific diagram */ #my-diagram .node rect { fill: #4f46e5; stroke: #3730a3; stroke-width: 2px; rx: 8px; ry: 8px; } /* Style node text */ #my-diagram .node .label { color: white; font-family: 'Inter', sans-serif; } /* Style edges */ #my-diagram .edgePath path { stroke: #6366f1; stroke-width: 2px; } ``` ### Dark Mode CSS Override Apply a dark look to any Mermaid diagram without using the built-in dark theme: ```css .dark-diagram .mermaid svg { background: #1f2937; border-radius: 8px; padding: 16px; } .dark-diagram .mermaid .node rect, .dark-diagram .mermaid .node circle, .dark-diagram .mermaid .node polygon { fill: #374151; stroke: #6b7280; } .dark-diagram .mermaid .nodeLabel { color: #f9fafb; } .dark-diagram .mermaid .edgePath path { stroke: #9ca3af; } ``` ## Practical Brand Customization Example Here's a complete example customizing Mermaid to match a purple brand palette: ``` %%{init: { 'theme': 'base', 'themeVariables': { 'primaryColor': '#7c3aed', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#6d28d9', 'secondaryColor': '#ede9fe', 'tertiaryColor': '#f5f3ff', 'lineColor': '#8b5cf6', 'background': '#fafafa', 'titleColor': '#4c1d95', 'edgeLabelBackground': '#ede9fe', 'fontFamily': 'system-ui, sans-serif' } }}%% flowchart LR subgraph Customer Journey A([Visit]) --> B[Browse] B --> C{Interested?} C -->|Yes| D[Sign Up] C -->|No| E([Exit]) D --> F[Onboard] F --> G([Active User]) end ``` ## Quick Reference: All 5 Themes Side by Side ### Default Theme ``` %%{init: {'theme': 'default'}}%% graph LR A[Node A] --> B[Node B] --> C[Node C] ``` **Best for:** Standard technical documentation, GitHub READMEs ### Neutral Theme ``` %%{init: {'theme': 'neutral'}}%% graph LR A[Node A] --> B[Node B] --> C[Node C] ``` **Best for:** Professional docs, minimal aesthetic, mixed content pages ### Dark Theme ``` %%{init: {'theme': 'dark'}}%% graph LR A[Node A] --> B[Node B] --> C[Node C] ``` **Best for:** Dark mode sites, terminal/CLI documentation, developer portals ### Forest Theme ``` %%{init: {'theme': 'forest'}}%% graph LR A[Node A] --> B[Node B] --> C[Node C] ``` **Best for:** Environmental projects, healthcare, non-tech audiences ### Base Theme ``` %%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#e11d48'}}}%% graph LR A[Node A] --> B[Node B] --> C[Node C] ``` **Best for:** Brand-aligned diagrams, full custom control ## Tips and Common Pitfalls **Tip 1: Use `base` for custom brands.** The `default` and other themes have opinionated styles that can clash with custom variables. Starting from `base` gives you a clean slate. **Tip 2: Test across diagrams.** Theme variables apply differently to flowcharts vs. sequence diagrams vs. class diagrams. Test your theme on each type you use. **Tip 3: Respect accessibility.** Ensure sufficient contrast between text and background colors. A color that looks great might fail WCAG contrast ratio requirements. **Tip 4: Don't over-style.** The goal of a diagram is to communicate. Heavy customization can make diagrams harder to read. When in doubt, keep it simple. **Pitfall: `init` placement.** The `%%{init: ...}%%` directive must be the very first line of your diagram — not after any other code. **Pitfall: JSON formatting.** Theme variable values in the init directive must be valid JSON. Use double quotes for strings, and don't use trailing commas. ## Conclusion Mermaid's theming system gives you everything from one-line theme switches to surgical CSS overrides. For most projects, picking the right built-in theme (likely `neutral` or `dark`) is all you need. When brand alignment matters, the `base` theme plus `themeVariables` lets you match any design system without writing CSS. The init directive syntax means your theme configuration lives inside the diagram definition itself — keeping everything self-contained and portable across platforms. [Try all these themes in our free Mermaid Live Editor →](/) ### Mermaid.js vs PlantUML: Which Tool Should You Use? URL: https://mermaideditor.lol/blog/mermaid-vs-plantuml Published: 2026-03-27 Updated: 2026-03-27 Description: Compare Mermaid.js and PlantUML on syntax, diagram types, rendering, integration, and performance. Find out which diagrams-as-code tool is right for your team. ## Two Giants of Diagrams as Code If you've decided to write your diagrams as code — congratulations, you've made the right call. Version control, diff-friendly docs, and no drag-and-drop grief. But now you face a new decision: **Mermaid.js or PlantUML?** Both tools let you describe diagrams in plain text and render them as images. Both are open-source and widely adopted. Yet they feel completely different to use, have different strengths, and suit different teams. This guide gives you a thorough, honest comparison so you can make the right choice. ## A Quick Introduction to Each ### Mermaid.js Mermaid is a **JavaScript-based** diagramming library that renders diagrams client-side in the browser. It uses a clean, human-readable syntax inspired by Markdown, and it integrates natively with GitHub, GitLab, Notion, Obsidian, Docusaurus, and MkDocs. ``` graph TD A[Client] --> B[API] B --> C[(Database)] ``` ### PlantUML PlantUML is a **Java-based** tool that generates diagrams on the server side, producing PNG, SVG, or ASCII art. It's been around since 2009, has a massive feature set, and is the dominant tool in enterprise and Java-heavy teams. It requires a Java runtime (or a remote server) to render diagrams. ``` @startuml [Client] --> [API] [API] --> [Database] @enduml ``` ## Syntax Comparison This is where the tools feel most different. ### Flowcharts **Mermaid:** ``` flowchart TD Start([Begin]) --> Input[Read data] Input --> Validate{Valid?} Validate -->|Yes| Process[Process data] Validate -->|No| Error[Show error] Process --> End([Done]) Error --> Input ``` **PlantUML:** ``` @startuml start :Read data; if (Valid?) then (Yes) :Process data; else (No) :Show error; :Read data; endif stop @enduml ``` **Verdict:** PlantUML's activity diagram syntax is more expressive for complex flows with explicit control structures (`if/else`, `while`). Mermaid's flowchart syntax is more visual and readable at a glance, but achieves conditional logic through diamond nodes rather than language constructs. ### Sequence Diagrams **Mermaid:** ``` sequenceDiagram participant C as Client participant A as API participant D as Database C->>+A: POST /login A->>+D: SELECT user D-->>-A: User found A-->>-C: JWT token ``` **PlantUML:** ``` @startuml participant Client as C participant API as A participant Database as D C -> A: POST /login activate A A -> D: SELECT user activate D D --> A: User found deactivate D A --> C: JWT token deactivate A @enduml ``` **Verdict:** Mermaid wins here for conciseness. The `+/-` activation syntax is far cleaner than PlantUML's explicit `activate/deactivate` blocks. Both tools produce comparable output for sequence diagrams. ### Class Diagrams **Mermaid:** ``` classDiagram class Animal { +String name +makeSound() void } class Dog { +fetch() void } Animal <|-- Dog ``` **PlantUML:** ``` @startuml class Animal { +String name +makeSound() } class Dog { +fetch() } Animal <|-- Dog @enduml ``` **Verdict:** Very similar — both follow UML class diagram conventions closely. PlantUML has more UML-specific features (namespaces, packages, notes on relationships), while Mermaid's output is cleaner by default. ### ER Diagrams **Mermaid:** ``` erDiagram CUSTOMER ||--o{ ORDER : places CUSTOMER { int id PK string name string email UK } ORDER { int id PK int customer_id FK date created_at } ``` **PlantUML:** ``` @startuml entity CUSTOMER { * id : int <> -- * name : varchar * email : varchar <> } entity ORDER { * id : int <> -- * customer_id : int <> * created_at : date } CUSTOMER ||--o{ ORDER : places @enduml ``` **Verdict:** Both are capable. Mermaid's cardinality notation for ER diagrams is identical to PlantUML's. PlantUML's entity notation (`* required` vs optional) offers a bit more expressiveness for data modeling. ## Diagram Types Supported | Diagram Type | Mermaid | PlantUML | |---|---|---| | Flowchart / Activity | ✅ | ✅ | | Sequence | ✅ | ✅ | | Class (UML) | ✅ | ✅ | | State | ✅ | ✅ | | ER / Database | ✅ | ✅ | | Gantt | ✅ | ✅ | | Pie chart | ✅ | ✅ | | Mind map | ✅ | ✅ | | Git graph | ✅ | ❌ | | Timeline | ✅ | ❌ | | Quadrant chart | ✅ | ❌ | | User journey | ✅ | ❌ | | Component / Deployment (UML) | ❌ | ✅ | | Use case | ❌ | ✅ | | Object diagram | ❌ | ✅ | | Network / Nwdiag | ❌ | ✅ | | Timing diagram | ❌ | ✅ | | JSON / YAML visualizer | ❌ | ✅ | | Wireframes (Salt) | ❌ | ✅ | | Math / LaTeX | ❌ | ✅ | **Verdict:** PlantUML wins on total diagram count, especially for UML-heavy use cases. Mermaid covers more modern diagram types (git graphs, timelines, quadrant charts, journey maps) that PlantUML lacks. ## Rendering: Browser vs Server This is a fundamental architectural difference. ### Mermaid — Client-Side Rendering Mermaid is a JavaScript library. Diagrams render in the browser using JavaScript. This means: - **No server required** — Embed Mermaid.js from a CDN and it just works - **No Java needed** — No JVM, no installation complexity - **Native platform support** — GitHub, GitLab, Notion, Obsidian render Mermaid without plugins - **Lightweight integration** — One `
graph TD A[Product Backlog] --> B[Sprint Planning] B --> C[Sprint Execution] C --> D[Sprint Review] D --> E[Retrospective] E --> B
``` > The HTML macro must be enabled by a Confluence administrator. ## Method 3: Export as Image (Universal Fallback) Works in every Confluence version, no admin permission needed: 1. Build your diagram at [MermaidEditor.lol](https://mermaideditor.lol) 2. Export as **PNG** or **SVG** 3. Upload the image to Confluence 4. Add a collapsible code block with the raw Mermaid source for future edits This gives you a visual diagram now, with the source preserved for later. ## Real-World Examples ### System Architecture ```mermaid graph TB subgraph Cloud LB[Load Balancer] subgraph App Tier A1[API Server 1] A2[API Server 2] end subgraph Data Tier DB[(Primary DB)] CACHE[Redis] end end USERS[Users] --> LB LB --> A1 & A2 A1 & A2 --> DB & CACHE ``` ### Incident Response Flow ```mermaid graph TD ALERT[Alert Triggered] --> SEV{Severity?} SEV -- P1/P2 --> PAGE[Page On-Call] SEV -- P3/P4 --> TICKET[Create Ticket] PAGE --> ACK[Acknowledge 15min] ACK --> INV[Investigate] INV --> RES{Resolved?} RES -- Yes --> PIR[Post-Incident Review] RES -- No --> ESC[Escalate to Lead] ESC --> INV PIR --> RUNBOOK[Update Runbook] ``` ### Agile Sprint States ```mermaid stateDiagram-v2 [*] --> Backlog Backlog --> InProgress : Sprint Start InProgress --> InReview : Dev Complete InReview --> Done : Approved InReview --> InProgress : Changes Requested Done --> [*] ``` ## Tips for Teams - **Create a Confluence template** with placeholder Mermaid diagrams for common doc types (architecture, runbook, RFC) - **Always include source** — even when using screenshots, add the Mermaid code in a collapsed section - **Name pages clearly** — "Architecture: Payment Service v2" beats "Payment Diagram" - **Update diagrams in the same session** as the system changes they describe ## Conclusion Mermaid.js brings diagrams-as-code to Confluence. Whether you use a marketplace macro, the HTML macro, or the screenshot workflow, your team can have clean, maintainable technical diagrams in the knowledge base. The real win: diagrams become living documentation that evolves with your codebase. [Create and export Mermaid diagrams for free →](/) ### Mermaid Click Events: Interactive Diagram Tutorial URL: https://mermaideditor.lol/blog/mermaid-click-events-interactive-diagrams Published: 2026-04-21 Updated: 2026-04-21 Description: Learn how to add click events to Mermaid.js diagrams. Link nodes to URLs, trigger JavaScript callbacks, build interactive flowcharts, and create clickable architecture diagrams with copy-paste examples. # Mermaid Click Events: Build Interactive Diagrams (Complete Tutorial) Static diagrams tell a story. **Interactive diagrams let users explore one.** Mermaid.js supports click events that turn any node into a clickable link or a JavaScript callback trigger — perfect for navigation maps, architecture explorers, runbooks, and dashboards. This guide covers everything you need to know about Mermaid click events: syntax, security levels, real-world examples, and the gotchas that trip up most developers. ## What Are Mermaid Click Events? A **click event** binds a node in your Mermaid diagram to one of two actions: 1. **Open a URL** when the node is clicked 2. **Call a JavaScript function** with the node ID as an argument This works in flowcharts, class diagrams, state diagrams, and several other Mermaid diagram types. With one line of syntax, your diagram becomes a navigable interface. ## Basic Syntax: Linking Nodes to URLs The simplest click event opens a URL in the same tab: ```mermaid flowchart LR A[Home] --> B[Docs] B --> C[API Reference] B --> D[Tutorials] click A "https://mermaideditor.lol" "Visit homepage" click B "https://mermaid.js.org/intro/" "Read the docs" click C "https://mermaid.js.org/syntax/flowchart.html" "API reference" click D "https://mermaideditor.lol/blog" "Browse tutorials" ``` The pattern is: ``` click "" "" ``` The tooltip is optional but highly recommended — it appears on hover and improves accessibility. ### Opening Links in a New Tab Use the `_blank` target to open the URL in a new browser tab: ```mermaid flowchart TD A[Dashboard] --> B[GitHub] A --> C[Docs Site] click B "https://github.com" "GitHub" _blank click C "https://mermaideditor.lol" "Docs" _blank ``` Valid targets: `_self`, `_blank`, `_parent`, `_top`. ## JavaScript Callbacks You can also trigger a JavaScript function when a node is clicked. The function receives the node ID as its first argument: ```mermaid flowchart LR A[Order Created] --> B[Payment Pending] B --> C[Shipped] C --> D[Delivered] click A callback "View order details" click B callback "View payment status" click C callback "Track shipment" click D callback "Confirm delivery" ``` In your host page, define the callback: ```javascript window.callback = function(nodeId) { console.log('Clicked node:', nodeId); showModal(nodeId); }; ``` You can also pass extra arguments: ``` click A myFunc "tooltip" arg1 arg2 ``` ## The Security Level Gotcha This is where most developers get stuck. By default, Mermaid runs with `securityLevel: "strict"`, which **disables click events that call JavaScript callbacks**. URL clicks still work, but custom functions won't fire. To enable callbacks, configure Mermaid like this: ```javascript import mermaid from 'mermaid'; mermaid.initialize({ startOnLoad: true, securityLevel: 'loose', // required for callbacks }); ``` ### Security Levels Explained | Level | Click URLs | Click Callbacks | HTML in labels | Use case | |-------|-----------|-----------------|----------------|----------| | `strict` (default) | ✅ | ❌ | ❌ | Untrusted content | | `loose` | ✅ | ✅ | ✅ | Trusted internal docs | | `antiscript` | ✅ | ❌ | sanitized | Mostly trusted | | `sandbox` | rendered in iframe | limited | limited | Maximum isolation | **Rule of thumb:** Use `loose` only when you control the diagram source. Never use it for user-submitted Mermaid code. ## Real-World Example: Clickable Architecture Diagram A practical use case — turn a system architecture diagram into a navigable map where each service links to its README: ```mermaid flowchart TB subgraph Frontend Web[Next.js Web App] Mobile[React Native App] end subgraph Backend API[REST API] Auth[Auth Service] Worker[Background Worker] end subgraph Data DB[(PostgreSQL)] Cache[(Redis)] Queue[RabbitMQ] end Web --> API Mobile --> API API --> Auth API --> DB API --> Cache API --> Queue Queue --> Worker Worker --> DB click Web "https://github.com/org/web" "Web app repo" _blank click Mobile "https://github.com/org/mobile" "Mobile repo" _blank click API "https://github.com/org/api" "API repo" _blank click Auth "https://github.com/org/auth" "Auth service repo" _blank click Worker "https://github.com/org/worker" "Worker repo" _blank ``` Now your architecture diagram doubles as a service catalog. New engineers click a box and land on the right repo. ## Click Events in Class Diagrams Mermaid class diagrams support clicks too — useful for linking classes to source files or API docs: ```mermaid classDiagram class User { +String email +login() +logout() } class Order { +Number total +place() } User --> Order : places click User "https://github.com/org/app/blob/main/models/user.ts" "User model source" click Order "https://github.com/org/app/blob/main/models/order.ts" "Order model source" ``` ## Click Events in State Diagrams State diagrams can link each state to its handler documentation: ```mermaid stateDiagram-v2 [*] --> Pending Pending --> Processing Processing --> Completed Processing --> Failed Completed --> [*] Failed --> [*] click Pending "/docs/states/pending" "Pending state docs" click Processing "/docs/states/processing" "Processing logic" click Failed "/docs/states/failed" "Failure recovery" ``` ## Common Pitfalls **1. Clicks not firing in GitHub READMEs** GitHub renders Mermaid with strict security and strips click handlers entirely. Click events only work in your own apps and docs sites where you control the Mermaid config. **2. "click" recognized as a node** Make sure the `click` directive is on its own line, not inside a node definition. The parser is whitespace sensitive. **3. Tooltips not showing** Tooltips require the URL or callback to be present first. The order is: `click `. **4. URLs with special characters** Wrap URLs in double quotes and URL-encode query strings. Spaces especially will break parsing. **5. Callbacks not defined yet** Mermaid renders before your script runs? Define callbacks on `window` before calling `mermaid.run()`, or use `startOnLoad: false` and trigger rendering manually. ## Styling Clickable Nodes Signal that a node is clickable using a `classDef`: ```mermaid flowchart LR A[Home] --> B[Docs] B --> C[API] classDef clickable fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,cursor:pointer class A,B,C clickable click A "/" "Home" click B "/docs" "Documentation" click C "/api" "API reference" ``` The `cursor:pointer` style is the visual cue users expect. ## When to Use Click Events Great fits: - **Service catalogs** — architecture diagrams that link to repos - **Runbooks** — flowcharts where each step links to a Slack channel or wiki page - **API maps** — endpoint diagrams linking to OpenAPI docs - **Onboarding diagrams** — clickable org charts or product tours - **Roadmaps** — milestone nodes linking to GitHub projects or Linear issues When not to bother: - Static images exported to PDF or PNG (clicks don't survive export) - GitHub README diagrams (strict mode strips them) - Print materials ## Conclusion Click events are one of Mermaid's most underused features. With one extra line per node, you can transform a flat diagram into a navigation interface — no extra libraries, no SVG editing, no JavaScript framework required. Start with simple URL links, graduate to JavaScript callbacks once you need richer interactions, and remember to set `securityLevel: "loose"` only on trusted content. [Try interactive Mermaid diagrams in our free editor →](/) ### Mermaid C4 Diagrams: Architecture as Code Guide URL: https://mermaideditor.lol/blog/mermaid-c4-architecture-diagrams Published: 2026-04-24 Updated: 2026-04-24 Description: Learn how to create C4 model architecture diagrams with Mermaid.js. Covers Context, Container, Component, and Dynamic diagrams with copy-paste examples for documenting software systems. # Mermaid C4 Diagrams: Document Software Architecture as Code (2026 Guide) Architecture diagrams age fast. The system evolves, the diagram doesn't, and six months later you're staring at a Lucidchart file that no longer matches reality. **The C4 model fixes this by giving you a structured way to describe software architecture — and Mermaid.js lets you write those diagrams as code that lives next to your source.** This guide walks through Mermaid's C4 diagram support: what each level means, the syntax, and complete copy-paste examples for Context, Container, Component, and Dynamic diagrams. ## What Is the C4 Model? The **C4 model**, created by Simon Brown, describes software architecture at four zoom levels: 1. **Context** — Your system as a single box, surrounded by users and external systems 2. **Container** — The major deployable units inside your system (web app, API, database, queue) 3. **Component** — The internal building blocks of a single container (controllers, services, repositories) 4. **Code** — Class-level detail (usually skipped — generated from source) Think of it like Google Maps: zoom out for the country, zoom in for the street. Each level answers different questions for different audiences. ## Why Mermaid C4 Beats Drawing Tools C4 diagrams in Lucidchart, Visio, or draw.io look great — until someone refactors. Mermaid's text-based C4 syntax means: - **Diagrams live in your repo** next to the code they describe - **Pull requests update the diagram** in the same commit as the architecture change - **Diffs are reviewable** — you can see exactly what changed - **No license fees**, no proprietary file formats, no broken exports - **Renders natively** in GitHub, GitLab, Notion, and Obsidian > ⚠️ **Heads up:** Mermaid's C4 support is still marked experimental as of 2026. The syntax works well in most renderers but may evolve. Always test in your target environment. ## C4 Context Diagram (Level 1) The Context diagram shows your system as a black box and identifies who uses it and what it depends on. This is the diagram you show executives, new hires, or anyone asking "what does this system do?" ```mermaid C4Context title System Context Diagram for Online Banking Person(customer, "Banking Customer", "A retail customer of the bank") Person(support, "Support Agent", "Helps customers with account issues") System(banking, "Internet Banking System", "Allows customers to view balances, transfer funds, and pay bills") System_Ext(mainframe, "Mainframe Banking System", "Stores all core banking information") System_Ext(email, "Email System", "Sends transactional emails to customers") Rel(customer, banking, "Uses", "HTTPS") Rel(support, banking, "Manages", "HTTPS") Rel(banking, mainframe, "Reads/Writes accounts", "XML/HTTPS") Rel(banking, email, "Sends emails", "SMTP") ``` **Key elements:** - `Person()` — A human actor (employee, customer, admin) - `System()` — Your system, the one being documented - `System_Ext()` — A third-party or legacy system you depend on - `Rel()` — A relationship with a label and optional protocol ## C4 Container Diagram (Level 2) Zoom in one level and you see the **containers** — the runnable units that make up your system. A container is anything that needs to be deployed: a Spring Boot service, a Next.js app, a Postgres database, a Redis cache, a message queue. ```mermaid C4Container title Container Diagram for Internet Banking System Person(customer, "Customer", "A retail banking customer") System_Boundary(banking, "Internet Banking System") { Container(web, "Web Application", "Next.js, TypeScript", "Delivers the banking UI") Container(mobile, "Mobile App", "React Native", "iOS and Android client") Container(api, "API Application", "Node.js, Express", "Provides banking functionality via JSON/HTTPS") ContainerDb(db, "Database", "PostgreSQL", "Stores user accounts, sessions, audit logs") Container(queue, "Message Queue", "RabbitMQ", "Async event processing") } System_Ext(mainframe, "Mainframe", "Core banking ledger") Rel(customer, web, "Uses", "HTTPS") Rel(customer, mobile, "Uses", "HTTPS") Rel(web, api, "Calls", "JSON/HTTPS") Rel(mobile, api, "Calls", "JSON/HTTPS") Rel(api, db, "Reads/Writes", "SQL") Rel(api, queue, "Publishes events", "AMQP") Rel(api, mainframe, "Fetches account data", "XML/HTTPS") ``` **New elements:** - `System_Boundary()` — Visual boundary around your containers - `Container()` — A deployable unit with technology and purpose - `ContainerDb()` — A data store (renders with a different shape) This is the diagram developers will use most. It answers "what runs where, and how do they talk?" ## C4 Component Diagram (Level 3) Go one level deeper and you're inside a single container, looking at its components — the controllers, services, and repositories that make it tick. ```mermaid C4Component title Component Diagram for API Application Container_Boundary(api, "API Application") { Component(auth, "Auth Controller", "Express Router", "Handles login, signup, token refresh") Component(accounts, "Accounts Controller", "Express Router", "Account balance and history endpoints") Component(transfers, "Transfers Controller", "Express Router", "Money movement endpoints") Component(authSvc, "Auth Service", "TypeScript class", "JWT issuance, password hashing") Component(accountSvc, "Account Service", "TypeScript class", "Business rules for accounts") Component(repo, "Account Repository", "Prisma ORM", "Persistence layer") } ContainerDb(db, "Database", "PostgreSQL") Rel(auth, authSvc, "Uses") Rel(accounts, accountSvc, "Uses") Rel(transfers, accountSvc, "Uses") Rel(accountSvc, repo, "Uses") Rel(repo, db, "Reads/Writes", "SQL") ``` Component diagrams are useful for onboarding new engineers to a service or planning a refactor. Don't draw one for every container — only the ones complex enough to need it. ## C4 Dynamic Diagram Dynamic diagrams show how components collaborate to handle a specific scenario — like a user login or a checkout flow. They're numbered to show sequence. ```mermaid C4Dynamic title Dynamic Diagram: Customer Money Transfer Person(customer, "Customer") Container(web, "Web App", "Next.js") Container(api, "API", "Node.js") ContainerDb(db, "Database", "PostgreSQL") Container(queue, "Queue", "RabbitMQ") Rel(customer, web, "1. Initiates transfer") Rel(web, api, "2. POST /transfers") Rel(api, db, "3. Validate balance") Rel(api, db, "4. Debit source account") Rel(api, queue, "5. Publish TransferRequested event") Rel(api, web, "6. Return confirmation") ``` Use Dynamic diagrams sparingly — for the two or three flows that everyone needs to understand. ## Best Practices for C4 in Mermaid **1. Start at Context, stop at Container.** Most teams never need Component diagrams. Don't over-document. **2. Keep one diagram per file.** Store them in `/docs/architecture/` next to the code: ``` docs/ architecture/ 01-context.md 02-container.md 03-component-api.md ``` **3. Update diagrams in the same PR as the code change.** Make it part of your definition of done. **4. Use technology labels consistently.** "Next.js, TypeScript" beats "web frontend" every time. **5. Name relationships with verbs.** "Reads from", "Publishes to", "Authenticates against" — not just arrows. ## C4 vs Plain Mermaid Flowcharts A flowchart can render an architecture diagram — but C4 enforces a vocabulary. Everyone on the team uses the same words for the same concepts: Person, System, Container, Component. That shared vocabulary is what makes C4 valuable, not the visual style. If your team is small and your system is simple, a plain flowchart is fine. The moment you have multiple services, multiple teams, or external auditors asking questions — switch to C4. ## Conclusion The C4 model + Mermaid.js gives you architecture documentation that actually stays current. Diagrams as code, version controlled, reviewed in pull requests, and rendered natively in every developer tool you use. Start with a Context diagram for your main system this week. Add a Container diagram next sprint. That's usually enough — and it's infinitely better than the stale Visio file nobody opens. [Build C4 architecture diagrams in our free Mermaid editor →](/) ### Mermaid Sankey Diagrams: Flows, Budgets & Energy URL: https://mermaideditor.lol/blog/mermaid-sankey-diagram-tutorial Published: 2026-04-28 Updated: 2026-04-28 Description: Learn how to build Mermaid.js Sankey diagrams to visualize data flows, budgets, energy usage, and conversion funnels. Complete syntax guide with copy-paste examples. # Mermaid Sankey Diagrams: Visualize Flows, Budgets & Energy Data Sankey diagrams are the go-to visualization for showing how a quantity flows from one set of categories to another. Energy distribution, website conversion funnels, budget allocation, supply chains — anywhere a value splits, merges, or transforms, a Sankey diagram tells the story better than a stacked bar chart ever could. The good news: since Mermaid.js v10.3, you can build production-ready Sankey diagrams in **plain text**, version-controlled alongside your code, no Tableau or D3.js required. This guide walks you through the syntax, common patterns, and real-world examples. ## What Is a Sankey Diagram? A Sankey diagram is a flow diagram where the **width of each link is proportional to the quantity it represents**. Wider arrows mean more flow. They were originally invented in 1898 by Captain Matthew Sankey to visualize steam engine energy efficiency, and they remain unbeaten for showing where things go and how much. Classic use cases: - **Energy budgets** — input fuel → useful work + losses - **Website analytics** — traffic source → page → conversion - **Financial flows** — revenue → departments → expense categories - **Supply chains** — raw materials → factories → distributors → customers - **User journeys** — landing page → signup → activation → retention ## Mermaid Sankey Syntax (The Basics) Mermaid uses a CSV-style format for Sankey diagrams. Each line is one flow: `source,target,value`. ```mermaid sankey-beta Marketing,Website,1000 Website,Signup,400 Website,Bounce,600 Signup,Activated,250 Signup,Churned,150 ``` That's it. No nodes to declare, no styling required. The diagram type is `sankey-beta` (still officially in beta, but stable in v10.3+). A few rules to remember: - **Three columns per row:** source, target, numeric value - **No header row** — just data - **Quote labels with commas or spaces using double quotes:** `"Paid Ads",Website,500` - **Values must be positive numbers** — Sankey diagrams can't represent negative flows ## Real-World Example 1: Marketing Funnel Here's a multi-stage acquisition funnel that splits traffic by source and tracks it through to paid conversion: ```mermaid sankey-beta "Google Ads",Landing,4500 "Organic Search",Landing,3200 "LinkedIn",Landing,800 "Email",Landing,500 Landing,Trial,2100 Landing,Bounce,6900 Trial,Activated,1400 Trial,"Trial Drop-off",700 Activated,"Paid Customer",420 Activated,"Free Forever",980 ``` In one glance you see: organic search and Google Ads dominate top-of-funnel, but only ~30% of activated users convert to paid. That's a clearer story than any spreadsheet. ## Real-World Example 2: Energy Flow The original Sankey use case — visualizing how a system uses (and wastes) energy: ```mermaid sankey-beta "Natural Gas","Power Plant",100 "Power Plant","Electricity",38 "Power Plant","Heat Loss",62 "Electricity","Buildings",22 "Electricity","Industry",12 "Electricity","Transmission Loss",4 ``` The widths instantly reveal that 62% of input energy is lost as heat at the power plant — the kind of insight a stacked bar chart hides. ## Real-World Example 3: Budget Allocation Quarterly budget breakdown for a small SaaS company: ```mermaid sankey-beta Revenue,Engineering,45000 Revenue,Marketing,28000 Revenue,"Sales & CS",18000 Revenue,Operations,9000 Engineering,Salaries,38000 Engineering,"Cloud Infra",7000 Marketing,"Paid Ads",18000 Marketing,Content,6000 Marketing,Tools,4000 ``` Great for board decks, investor updates, and internal alignment. ## Styling and Themes Sankey diagrams inherit Mermaid's **theme system**. Switch the theme with an init directive: ```mermaid %%{init: {"theme": "dark"}}%% sankey-beta Alpha,Beta,10 Alpha,Gamma,20 Beta,Delta,8 ``` Available themes: `default`, `dark`, `forest`, `neutral`, and `base` (fully customizable). For brand colors, use the `base` theme with `themeVariables`: ```mermaid %%{init: {"theme":"base","themeVariables":{"primaryColor":"#2563eb","primaryTextColor":"#fff"}}}%% sankey-beta Input,Output,100 ``` Note: link colors in Sankey diagrams are auto-generated from the source node — you currently can't color individual links manually. If you need that level of control, fall back to D3.js. ## Where Mermaid Sankey Renders Natively - **GitHub Markdown** — wrap in a `mermaid` code fence and it renders in any README - **GitLab** — supported in `.md` files - **Notion** — paste into a Mermaid code block - **Obsidian** — works out of the box in preview mode - **Docusaurus & MkDocs** — with the Mermaid plugin enabled - **VS Code** — via the Markdown Preview Mermaid Support extension If the platform supports Mermaid v10.3+, your Sankey diagram works. ## Common Pitfalls **1. Cycles aren't supported.** A Sankey is a directed acyclic flow. If `A → B → A`, the renderer will fail or produce nonsense. Restructure your data into stages. **2. Quote labels with spaces.** `Paid Ads,Website,500` will break. Use `"Paid Ads",Website,500`. **3. Mismatched totals look wrong.** If 1000 enters node X but only 800 leaves, the diagram still renders — but the imbalance shows visually as a stub. Either accept it (it represents "loss" or "unaccounted") or balance your data. **4. Too many nodes = unreadable.** Sankey diagrams shine with 5–25 nodes. Beyond that, group related items into parent categories. ## When to Use Sankey vs Other Diagrams | Use Sankey when... | Use something else when... | |--------------------|----------------------------| | Showing **proportional flow** between stages | Showing process steps → use a **flowchart** | | Comparing **input vs output volumes** | Showing time series → use **xychart** or Gantt | | Visualizing **funnels and conversions** | Showing relationships → use **ER diagram** | | Highlighting **losses or splits** | Showing hierarchies → use **mindmap** | ## Conclusion Mermaid Sankey diagrams turn flow data into instantly readable visuals — funnels, budgets, energy, supply chains — all in plain text that lives next to your code. The syntax is dead simple (`source,target,value`), it renders natively in GitHub and most documentation platforms, and you can ship a polished flow chart in under five minutes. Next time you're tempted to embed a screenshot of a Tableau Sankey in your docs, write it in Mermaid instead. Future-you (and every reviewer of that pull request) will thank you. [Build your Sankey diagram in our free Mermaid editor →](/) ### Mermaid XY Charts: Build Bar & Line Graphs in Plain Text URL: https://mermaideditor.lol/blog/mermaid-xy-chart-tutorial Published: 2026-05-05 Updated: 2026-07-04 Description: Learn how to build Mermaid.js XY charts — bar and line graphs in pure text. Complete syntax guide with axis configuration, multi-series examples, and styling tips. # Mermaid XY Charts: Build Bar & Line Graphs in Plain Text For years, Mermaid.js was the kingdom of flowcharts, sequence diagrams, and architecture docs — but if you wanted a simple bar chart in your README, you were stuck embedding a screenshot from Excel. Not anymore. Since v10.5, Mermaid ships with **xychart-beta**, a diagram type built specifically for bar charts and line graphs in plain text. No D3.js. No Chart.js setup. No PNGs going stale every quarter. Just write the data, commit it, and GitHub renders a real chart inside your Markdown. This guide walks you through everything: syntax, axis configuration, multi-series charts, theming, and where XY charts fit in your documentation stack. ## What Is an XY Chart in Mermaid? An XY chart is a 2D plot with an x-axis and a y-axis. Mermaid's `xychart-beta` supports two visualization styles: - **Bar charts** — categorical x-axis, numeric y-axis - **Line charts** — same axes, plotted as a continuous line You can also **combine them** in a single chart (bars + a trend line on top) — exactly like Excel combo charts, but in version-controlled text. Use cases that fit perfectly: - Monthly revenue, signups, or active users in a status report - Performance benchmarks (latency, throughput) in a tech postmortem - Survey results or simple distributions - Sprint velocity over time in retrospectives - Cost trends in cloud billing reviews ## Basic Syntax: Your First Bar Chart Here's the minimum viable XY chart — a bar chart of monthly signups: ```mermaid xychart-beta title "Monthly Signups 2026" x-axis [Jan, Feb, Mar, Apr, May] y-axis "Signups" 0 --> 1000 bar [240, 380, 520, 610, 890] ``` Three things to notice: 1. **`x-axis`** takes a comma-separated list of category labels in square brackets. 2. **`y-axis`** takes a label, then a numeric range with `min --> max`. 3. **`bar`** takes the data values in the same order as the x-axis categories. That's a complete chart in five lines. ## Switching to a Line Chart Same data, swap `bar` for `line`: ```mermaid xychart-beta title "Monthly Signups 2026" x-axis [Jan, Feb, Mar, Apr, May] y-axis "Signups" 0 --> 1000 line [240, 380, 520, 610, 890] ``` That's it. Mermaid handles axis ticks, grid lines, and colors automatically. ## Combo Charts: Bars + Line on the Same Axes This is where xychart-beta starts to feel powerful. Stack a line on top of bars to show a trend: ```mermaid xychart-beta title "Revenue vs Target" x-axis [Q1, Q2, Q3, Q4] y-axis "USD (thousands)" 0 --> 200 bar [85, 110, 145, 178] line [100, 120, 140, 160] ``` Bars = actuals. Line = target. The visual story ("we're beating target") jumps out instantly. You can stack multiple bar series too — Mermaid will color them differently: ```mermaid xychart-beta title "Sprint Velocity by Team" x-axis ["Sprint 1", "Sprint 2", "Sprint 3", "Sprint 4"] y-axis "Story Points" 0 --> 80 bar [45, 52, 48, 60] bar [30, 38, 42, 50] ``` ## Horizontal Bar Charts Need bars going sideways (great for long category labels)? Use the `horizontal` orientation: ```mermaid xychart-beta horizontal title "Top 5 Marketing Channels" x-axis ["Organic Search", "Paid Ads", "Email", "Referral", "Social"] y-axis "Leads" 0 --> 500 bar [420, 310, 240, 180, 95] ``` The `horizontal` keyword goes right after `xychart-beta` on the first line. ## Numeric X-Axis (Time Series Style) For line charts where the x-axis is itself a number range — like time, version numbers, or load levels — use a numeric range instead of category labels: ```mermaid xychart-beta title "API p95 Latency by Concurrent Users" x-axis "Concurrent Users" 0 --> 1000 y-axis "Latency (ms)" 0 --> 500 line [80, 95, 130, 180, 240, 310, 380, 450] ``` Mermaid distributes your data points evenly across the numeric range. ## Theming and Colors XY charts inherit Mermaid's theme system. Switch themes with an init directive: ```mermaid %%{init: {"theme": "dark"}}%% xychart-beta title "Dark Mode Chart" x-axis [Mon, Tue, Wed, Thu, Fri] y-axis "Errors" 0 --> 50 bar [12, 8, 22, 5, 18] ``` For brand-specific colors, override `xyChart` theme variables: ```mermaid %%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#2563eb, #f59e0b"}}}}%% xychart-beta title "Custom Brand Colors" x-axis [Jan, Feb, Mar, Apr] y-axis "MRR" 0 --> 100 bar [40, 55, 70, 85] line [50, 60, 75, 90] ``` The `plotColorPalette` is a comma-separated list — Mermaid cycles through it for each series. ## Where XY Charts Render Natively - **GitHub** — works in any `.md` file with a `mermaid` code fence (Mermaid v10.5+) - **GitLab** — supported in repository markdown - **Notion** — paste into a Mermaid code block - **Obsidian** — renders in preview mode - **VS Code** — Markdown Preview Mermaid Support extension - **Docusaurus, MkDocs, Hugo** — with the Mermaid plugin enabled If the platform supports Mermaid v10.5 or later, your XY chart works. ## XY Chart vs Other Mermaid Diagrams | Use xychart-beta when... | Use something else when... | |--------------------------|----------------------------| | Plotting **numeric trends** over categories | Showing **flows** → use Sankey | | Comparing **2–3 metric series** | Showing **proportions** of a whole → use pie | | Visualizing **performance benchmarks** | Showing **process steps** → use flowchart | | Reporting **time-series KPIs** | Showing **categorized rankings** → use quadrant | ## Common Pitfalls **1. Mismatched array lengths.** If your x-axis has 5 categories, your bar/line array needs exactly 5 values. Otherwise you'll get a render error or a chart with empty slots. **2. Negative y-axis ranges.** Use them — they work. `y-axis "Profit" -50 --> 200` is valid. **3. Quoting category labels with spaces.** Wrap them in double quotes: `x-axis ["Q1 2026", "Q2 2026"]`. **4. Too many data points.** XY charts shine with 4–20 points. Beyond ~30, labels overlap and the chart becomes noisy. Aggregate first (weekly → monthly), or switch to a real BI tool. **5. Forgetting the `-beta` suffix.** It's still officially `xychart-beta`. Just `xychart` won't parse. ## When NOT to Use Mermaid XY Charts Let's be honest — Mermaid XY isn't trying to replace Tableau, Looker, or Plotly. Skip it when you need: - Tooltips on hover - Drill-down interactions - Logarithmic axes (not yet supported) - More than ~5 data series in one chart - Pixel-perfect publication graphics For those cases, embed an interactive dashboard. For everything else — quarterly recaps, status reports, design docs, postmortems — Mermaid XY is faster, version-controlled, and renders everywhere your code does. ## Conclusion Mermaid `xychart-beta` finally closes the last big gap in text-based diagramming: numerical charts. Bars, lines, combos, horizontal layouts, custom palettes — all in plain text, all version-controlled, all rendered natively in GitHub and the rest of your documentation stack. The next time you're tempted to paste a screenshot of an Excel chart into a README, write five lines of `xychart-beta` instead. Your future self — the one rebasing that doc six months from now — will thank you. [Build your XY chart in our free Mermaid editor →](/) ## Additional Guide: Mermaid XY Chart Tutorial: Plot Bar and Line Charts in Code Mermaid.js added a powerful new diagram type called **xychart-beta** that lets you plot bar charts and line charts directly in Markdown using plain text. No spreadsheet, no image exports — just code. This tutorial covers the full syntax, real-world examples, and tips to get clean, readable charts inside any tool that renders Mermaid diagrams. ## What Is the Mermaid XY Chart? The `xychart-beta` type (introduced in Mermaid v10.3) renders Cartesian charts with a horizontal X axis and a vertical Y axis. It supports two series types: - **bar** — vertical bars for comparing categories - **line** — connected points for showing trends over time You can combine both on the same chart, which makes it useful for things like comparing actual vs. target metrics. ## Basic Syntax Every XY chart follows this structure: ```mermaid xychart-beta title "Monthly Revenue" x-axis [Jan, Feb, Mar, Apr, May, Jun] y-axis "Revenue (USD)" 0 --> 50000 bar [12000, 18000, 23000, 19000, 31000, 42000] ``` Key elements: - **title** — optional chart heading - **x-axis** — list of category labels in square brackets - **y-axis** — optional label and min/max range (`0 --> 50000`) - **bar** or **line** — data series as a comma-separated list ## Bar Chart Example: Sales by Product ```mermaid xychart-beta title "Q2 Sales by Product" x-axis ["Widget A", "Widget B", "Widget C", "Widget D"] y-axis "Units Sold" 0 --> 500 bar [320, 180, 450, 270] ``` Use this pattern for any comparison across discrete categories — product sales, support tickets by team, test scores by class. ## Line Chart Example: Weekly Active Users ```mermaid xychart-beta title "Weekly Active Users" x-axis ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"] y-axis "Users" 0 --> 10000 line [2400, 3100, 4500, 4200, 6800, 8900] ``` Line charts are better than bar charts when you want to show momentum or growth over time. ## Combining Bar and Line on One Chart You can overlay series by adding both `bar` and `line` blocks: ```mermaid xychart-beta title "Revenue vs. Target" x-axis [Jan, Feb, Mar, Apr, May] y-axis "USD" 0 --> 60000 bar [28000, 32000, 41000, 38000, 52000] line [30000, 30000, 35000, 40000, 45000] ``` The bar series shows actuals; the line shows the monthly target. This dual-series approach is popular in engineering dashboards and sprint retrospectives. ## Real-World Use Cases **Sprint velocity** — plot story points completed per sprint (bar) with a rolling average (line) to spot team trends in your project README. **API response time** — chart p50/p95 latency over deploys without leaving your architecture documentation. **CI pipeline duration** — track build times week over week directly in your repo's CHANGELOG. **Feature adoption** — embed in a product spec document to show activation rate ramp after a launch. ## Tips and Gotchas **Use quotes around multi-word labels.** If an x-axis label has spaces, wrap it in double quotes: `["Week 1", "Week 2"]`. Without quotes, Mermaid may parse the space as a delimiter and produce unexpected output. **Set explicit y-axis ranges.** If you skip the `0 --> N` range, Mermaid auto-scales, which can make small differences look dramatic. For honest data visualization, always set a baseline of `0`. **xychart-beta is still a beta feature.** The `-beta` suffix means the syntax may shift in future Mermaid releases. If you pin a Mermaid version in your project (e.g., in a `package.json`), the chart will stay stable. **Theme support is limited.** XY charts respect the global Mermaid theme (`default`, `dark`, `forest`, etc.) for background and axis colors, but per-series color overrides via `%%{init}%%` directives are not fully supported yet. ## Customizing with Init Directives You can nudge chart dimensions and colors using the init block at the top: ```mermaid %%{init: {'theme': 'dark', 'xyChart': {'width': 800, 'height': 400}}}%% xychart-beta title "Dark Mode Chart" x-axis [Q1, Q2, Q3, Q4] y-axis "Revenue" 0 --> 100000 bar [45000, 62000, 71000, 89000] ``` Setting `width` and `height` is especially helpful when embedding charts in documentation sites where the default canvas feels too small. ## Where to Use XY Charts Mermaid XY charts render anywhere Mermaid is supported: - **GitHub** — in README files, issues, pull request descriptions, and wikis (fenced ```mermaid blocks) - **GitLab** — same fenced code block support - **Notion** — via the /code block with Mermaid selected - **Obsidian** — with the Mermaid plugin enabled - **Docusaurus / MkDocs** — via official Mermaid integrations For instant preview and PNG/SVG export without any setup, open **[MermaidEditor.lol](https://mermaideditor.lol)** — paste the code and your chart renders immediately. ## Quick Reference | Element | Syntax | Required? | |---|---|---| | Diagram type | `xychart-beta` | Yes | | Title | `title "My Chart"` | No | | X axis | `x-axis [A, B, C]` | Yes | | Y axis | `y-axis "Label" 0 --> 100` | No | | Bar series | `bar [10, 20, 30]` | One of these | | Line series | `line [10, 20, 30]` | One of these | ## Try It Now Copy any example above and paste it into the **[Mermaid Live Editor →](https://mermaideditor.lol)**. Tweak the numbers, switch `bar` to `line`, change the theme — the preview updates instantly. For more diagram types: - [Mermaid Pie Chart Tutorial](/blog/mermaid-pie-chart-tutorial) - [Mermaid Gantt Chart Examples](/blog/mermaid-gantt-chart-examples) - [Mermaid Diagram Types Overview](/blog/mermaid-diagram-types) ### Export Mermaid Diagrams to PNG, SVG, and PDF URL: https://mermaideditor.lol/blog/export-mermaid-diagrams-png-svg-pdf Published: 2026-05-08 Updated: 2026-05-08 Description: A complete guide to exporting Mermaid.js diagrams as PNG, SVG, or PDF — using the live editor, CLI, browser, and code. Includes high‑resolution and transparent background tips. # How to Export Mermaid Diagrams to PNG, SVG, and PDF (2026 Guide) Mermaid is great for writing diagrams as code — but eventually you need to **get the picture out**. A PNG for a Notion page. An SVG for a docs site. A PDF for a stakeholder deck. This guide walks through every reliable way to export Mermaid diagrams in 2026, from one‑click downloads to scriptable CLI pipelines. ## Why Export Matters Mermaid diagrams render beautifully inside GitHub, GitLab, Notion, Obsidian, and Docusaurus — but the moment you need to: - Paste a diagram into a Google Doc, Slides, or Figma - Embed it in a PDF report or investor deck - Send a clean image to a non‑technical stakeholder - Use it as a hero image on your blog …you need a real file. PNG for raster, SVG for vector scaling, PDF for documents. ## Method 1: One‑Click Export from the Live Editor (Easiest) The fastest path is using a browser‑based Mermaid editor. On [mermaideditor.lol](https://mermaideditor.lol) you can paste any Mermaid code and download as PNG or SVG instantly: ```mermaid flowchart LR A[Write Mermaid] --> B[Preview] B --> C{Download} C --> D[PNG] C --> E[SVG] C --> F[Copy as Image] ``` This works for every diagram type — flowcharts, sequence, ER, class, mindmap, Gantt, quadrant, Sankey, XY chart. No install, no CLI, no Node.js. **When to use it:** quick one‑offs, screenshots for Slack, embedding in a doc. ## Method 2: Mermaid CLI (mmdc) for Automation For batch exports or CI pipelines, use the official **Mermaid CLI** (`@mermaid-js/mermaid-cli`). It runs headless Chromium under the hood and outputs PNG, SVG, or PDF. ### Install ```bash npm install -g @mermaid-js/mermaid-cli ``` ### Export to PNG ```bash mmdc -i diagram.mmd -o diagram.png ``` ### Export to SVG ```bash mmdc -i diagram.mmd -o diagram.svg ``` ### Export to PDF ```bash mmdc -i diagram.mmd -o diagram.pdf ``` ### High‑Resolution PNG (for retina screens / print) ```bash mmdc -i diagram.mmd -o diagram.png -w 3840 -H 2160 -s 3 ``` - `-w` width in pixels - `-H` height in pixels - `-s` scale factor (3 = 3x DPI) ### Transparent Background ```bash mmdc -i diagram.mmd -o diagram.png -b transparent ``` ### Dark Theme Export ```bash mmdc -i diagram.mmd -o diagram.png -t dark -b "#0f172a" ``` ## Method 3: Export from the Browser (Right‑Click + DevTools) If your diagram already renders on a webpage (GitHub README, Docusaurus site, Notion), you can grab the SVG directly: 1. Right‑click the rendered diagram → **Inspect** 2. Find the `` element in the DOM 3. Right‑click the node → **Copy → Copy outerHTML** 4. Paste into a file named `diagram.svg` For PNG, take a screenshot — but for crisp output, prefer the SVG → convert path. ## Method 4: Convert SVG to PNG / PDF Programmatically Once you have the SVG, you can convert it to anything using standard tools. ### SVG → PNG with ImageMagick ```bash convert -density 300 diagram.svg diagram.png ``` ### SVG → PDF with rsvg-convert ```bash rsvg-convert -f pdf -o diagram.pdf diagram.svg ``` ### SVG → PNG with Inkscape (best quality) ```bash inkscape diagram.svg --export-type=png --export-dpi=300 -o diagram.png ``` ## Method 5: Programmatic Export with Node.js If you're building a docs pipeline, use the Mermaid CLI as a library: ```javascript import { run } from '@mermaid-js/mermaid-cli'; await run( 'input.mmd', 'output.png', { puppeteerConfig: { headless: 'new' }, mermaidConfig: { theme: 'dark' }, backgroundColor: 'transparent', width: 1920, height: 1080 } ); ``` Drop this into a CI job and your docs site can regenerate every diagram on every push. ## Method 6: Export Mermaid in VS Code The **Markdown Preview Mermaid Support** and **Mermaid Editor** extensions both add export buttons. Open any `.md` or `.mmd` file, preview it, and click Export → PNG / SVG. For batch exports, run `mmdc` from the integrated terminal — same flags as Method 2. ## Choosing the Right Format | Format | Best For | Avoid When | |--------|----------|------------| | **SVG** | Web embeds, docs sites, scaling without quality loss | Email clients (poor support), Office docs | | **PNG** | Notion, Slack, Google Docs, social media, screenshots | When you'll resize aggressively | | **PDF** | Investor decks, formal reports, print | Web pages | Rule of thumb: **export SVG first, convert as needed.** SVG is the lossless source. ## Common Export Problems and Fixes **1. Blurry PNG.** You exported at 1x scale. Use `-s 2` or `-s 3` with mmdc, or set `width=1920` minimum. **2. Cut‑off edges.** Add padding via the CLI: `mmdc -i d.mmd -o d.png --pdfFit` — or wrap the SVG in a viewBox with extra margin. **3. Fonts look wrong.** mmdc uses the system fonts inside Chromium. Install your brand font system‑wide, or pass a custom CSS via `-C custom.css`. **4. Dark background showing in PNG.** Pass `-b white` or `-b transparent`. **5. Huge SVG file size.** Mermaid embeds inline styles per node. Run `svgo diagram.svg` to compress 60–80% with no visual loss. ## Automating Diagram Exports in CI A realistic pipeline for a docs repo: ```mermaid flowchart LR A[Push to main] --> B[GitHub Actions] B --> C[Install mmdc] C --> D[Find *.mmd files] D --> E[Export to /public/diagrams/*.svg] E --> F[Commit & deploy] ``` Example GitHub Actions step: ```yaml - name: Export Mermaid diagrams run: | npm install -g @mermaid-js/mermaid-cli for f in docs/diagrams/*.mmd; do mmdc -i "$f" -o "public/diagrams/$(basename "$f" .mmd).svg" -t default done ``` Now every diagram in your repo is auto‑exported on every push. No more stale screenshots. ## TL;DR - **Quickest:** paste into [mermaideditor.lol](https://mermaideditor.lol) → click PNG/SVG download. - **Scriptable:** `mmdc -i in.mmd -o out.png -s 3 -b transparent`. - **Best quality:** export SVG, convert with Inkscape or rsvg. - **Automated:** wire mmdc into CI and never ship a stale screenshot again. Mermaid's whole point is **diagrams as code**. Treat exports the same way — version‑controlled, scriptable, and reproducible. ## Want Export-Ready Templates? If you export Mermaid diagrams often, join the [Mermaid Templates Pro early-access list](/templates/pro). The pack will include 100+ copy-paste diagrams designed for engineering docs, README files, architecture notes, and product specs. ### Mermaid Requirement Diagram: Document Requirements as Code URL: https://mermaideditor.lol/blog/mermaid-requirement-diagram-guide Published: 2026-05-12 Updated: 2026-05-12 Description: Learn how to create requirement diagrams in Mermaid.js to document system requirements, trace dependencies, and link specs directly in your codebase. # Mermaid Requirement Diagram: Document Requirements as Code Most teams manage requirements in sprawling spreadsheets, Jira tickets, or Word docs that go stale the moment a developer closes the tab. There's a better way. Mermaid's **requirementDiagram** type lets you define requirements, risks, and verification methods right next to your code — and render them as clean, linkable diagrams in any Markdown-aware tool. This guide walks through everything you need to start using Mermaid requirement diagrams today. ## What Is a Mermaid Requirement Diagram? A **requirementDiagram** is a structured way to capture: - **Requirements** — what the system must do - **Elements** — the components that fulfill requirements - **Relationships** — traces between requirements and elements (satisfies, contains, copies, derives, refines, verifies) It's based loosely on SysML requirement diagrams but much simpler to write. The output is a visual map that shows *which part of your system fulfills which requirement*. ## Basic Requirement Diagram Syntax Here's a minimal example showing a login feature requirement: ```mermaid requirementDiagram requirement LoginRequirement { id: REQ-001 text: The system shall authenticate users with email and password. risk: high verifymethod: test } element AuthService { type: component docref: src/auth/AuthService.ts } AuthService - satisfies -> LoginRequirement ``` Breaking this down: - **requirement** block defines a named requirement with an id, description, risk level, and how it's verified. - **element** block defines a system component (class, module, service, etc.). - The arrow **satisfies** links the element to the requirement it fulfills. ## Risk Levels and Verification Methods Mermaid supports the following values out of the box: **Risk:** `Low`, `Medium`, `High` **Verify method:** `Analysis`, `Demonstration`, `Inspection`, `Test` These map directly to standard systems-engineering terminology, making requirement diagrams useful for formal documentation as well as agile teams. ## A Real-World Example: E-Commerce Checkout Here's a fuller diagram tracing requirements for a checkout flow: ```mermaid requirementDiagram requirement PaymentProcessing { id: REQ-010 text: The system shall process credit card payments via Stripe. risk: high verifymethod: test } requirement OrderConfirmation { id: REQ-011 text: The system shall send an order confirmation email within 30 seconds. risk: medium verifymethod: demonstration } requirement AuditLogging { id: REQ-012 text: All payment events shall be logged for audit purposes. risk: high verifymethod: inspection } element StripeGateway { type: component docref: src/payments/StripeGateway.ts } element EmailService { type: component docref: src/notifications/EmailService.ts } element AuditLogger { type: component docref: src/logging/AuditLogger.ts } StripeGateway - satisfies -> PaymentProcessing EmailService - satisfies -> OrderConfirmation AuditLogger - satisfies -> AuditLogging AuditLogging - contains -> PaymentProcessing ``` Notice the **contains** relationship — it shows that audit logging is a sub-requirement of payment processing. Mermaid supports these relationship types: | Relationship | Meaning | |---|---| | contains | Parent-child requirement | | copies | One requirement replicates another | | derives | Requirement derived from another | | satisfies | Element fulfills a requirement | | verifies | Element provides verification | | refines | Requirement elaborates another | | traces | General traceability | ## Linking Requirements to Your Codebase The `docref` field on elements is key. Set it to the file path of the actual implementation: ```mermaid requirementDiagram requirement DataEncryption { id: SEC-001 text: All PII data shall be encrypted at rest using AES-256. risk: high verifymethod: inspection } element DatabaseLayer { type: component docref: src/db/EncryptedRepository.ts } element ConfigStore { type: component docref: config/encryption.yaml } DatabaseLayer - satisfies -> DataEncryption ConfigStore - satisfies -> DataEncryption ``` When this diagram lives in your repo's `docs/requirements.md`, any developer can instantly see *which files* handle a given compliance requirement. No ticket archaeology required. ## Where to Use Requirement Diagrams **Architecture Decision Records (ADRs):** Embed a requirementDiagram to show which components satisfy each architectural constraint. **GitHub / GitLab README:** Requirement diagrams render natively in both platforms. Drop one in your project README to give new contributors instant context. **Confluence and Notion:** Both support Mermaid blocks. Use requirement diagrams in your technical spec pages to replace static tables. **Sprint planning:** Create a lightweight diagram per sprint showing which requirements the team will satisfy — link it to your Jira epics via the `id` field. ## Tips for Better Requirement Diagrams 1. **Use consistent ID prefixes** — REQ- for features, SEC- for security, PERF- for performance. Makes search easy. 2. **Keep text concise** — Use "shall" language (ISO/IEC 29148 style). One requirement per block. 3. **Set risk honestly** — High-risk requirements are where your tests should be densest. 4. **Commit the diagram file** — Store `.mmd` files in `docs/diagrams/` so they're versioned with the code. 5. **Regenerate on CI** — Pair with `mmdc` in your pipeline to auto-export SVGs so docs stay current. ## Requirement Diagrams vs. Other Approaches | Approach | Pros | Cons | |---|---|---| | Jira/Linear tickets | Familiar, trackable | Disconnected from code | | Word/Google Docs | Easy for non-devs | Goes stale, no versioning | | SysML tools | Formal, complete | Expensive, steep learning curve | | Mermaid requirementDiagram | In-code, free, renders everywhere | Limited to what Mermaid supports | For most software teams, Mermaid hits the sweet spot: formal enough to be useful, lightweight enough to actually maintain. ## Try It Now The fastest way to experiment with requirement diagrams is [mermaideditor.lol](https://mermaideditor.lol) — paste any of the examples above and see them render instantly. No install, no signup. Once you're happy with a diagram, copy the Mermaid source into your README, wiki, or `docs/` folder. Your requirements are now living documentation — always in sync, always readable, always free. Requirements as code isn't just a nice idea. With Mermaid, it's three lines of syntax away. ### Best Mermaid Diagram Editors in 2026: Honest Comparison URL: https://mermaideditor.lol/blog/best-mermaid-diagram-editor-2026 Published: 2026-05-23 Updated: 2026-05-23 Description: Comparing the best mermaid diagram editors in 2026. Side-by-side feature comparison of online editors, VS Code extensions, and desktop tools. # Best Mermaid Diagram Editors in 2026: Honest Comparison There are more ways to write and preview Mermaid diagrams than most people realize. The right editor depends on your workflow — are you embedding in docs, working in a team, or just need a quick scratchpad? This comparison covers the main options in 2026: what they do well, where they fall short, and who each one is for. **Disclosure:** MermaidEditor is our product. We still include the official Mermaid Live Editor, VS Code extensions, GitHub native rendering, and desktop-style alternatives so readers can compare the trade-offs honestly. ## What Makes a Good Mermaid Editor? Before the comparison, here's the criteria that matters: - **Live preview** — renders as you type, no need to click "Run" - **Error messages** — tells you *what* broke, not just that it broke - **Export options** — SVG, PNG, or copy-to-clipboard - **No friction** — zero sign-up, open URL, start typing - **Syntax highlighting** — makes reading and editing code faster - **Diagram type support** — covers all Mermaid types, not just flowcharts - **Shareable links** — URL or embed code for sharing diagrams Let's go through each editor. --- ## 1. MermaidEditor.lol — Best Free Online Option **[mermaideditor.lol](https://mermaideditor.lol)** is built specifically for Mermaid and opens instantly in your browser. No account needed. **What it does well:** - Live preview — renders as you type - Supports all Mermaid diagram types (flowchart, sequence, timeline, mindmap, Gantt, ER, class, state, pie, journey, Gitgraph) - Clean, distraction-free UI - Free with no usage limits - Works on mobile too **What to use it for:** Quick diagrams, exploring syntax, sharing with teammates, embedding in documentation. Here's a sample flowchart you can test immediately: ```mermaid flowchart LR A[Open mermaideditor.lol] --> B[Paste your code] B --> C{Preview looks right?} C -- Yes --> D[Export or share] C -- No --> E[Fix the syntax] E --> B ``` **What this does:** A self-referential flowchart showing how to use the editor. `LR` means left-to-right layout. The diamond shape `{}` is a decision node. `--` creates an edge with label text. **Best for:** Anyone who wants a zero-friction online editor with full Mermaid support. --- ## 2. Mermaid Live Editor (Official) The official editor at **mermaid.live** is the reference implementation from the Mermaid team. **What it does well:** - Always runs the latest Mermaid version - Full syntax support - JSON config panel for theme customization - Sharable links (long URL encoding) **What it lacks:** - No syntax highlighting in the editor pane - Doesn't auto-save - Shareable links are very long (base64 encoded) - UI feels dated compared to newer tools **Best for:** Debugging syntax issues, testing features on the latest Mermaid version, or when you specifically need the official reference tool. --- ## 3. VS Code Extensions For developers, writing Mermaid inside VS Code is the most efficient workflow because your diagrams stay in the same repo as your code. **Top extension: "Markdown Preview Mermaid Support"** - Preview rendered Mermaid inside `.md` files - No separate browser tab needed - Diagrams live next to your code/docs **Setup:** Install the extension, write your Mermaid blocks in a `.md` file, open the Markdown preview (`Ctrl+Shift+V`). ```mermaid sequenceDiagram participant Dev as Developer participant VSC as VS Code participant Git as GitHub Dev->>VSC: Write Mermaid in .md file VSC->>Dev: Live preview in split pane Dev->>Git: Commit .md file Git->>Git: Renders in README automatically ``` **What this does:** Shows the developer workflow — write in VS Code, preview locally, commit to GitHub where it auto-renders. `participant` aliases make the diagram cleaner. `->>` is a solid arrow (synchronous call). **Limitation:** Preview quality depends on the extension's bundled Mermaid version, which may lag behind the latest release. **Best for:** Developers who write documentation in Markdown alongside their code. --- ## 4. GitHub Native Rendering GitHub has supported Mermaid natively in Markdown since 2022. Write a code block with the `mermaid` language tag — GitHub renders it automatically in README files, issues, PRs, and discussions. **What it does well:** - No tool to install - Renders everywhere on GitHub (READMEs, issues, wikis, comments) - Automatically uses a consistent style **What it lacks:** - No live preview as you write - Can't export as image directly - Minor version differences vs. latest Mermaid **Best for:** Open source projects, team READMEs, GitHub wikis, and putting diagrams in issues/PRs. --- ## 5. Notion Notion added Mermaid support via its code block (`/code` → select "Mermaid"). It renders inline in the page. **What it does well:** - Diagrams live in your project docs - Team members see rendered diagrams without any tools - Works in team wikis and project pages **What it lacks:** - No syntax highlighting while editing - Rendering can be slow on complex diagrams - Limited export options **Best for:** Teams using Notion as their primary docs tool who want diagrams embedded in their pages. --- ## Side-by-Side Comparison | Feature | MermaidEditor.lol | mermaid.live | VS Code | GitHub | Notion | |---------|-------------------|--------------|---------|--------|--------| | Live preview | ✅ | ✅ | ✅ | ❌ | ❌ | | No signup needed | ✅ | ✅ | ✅ | ❌ | ❌ | | Export SVG/PNG | ✅ | ✅ | ✅ | ❌ | ❌ | | Sharable links | ✅ | ✅ | ❌ | ✅ | ✅ | | All diagram types | ✅ | ✅ | ✅ | ✅ | ✅ | | Works in docs | ✅ | ❌ | ✅ | ✅ | ✅ | | Free | ✅ | ✅ | ✅ | ✅ | Freemium | --- ## Which Editor Should You Use? **Use [mermaideditor.lol](https://mermaideditor.lol)** if you want a dedicated online editor with live preview and zero friction. Good for quick work, learning, and sharing diagrams. **Use mermaid.live** if you specifically need to test the latest Mermaid features or debug syntax against the official parser. **Use VS Code** if you're a developer writing documentation alongside your code. Install the extension once and you won't need a browser tab. **Use GitHub natively** if your team collaborates on GitHub and you want diagrams embedded in issues, PRs, and READMEs automatically. **Use Notion** if your team's documentation lives in Notion and you want diagrams next to your project notes without switching tools. --- ## How to Pick the Right Diagram Type Once you've picked an editor, you still need to pick the right diagram type. Here's a quick decision tree: ```mermaid flowchart TD A[What are you diagramming?] --> B{Process or flow?} B -- Yes --> C[Flowchart or Sequence] B -- No --> D{Timeline or schedule?} D -- Yes --> E[Timeline or Gantt] D -- No --> F{Hierarchy or ideas?} F -- Yes --> G[Mindmap or Class diagram] F -- No --> H{Database structure?} H -- Yes --> I[ER Diagram] H -- No --> J[Pie chart or Journey] ``` **What this does:** A decision flowchart to pick the right Mermaid diagram type. The `TD` means top-down layout. Diamond nodes `{}` are decisions, rectangles `[]` are outcomes. Follow the arrows based on your use case. --- ## Want to Try Specific Diagram Types? - **Timelines:** Read the [Mermaid Timeline Instructions Guide](/blog/mermaid-timeline-diagram) - **Mindmaps:** Check the [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial) - **All types:** Browse the [Mermaid Cheat Sheet](/cheat-sheet) --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** No sign-up, no install. Open the link and start building your first diagram in under a minute. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ### MermaidEditor vs mermaid.live: Which Editor Is Best? URL: https://mermaideditor.lol/blog/mermaideditor-vs-mermaid-live Published: 2026-07-23 Updated: 2026-07-23 Description: MermaidEditor vs mermaid.live compared: templates, tutorials, export, official Mermaid support, and the best editor choice for docs teams. ## Short Answer **MermaidEditor is best for practical day-to-day Mermaid.js diagram work:** templates, tutorials, live preview, and PNG/SVG export in one no-signup tool. **mermaid.live is best when you need the official Mermaid reference editor** or want to test the newest Mermaid syntax first. The two tools are not enemies. They solve slightly different jobs. ## Quick Comparison | Feature | MermaidEditor | mermaid.live | |---|---|---| | Official Mermaid project | No, independent | Yes | | Live preview | Yes | Yes | | Templates | Yes, organized by diagram type | Limited examples | | Tutorials | Yes, many long-form guides | No | | Export | PNG/SVG workflow | Export/share workflows vary by version | | Best for | Docs teams, learners, quick diagram creation | Testing official Mermaid behavior | | Signup required | No | No | | Main risk | Not official | Less guided for beginners | ## What Is MermaidEditor? MermaidEditor is a free online Mermaid.js editor for creating diagrams as code. It combines a live editor, rendered preview, copy-paste templates, tutorials, and export workflows so you can move from idea to diagram faster. Use MermaidEditor when you want to: - start from a flowchart, sequence, ER, Gantt, class, timeline, or mindmap template - learn Mermaid syntax while editing - export a diagram as PNG or SVG - create documentation diagrams without opening a heavyweight drawing tool - share Mermaid examples with teammates ## What Is mermaid.live? mermaid.live is the official online editor from the Mermaid project. It is the safest place to test whether a diagram works with the current Mermaid renderer because it reflects the official project direction. Use mermaid.live when you want to: - validate syntax against the official Mermaid editor - test newly released Mermaid features - debug renderer behavior - confirm whether a rendering issue is with your code or with another editor ## When MermaidEditor Is Better MermaidEditor is better when the job is practical diagram creation rather than renderer validation. If you are writing a README, architecture decision record, product spec, onboarding doc, or tutorial, you usually need examples and context. MermaidEditor gives you templates and guides next to the editing workflow, which helps you avoid starting from a blank screen. For example, a documentation workflow often looks like this: ```mermaid flowchart TD A[Choose diagram type] --> B[Start from template] B --> C[Edit Mermaid syntax] C --> D[Preview diagram] D --> E{Looks correct?} E -->|No| C E -->|Yes| F[Export PNG/SVG or paste into docs] ``` This is where MermaidEditor shines: it treats Mermaid as a documentation workflow, not just a rendering test box. ## When mermaid.live Is Better mermaid.live is better when official renderer accuracy matters more than workflow help. If you are testing a brand-new Mermaid feature, comparing renderer versions, or filing a Mermaid bug, use the official editor. It is the reference point for the Mermaid ecosystem. In practice, a good workflow is: 1. Draft the diagram in MermaidEditor. 2. Export or copy the code into your docs. 3. If something behaves strangely, verify the same code in mermaid.live. ## Best Choice by Use Case | Use case | Better choice | Why | |---|---|---| | Learning Mermaid.js | MermaidEditor | Tutorials and templates reduce friction | | Writing documentation diagrams | MermaidEditor | Templates and export are built into the workflow | | Testing latest Mermaid syntax | mermaid.live | Official project reference | | Debugging renderer bugs | mermaid.live | Best source for official behavior | | Creating quick flowcharts | MermaidEditor | Faster start from templates | | Teaching teammates | MermaidEditor | Easier examples and guides | ## Is MermaidEditor a mermaid.live Replacement? MermaidEditor is not a replacement for the official Mermaid editor. It is an independent editor built around a different workflow: learning, templating, editing, and exporting Mermaid diagrams quickly. Think of it this way: - **mermaid.live** answers: “Does this Mermaid syntax work in the official editor?” - **MermaidEditor** answers: “How do I create, learn, template, and export this diagram faster?” Both are useful. ## Recommendation Use MermaidEditor for most everyday Mermaid.js work. Use mermaid.live as the official reference when you need to validate renderer behavior or newest syntax. [Open MermaidEditor and start from a template →](/templates) ## Want More Ready-Made Mermaid Templates? If you use Mermaid diagrams for engineering docs, README files, architecture notes, or product specs, join the [Mermaid Templates Pro early-access list](/templates/pro). The first pack will include 100+ copy-paste Mermaid templates for real documentation workflows. ### Mermaid Live Editor Guide: How to Use, Tips & Tricks (2026) URL: https://mermaideditor.lol/blog/mermaid-live-editor-guide Published: 2026-05-24 Updated: 2026-05-24 Description: Complete guide to using a mermaid live editor in 2026. Learn the interface, diagram types, export options, tips, and keyboard shortcuts. # Mermaid Live Editor Guide: How to Use, Tips & Tricks (2026) A Mermaid live editor is the fastest way to go from diagram idea to finished visual. You type code on the left, see the diagram render on the right — instantly, as you type. This guide walks through everything: how to use a live editor effectively, which features matter, workflow tips, and tricks that most users never discover. ## What Is a Mermaid Live Editor? A Mermaid live editor is a browser-based tool that renders Mermaid diagrams in real-time as you write the diagram code. There's no build step, no export process for viewing — just type and see. **Why use a live editor over writing Mermaid in your docs directly?** When you write Mermaid inside a GitHub README or Notion page, you can't see the rendered result until you save or publish. A live editor gives you instant visual feedback, so you can iterate 10x faster and catch errors immediately. [mermaideditor.lol](https://mermaideditor.lol) is built exactly for this workflow. Open it, start typing, see your diagram. ## Your First Diagram in 60 Seconds Open [mermaideditor.lol](https://mermaideditor.lol) in your browser. Paste this into the editor pane: ```mermaid flowchart TD A[Start here] --> B[Write some code] B --> C{Does it work?} C -- Yes --> D[Ship it] C -- No --> E[Debug] E --> B ``` **What this does:** A simple flowchart with a decision node. `TD` means top-down layout. `-->` creates arrows, `--text-->` adds labels to arrows. `{}` creates a diamond/decision shape, `[]` creates a rectangle, `()` creates a rounded shape. You should see the diagram render immediately on the right side. Change "Start here" to something else — the preview updates instantly. That's the live editor experience. ## The Interface Layout Most Mermaid live editors follow the same two-panel layout: **Left panel — Code editor:** - Where you write your Mermaid syntax - Usually has syntax highlighting - Shows parse errors inline or below the editor **Right panel — Live preview:** - Renders your diagram in real-time - Updates as you type (with a small debounce delay) - Scrolls and zooms independently **Toolbar (usually at top):** - Export buttons (SVG, PNG) - Theme selector - Copy-to-clipboard - Shareable link generator ## All Supported Diagram Types A good Mermaid live editor supports all diagram types. Here's a quick reference with one example of each: ### Flowchart ```mermaid flowchart LR A[Input] --> B[Process] B --> C[Output] B --> D[Error handler] D --> B ``` **What this does:** Left-to-right flowchart showing a process loop with error handling. `LR` = left-right, `TB` = top-bottom, `BT` = bottom-top, `RL` = right-left. ### Sequence Diagram ```mermaid sequenceDiagram participant U as User participant A as App participant DB as Database U->>A: Login request A->>DB: Check credentials DB-->>A: User found A-->>U: Access granted ``` **What this does:** Shows a login flow between three participants. `participant` with `as` creates a shorter alias. `->>` is a solid arrow, `-->>` is a dashed return arrow. Use sequence diagrams for API flows, authentication, and multi-system interactions. ### Timeline ```mermaid timeline title Product Roadmap Q2-Q3 2026 section Q2 2026 Feature A shipped Beta program launched : June section Q3 2026 Public launch 10K users milestone : September ``` **What this does:** A two-quarter product roadmap. Timelines are excellent for stakeholder updates and project planning. Read the full [Mermaid Timeline Instructions guide](/blog/mermaid-timeline-diagram) for the complete syntax. ### Pie Chart ```mermaid pie title Traffic Sources "Organic Search" : 45 "Direct" : 25 "Social" : 15 "Referral" : 10 "Email" : 5 ``` **What this does:** A simple pie chart of traffic sources. Each slice is `"label" : value`. The values don't need to add to 100 — Mermaid calculates percentages automatically. ### Mindmap ```mermaid mindmap root((Our Product)) Features Core functionality Premium features Users Free tier Pro tier Growth SEO content Partnerships ``` **What this does:** A mindmap showing a product across three branches. Great for brainstorming and strategy overviews. See the full [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial) for shapes, icons, and styling. ## Live Editor Tips & Tricks ### Tip 1: Start With the Diagram Type Keyword Every Mermaid diagram starts with a type keyword: `flowchart`, `sequenceDiagram`, `timeline`, `mindmap`, `gantt`, `erDiagram`, etc. If your preview is blank or throwing errors, the first thing to check is whether the opening keyword is correct and spelled right. ### Tip 2: Use the Error Panel When Mermaid can't parse your code, it shows an error message. Read it. The error usually tells you the line and the problem ("Unexpected token at line 5"). Most errors are: - Missing colons in timeline events - Wrong arrow syntax (`->` instead of `-->`) - Mismatched brackets - Wrong indentation in mindmaps ### Tip 3: Themes Change Everything The default Mermaid theme is fine, but adding `%%{init: {'theme': 'forest'}}%%` at the top can completely change the look. Try `forest`, `dark`, `neutral`, or `base` to see what fits your use case. ```mermaid %%{init: {'theme': 'dark'}}%% flowchart LR A[Dark theme] --> B[Looks different] B --> C[Use for presentations] ``` **What this does:** Applies the dark theme. The `%%{init: ...}%%` directive goes on the very first line of your diagram, before the type keyword. ### Tip 4: Export at the Right Size When exporting PNG for presentations, export at 2x resolution if the option is available. Mermaid SVGs are vector — they scale perfectly. PNGs need to be large enough to stay crisp on retina displays. ### Tip 5: Copy the Code, Not Just the Image The Mermaid code is the source of truth. When you share a diagram, share the code alongside the image (or instead of it). This way, whoever receives it can update it — no need to redraw from scratch. ### Tip 6: Use Comments Mermaid supports `%%` comments inside diagrams. Use them to leave notes: ```mermaid flowchart TD %% This is the happy path A[User signs up] --> B[Verification email sent] B --> C[Email verified] %% TODO: add the declined path C --> D[Account active] ``` **What this does:** Comments (`%%`) are ignored by the renderer — they don't appear in the output but help you document intent or leave TODOs in complex diagrams. ## Keyboard Shortcuts (Most Editors) | Action | Shortcut | |--------|---------| | Format/indent code | `Shift+Alt+F` (VS Code style) | | Undo | `Ctrl+Z` / `Cmd+Z` | | Redo | `Ctrl+Y` / `Cmd+Shift+Z` | | Select all | `Ctrl+A` / `Cmd+A` | | Find | `Ctrl+F` / `Cmd+F` | Standard code-editor shortcuts work in most Mermaid editors since they use CodeMirror or Monaco under the hood. ## Common Use Cases by Role **Developers:** Architecture diagrams, sequence diagrams for API flows, ER diagrams for database design, Gitgraph for branching strategies. **Product managers:** Flowcharts for user journeys, timelines for roadmaps, Gantt for sprint planning, pie charts for metrics dashboards. **Technical writers:** Flowcharts embedded in docs, sequence diagrams for integration guides, mindmaps for documentation structure. **Researchers:** Timelines for study plans, flowcharts for methodology, ER diagrams for data models. --- ## What to Read Next - [Mermaid Editor: The Complete Beginner's Guide](/blog/mermaid-editor-beginners-guide) — if you're completely new to Mermaid - [Best Mermaid Diagram Editors in 2026](/blog/best-mermaid-diagram-editor-2026) — comparing all the options - [Mermaid Timeline Instructions](/blog/mermaid-timeline-diagram) — deep dive into the timeline diagram type --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** Every code block in this guide works directly in the editor. Open it, paste, and start exploring. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ### Mermaid Editor: The Complete Beginner's Guide (2026) URL: https://mermaideditor.lol/blog/mermaid-editor-beginners-guide Published: 2026-05-25 Updated: 2026-05-25 Description: New to Mermaid? This beginner's guide covers what a mermaid editor is, how diagrams work, first diagram tutorial, and all diagram types explained. # Mermaid Editor: The Complete Beginner's Guide (2026) You've probably seen diagrams embedded in GitHub READMEs or documentation sites that look clean and professional, but don't have a "created with Figma" credit. A lot of them are Mermaid diagrams — written in plain text and rendered automatically. This guide explains what Mermaid is, why it's useful, and how to create your first diagram in a Mermaid editor in under 5 minutes. ## What Is Mermaid? Mermaid is a JavaScript-based diagramming tool that lets you define diagrams using plain text syntax. Instead of drag-and-drop boxes and arrows, you write code — and Mermaid turns that code into a rendered visual diagram. **The core idea:** ``` flowchart LR A --> B --> C ``` That plain text produces a three-node left-to-right flowchart. No drawing tools. No manual positioning. Just type and render. Mermaid was created in 2014 and is now used in GitHub, GitLab, Notion, Confluence, Obsidian, and dozens of other tools — natively, without plugins. ## What Is a Mermaid Editor? A Mermaid editor is a tool that provides a writing environment for Mermaid code with a live preview panel. You write on one side, see the rendered diagram on the other. [mermaideditor.lol](https://mermaideditor.lol) is a free online Mermaid editor — open it in your browser, start typing, and you'll see your diagram render instantly. No account needed, no install. ## Why Use Mermaid Instead of Visio or Lucidchart? This is the fair question. Tools like Lucidchart and Draw.io are great. So why use Mermaid? **Mermaid advantages:** - **Text = source of truth.** Diagrams live in your repo, your docs, your README. You version-control them like code. - **Instant updates.** Change one line of text, re-render. No redrawn boxes. - **Platform-native.** GitHub, GitLab, Notion render Mermaid automatically. No export needed. - **Free.** No subscription, no diagram count limit. **When to stick with Lucidchart/Draw.io:** - When you need pixel-perfect layouts (org charts, office floorplans) - When non-technical stakeholders need to edit the diagram - When you need shapes Mermaid doesn't support (custom icons, images in nodes) For software documentation, architecture diagrams, and technical planning — Mermaid wins on speed and maintainability. ## Your First Diagram: Step-by-Step Open [mermaideditor.lol](https://mermaideditor.lol). You'll see two panels — code on the left, preview on the right. **Step 1:** Clear anything in the editor pane. **Step 2:** Type the following: ```mermaid flowchart TD A[You] --> B[Learn Mermaid syntax] B --> C[Write a diagram] C --> D{Looks right?} D -- Yes --> E[Done!] D -- No --> B ``` **What this does:** A flowchart showing the learning loop. `TD` = top-down. `A[You]` creates a rectangle labeled "You". `-->` is an arrow. `D{Looks right?}` creates a diamond decision node. `D -- Yes -->` adds a label to the arrow. **Step 3:** Watch the preview update. If it looks right, you've written your first Mermaid diagram. **Step 4:** Try changing "You" to your name. The preview updates instantly. ## Understanding Mermaid Syntax Basics Mermaid syntax follows a few consistent rules across all diagram types: **1. Diagram type declaration first:** Every diagram starts with its type: `flowchart`, `sequenceDiagram`, `timeline`, `mindmap`, etc. **2. Indentation defines structure:** In mindmaps and timelines, indentation defines parent-child relationships. Be consistent — use spaces, not tabs. **3. Special characters in labels need quotes:** If your label contains commas, parentheses, or special characters, wrap it in quotes: `A["User (authenticated)"]` **4. Direction modifiers:** For flowcharts: `TD` (top-down), `LR` (left-right), `BT` (bottom-top), `RL` (right-left). Other diagram types have their own orientation options. ## The Main Diagram Types Here's a practical overview of what each diagram type is for: ### Flowchart — For processes and logic ```mermaid flowchart LR Input --> Process --> Output Process --> Error Error --> Process ``` **What this does:** A minimal left-to-right process flow with an error loop. Flowcharts are the most versatile Mermaid diagram type — use them for any process, workflow, or decision tree. ### Sequence Diagram — For system interactions ```mermaid sequenceDiagram User->>Server: HTTP Request Server->>Database: Query Database-->>Server: Results Server-->>User: HTTP Response ``` **What this does:** Shows a request-response cycle between a user, server, and database. `->>` is a solid arrow (request), `-->>` is a dashed arrow (response). Essential for API documentation and debugging distributed systems. ### Timeline — For schedules and roadmaps ```mermaid timeline title My Learning Plan section Month 1 Mermaid basics First diagram built : Week 2 section Month 2 Advanced types Diagrams in production : Week 6 ``` **What this does:** A 2-month learning plan. Timelines map events to time periods using sections and events. See the [complete timeline instructions guide](/blog/mermaid-timeline-diagram) for full syntax. ### Mindmap — For brainstorming and structure ```mermaid mindmap root((My Project)) Goals Revenue target Launch date Team Dev team Design team Risks Timeline Budget ``` **What this does:** A project mindmap with three branches. The root uses `((double parens))` for a circle shape. Mindmaps are great for brainstorming, planning, and structuring information. See the [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial) for all the shape options. ### Gantt Chart — For project scheduling ```mermaid gantt title Development Schedule dateFormat YYYY-MM-DD section Design Wireframes :done, des1, 2026-01-01, 2026-01-10 Mockups :active, des2, 2026-01-10, 2026-01-25 section Development Frontend :dev1, 2026-01-20, 2026-02-10 Backend :dev2, 2026-01-25, 2026-02-15 ``` **What this does:** A Gantt chart with two parallel workstreams. `done` and `active` are status flags that affect bar styling. Gantt charts show task duration and overlap — use them when you need to show how long things take, not just when milestones land. ### ER Diagram — For database design ```mermaid erDiagram USER { int id PK string email string name } ORDER { int id PK int user_id FK date created_at } USER ||--o{ ORDER : places ``` **What this does:** A minimal ER diagram with two entities and a relationship. `PK` and `FK` label primary and foreign keys. `||--o{` means "one to zero or many". Use ER diagrams for database schema documentation. ## Common Beginner Questions **Q: Does Mermaid work offline?** The [mermaideditor.lol](https://mermaideditor.lol) editor needs an internet connection. But if you're using Mermaid via VS Code extensions or in a local docs setup, it works offline once the library is loaded. **Q: Can I use Mermaid in Google Docs?** Not natively. Google Docs doesn't render Mermaid. For Google Docs, you'd need to export your diagram as an image and insert it. **Q: What's the difference between Mermaid and PlantUML?** Both are text-based diagramming tools. Mermaid has better native support in modern platforms (GitHub, Notion, GitLab). PlantUML has been around longer and has more diagram types but requires a Java server to render. **Q: Are there character limits for diagram labels?** No hard limit, but very long labels make diagrams hard to read. Keep node labels under 50 characters for flowcharts, 40 for mindmaps. ## Next Steps Once you've built your first diagram, explore specific types in depth: - **Timelines:** [How to Use Mermaid Timeline Diagrams](/blog/mermaid-timeline-diagram) - **Mindmaps:** [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial) - **All types at a glance:** [Mermaid Cheat Sheet](/cheat-sheet) - **Templates to copy:** [Diagram Templates](/templates) --- **Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)** The best way to learn Mermaid is to type diagrams and watch them render. Open the editor, try each example in this guide, and you'll have the basics down in 30 minutes. --- *Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)* ### How to Create Mermaid Diagrams Online (No Install Required) URL: https://mermaideditor.lol/blog/mermaid-diagram-online Published: 2026-05-28 Updated: 2026-05-28 Description: Create mermaid diagrams online without installing anything. Browser-based tools, all diagram types, export options, and embedding in your docs. # How to Create Mermaid Diagrams Online (No Install Required) Creating a Mermaid diagram doesn't require any software, command line tools, or developer setup. Open a browser, go to an online editor, paste some code, and your diagram renders immediately. This guide shows you how — from your first diagram to exporting and embedding it in your docs. ## What You Need (Spoiler: Just a Browser) Nothing to install. No Node.js, no terminal, no IDE. Just open [mermaideditor.lol](https://mermaideditor.lol) in any modern browser and start typing. This is the whole setup: 1. Open `mermaideditor.lol` 2. Type (or paste) Mermaid code in the left panel 3. See your diagram render on the right 4. Export or share That's it. The rest of this guide is about doing more with that setup. ## Your First Online Diagram Paste this into [mermaideditor.lol](https://mermaideditor.lol): ```mermaid flowchart TD A[Open browser] --> B[Go to mermaideditor.lol] B --> C[Paste Mermaid code] C --> D{Looks right?} D -- Yes --> E[Export or share] D -- No --> F[Fix the code] F --> C ``` **What this does:** A self-referential flowchart showing how to use an online Mermaid editor. `TD` = top-down layout. The diamond `{}` is a decision node. Arrow labels are added with `-- text -->`. You should see this diagram render in the preview panel immediately after pasting. If you see an error, check that you copied the entire block including the first line (`flowchart TD`). ## All the Diagram Types Available Online A good online Mermaid editor supports all diagram types. Here's a sample of each: ### Flowchart ```mermaid flowchart LR Start --> A[Gather requirements] A --> B[Design solution] B --> C[Build it] C --> D{QA passed?} D -- Yes --> End D -- No --> B ``` **What this does:** A simple development workflow with a QA feedback loop. `LR` = left-to-right. The loop from `D` back to `B` represents iterating on the design after a failed QA check. ### Sequence Diagram ```mermaid sequenceDiagram participant Browser participant Server participant Cache Browser->>Server: GET /dashboard Server->>Cache: Check cache Cache-->>Server: Cache miss Server-->>Browser: Return fresh data ``` **What this does:** A web request flow showing a cache miss scenario. `->>` is a request arrow, `-->>` is a return/response arrow. Use sequence diagrams when you need to show communication between multiple systems. ### Timeline ```mermaid timeline title 2026 Content Calendar section Q1 Blog series launched First 10 posts live : March section Q2 Video content starts SEO traffic 10K/mo : June section Q3 Newsletter launched 5K subscribers : September section Q4 Paid content tier Revenue milestone : December ``` **What this does:** A year-long content strategy roadmap broken into quarters. Timelines are perfect for showing progression over time. See the [Mermaid Timeline Instructions guide](/blog/mermaid-timeline-diagram) for full syntax. ### Mindmap ```mermaid mindmap root((Online Tools)) Diagramming Mermaid Editor Draw.io Excalidraw Documentation Notion Confluence GitBook Design Figma Canva Adobe XD ``` **What this does:** A mindmap of online productivity tools by category. Three branches, each with three tools. For more mindmap syntax, see the [Mermaid Mindmap Syntax Cheat Sheet](/blog/mermaid-mindmap-tutorial). ### Gantt Chart ```mermaid gantt title Website Redesign Project dateFormat YYYY-MM-DD section Design Wireframes :done, a1, 2026-01-01, 2026-01-10 Visual design :active, a2, 2026-01-08, 2026-01-20 section Dev Frontend dev :a3, 2026-01-18, 2026-02-05 Backend dev :a4, 2026-01-20, 2026-02-10 section Launch QA & testing :a5, 2026-02-08, 2026-02-20 Go live :milestone, a6, 2026-02-20, 0d ``` **What this does:** A project Gantt chart with three sections and overlapping tasks. `done` and `active` are status flags. `milestone` creates a diamond marker. The `0d` duration on the milestone means it's a point in time, not a range. --- ## Exporting Your Diagram Once your diagram looks right, you have several export options: **SVG export:** - Vector format — scales perfectly at any size - Best for: websites, high-res documents, print - File stays small even for complex diagrams **PNG export:** - Raster image — fixed pixel dimensions - Best for: presentations, email attachments, social media - Export at 2x resolution if your editor supports it for retina displays **Copy to clipboard:** - Some editors let you copy the rendered image directly - Good for quickly pasting into Slack, email, or Notion **Share via URL:** - Some editors encode your diagram in the URL - Anyone with the link sees the same diagram - Link updates when you edit (in editors that auto-save to URL) --- ## Embedding Mermaid Diagrams in Other Tools ### GitHub / GitLab Just use a code block with the `mermaid` language tag in any Markdown file: ```` ```mermaid flowchart LR A --> B --> C ``` ```` GitHub and GitLab render this automatically in READMEs, issues, PRs, and wikis. No plugins needed. ### Notion In a Notion page, type `/code`, select the code block, then choose "Mermaid" as the language. Notion renders the diagram inline. ### Confluence Confluence has a Mermaid macro (may require the Mermaid for Confluence app depending on your instance). Search the Confluence Marketplace for "Mermaid". ### Your Website or Blog Include the Mermaid JavaScript library and use `
` tags, or use the CDN:

```html


flowchart LR
    A --> B --> C
``` **What this does:** Loads Mermaid from the CDN and auto-renders any `
` elements on the page. This is the simplest way to add Mermaid to a static site or blog.

---

## When to Use Online vs. Local

**Use online (mermaideditor.lol) when:**
- Quick one-off diagrams
- Sharing with someone who doesn't have an editor set up
- Learning and experimenting with syntax
- No access to VS Code or a terminal

**Use VS Code + extension when:**
- Diagrams live in your codebase
- You want version control on your diagrams
- Working offline

**Use GitHub/Notion natively when:**
- Diagrams belong in your documentation
- Team members need to edit the diagram
- You want diagrams to stay in sync with your docs

---

## Common Questions

**Does it work on mobile?**
Yes. [mermaideditor.lol](https://mermaideditor.lol) is mobile-responsive. The editor is a bit cramped on phone screens, but it works well on tablets.

**Can I save my diagrams?**
Your browser doesn't auto-save work in an online editor. Bookmark the URL if your editor encodes the diagram in the URL, or copy the code to a `.md` file in your project.

**Is my data private?**
Mermaid renders client-side in the browser. Your diagram code doesn't get sent to a server. The rendering happens locally in your browser's JavaScript engine.

**What's the maximum diagram size?**
There's no hard limit, but very large diagrams (hundreds of nodes) get slow to render and hard to read. If your diagram has more than ~30 nodes, consider splitting it into multiple diagrams.

---

## What to Build Next

Now that you can create diagrams online, explore specific types:

- **Timelines:** [How to Use Mermaid Timeline Diagrams](/blog/mermaid-timeline-diagram) — perfect for roadmaps and schedules
- **Mindmaps:** [Mermaid Mindmap Examples: 15 Real Use Cases](/blog/mermaid-mindmap-tutorial) — brainstorming and structure
- **Full reference:** [Mermaid Cheat Sheet](/cheat-sheet) — all diagram types in one place
- **Ready-made templates:** [Diagram Templates](/templates) — copy and customize

---

**Try this live in our free Mermaid Editor → [mermaideditor.lol](https://mermaideditor.lol)**

Open it now, paste any example from this guide, and you'll have a working diagram in under a minute.

---

*Related: [Mermaid Cheat Sheet](/cheat-sheet) · [Diagram Templates](/templates) · [Home](/)*

### How to Document REST APIs with Mermaid Sequence Diagrams
URL: https://mermaideditor.lol/blog/mermaid-api-flow-diagram
Published: 2026-05-22
Updated: 2026-05-22
Description: Learn how to use Mermaid sequence diagrams to document REST API flows, authentication, error handling, and microservice interactions — with copy-paste examples.

# How to Document REST APIs with Mermaid Sequence Diagrams

Every API has a story. A client sends a request, an auth layer checks credentials, a service does work, a database gets queried, and a response comes back. That story is almost impossible to communicate clearly in prose — but a sequence diagram tells it in seconds.

Mermaid's sequence diagram syntax is purpose-built for exactly this. You write plain text, and it renders into a crisp interaction diagram that lives right next to your code, your README, or your wiki. No Visio license, no drag-and-drop fatigue.

This guide shows you how to document real API patterns — auth flows, CRUD operations, error handling, and microservice chains — using Mermaid sequence diagrams you can paste directly into your docs today.

---

## Why Sequence Diagrams for APIs?

Other diagram types show *structure*. Sequence diagrams show *behavior over time* — which is exactly what an API consumer needs to understand:

- Who initiates the call
- What gets checked before the work happens
- What happens when something fails
- Which systems talk to each other and in what order

Sequence diagrams are also the most universally understood diagram type among developers. Even non-technical stakeholders can follow the left-to-right, top-to-bottom flow.

---

## Basic REST API Request

Let's start simple. A client fetches a user record:

```mermaid
sequenceDiagram
    participant Client
    participant API as REST API
    participant DB as Database

    Client->>API: GET /users/42
    API->>DB: SELECT * FROM users WHERE id=42
    DB-->>API: User row
    API-->>Client: 200 OK { id: 42, name: "Alice" }
```

Note the arrow types: `->>` for requests (solid line), `-->>` for responses (dashed line). This visual distinction immediately shows direction and intent.

---

## JWT Authentication Flow

Auth is where sequence diagrams really shine. Here's a complete JWT login + protected request flow:

```mermaid
sequenceDiagram
    participant User
    participant API as REST API
    participant Auth as Auth Service
    participant DB as Database

    User->>API: POST /auth/login { email, password }
    API->>Auth: Validate credentials
    Auth->>DB: SELECT user WHERE email=?
    DB-->>Auth: User record
    Auth->>Auth: bcrypt.compare(password, hash)
    Auth-->>API: Valid ✓
    API-->>User: 200 OK { access_token, refresh_token }

    Note over User,API: Later — authenticated request

    User->>API: GET /profile (Authorization: Bearer )
    API->>Auth: Verify JWT signature
    Auth-->>API: { userId: 42, role: "admin" }
    API->>DB: SELECT * FROM profiles WHERE userId=42
    DB-->>API: Profile data
    API-->>User: 200 OK { profile }
```

The `Note` instruction lets you annotate a moment in time — perfect for explaining context between steps.

---

## API Error Handling Paths

Good API docs show the unhappy paths too. Use `alt` blocks to branch on conditions:

```mermaid
sequenceDiagram
    participant Client
    participant API as REST API
    participant DB as Database

    Client->>API: DELETE /posts/99

    alt Post exists and user owns it
        API->>DB: DELETE FROM posts WHERE id=99
        DB-->>API: 1 row affected
        API-->>Client: 204 No Content
    else Post not found
        API-->>Client: 404 Not Found { error: "Post not found" }
    else User does not own post
        API-->>Client: 403 Forbidden { error: "Not your post" }
    end
```

The `alt/else/end` block maps directly to your API's conditional logic. Anyone reading the diagram instantly understands the three possible outcomes without reading a line of code.

---

## Microservice Chain

Modern APIs rarely live alone. Here's an e-commerce order placement flow across services:

```mermaid
sequenceDiagram
    participant App as Mobile App
    participant GW as API Gateway
    participant Order as Order Service
    participant Inventory as Inventory Service
    participant Payment as Payment Service
    participant Notify as Notification Service

    App->>GW: POST /orders { items, payment }
    GW->>Order: Create order
    Order->>Inventory: Reserve items
    Inventory-->>Order: Reserved ✓
    Order->>Payment: Charge card
    Payment-->>Order: Charged ✓
    Order-->>GW: Order #1042 created
    GW-->>App: 201 Created { orderId: 1042 }

    Order-)Notify: (async) Send confirmation email
```

The `-)` arrow (vs `->>`) denotes an **async** message — the order service fires the notification and doesn't wait for a response. That single character change communicates a meaningful architectural decision.

---

## Pagination and Cursor-Based APIs

```mermaid
sequenceDiagram
    participant Client
    participant API as REST API

    Client->>API: GET /posts?limit=20
    API-->>Client: 200 OK { data: [...], next_cursor: "abc123" }

    loop Until no next_cursor
        Client->>API: GET /posts?limit=20&cursor=abc123
        API-->>Client: 200 OK { data: [...], next_cursor: "def456" }
    end

    Client->>API: GET /posts?limit=20&cursor=xyz999
    API-->>Client: 200 OK { data: [...], next_cursor: null }
```

The `loop` block lets you model repeated behavior without drawing 50 identical arrows. Essential for polling, pagination, and retry logic.

---

## OAuth 2.0 Authorization Code Flow

This one's a classic that trips up a lot of developers to explain verbally:

```mermaid
sequenceDiagram
    participant User
    participant App as Your App
    participant AuthServer as Auth Server
    participant Resource as Resource Server

    User->>App: Click "Login with Google"
    App->>AuthServer: Redirect to /authorize?client_id=...&scope=...
    AuthServer->>User: Show login + consent screen
    User->>AuthServer: Grant permission
    AuthServer->>App: Redirect to callback?code=AUTH_CODE
    App->>AuthServer: POST /token { code, client_secret }
    AuthServer-->>App: { access_token, refresh_token }
    App->>Resource: GET /userinfo (Bearer access_token)
    Resource-->>App: { id, email, name }
```

Try explaining that in words. The diagram does it in 9 lines.

---

## Tips for Clean API Sequence Diagrams

**Use aliases for long participant names.** `participant DB as PostgreSQL Database` keeps the diagram readable without truncating names in the boxes.

**Keep it to one flow per diagram.** Don't cram the login flow, the data fetch, and the logout into one diagram. Split them. Smaller diagrams are easier to maintain and easier to understand.

**Show the response body when it matters.** `API-->>Client: 200 OK { token }` is more useful than `API-->>Client: Success`.

**Use `activate/deactivate`** to show when a service is actively processing:

```mermaid
sequenceDiagram
    participant Client
    participant API

    Client->>API: POST /report/generate
    activate API
    API-->>Client: 202 Accepted { jobId: 99 }
    Note right of API: Processing in background...
    deactivate API
```

---

## Where to Put Your API Diagrams

**README.md on GitHub** — GitHub renders Mermaid natively in markdown. Drop a ```mermaid block directly in your README.

**OpenAPI / Swagger** — Swagger UI doesn't render Mermaid, but your `description` fields support markdown. Link to a docs page that has the diagrams.

**Confluence or Notion** — Both support Mermaid via plugins (Confluence) or code blocks (Notion). Put diagrams next to endpoint tables.

**Your own docs site** — Docusaurus, VitePress, and Nextra all support Mermaid out of the box.

If you want to quickly draft a diagram before committing it, [mermaideditor.lol](https://mermaideditor.lol) gives you an instant preview with no setup — paste, tweak, export.

---

## Sequence Diagram Quick Reference

| Syntax | Meaning |
|---|---|
| `A->>B: message` | Synchronous request |
| `A-->>B: message` | Response (dashed) |
| `A-)B: message` | Async fire-and-forget |
| `activate A` | Show A as active (lifeline box) |
| `deactivate A` | End active state |
| `Note over A,B: text` | Annotation spanning participants |
| `alt condition` ... `else` ... `end` | Conditional branch |
| `loop label` ... `end` | Repeated interaction |
| `opt label` ... `end` | Optional block |
| `par` ... `and` ... `end` | Parallel actions |

---

## Start Documenting Your API Now

Better API documentation isn't about buying a tool. It's about spending 10 minutes turning an API flow into a diagram your whole team can read.

Grab any endpoint from your current project, trace the call from client to database and back, and build a sequence diagram. You'll immediately spot assumptions you've been carrying around without realizing it.

**Try the examples above live → [mermaideditor.lol](https://mermaideditor.lol)**

Paste any diagram from this guide, see it render instantly, and export it as SVG or PNG when you're ready to share.

---

*Related: [Mermaid Sequence Diagram Tutorial](/blog/mermaid-sequence-diagram-tutorial) · [Mermaid C4 Architecture Diagrams](/blog/mermaid-c4-architecture-diagrams) · [Mermaid Cheat Sheet](/cheat-sheet)*

### Mermaid.js Architecture Diagrams: Complete Guide for 2026
URL: https://mermaideditor.lol/blog/mermaid-architecture-diagram-guide
Published: 2026-06-10
Updated: 2026-06-10
Description: Learn how to draw software architecture diagrams with Mermaid.js. Covers system architecture, microservices, cloud infrastructure, and database design with real examples.

# Mermaid.js Architecture Diagrams: Complete Guide for 2026

Software architecture diagrams are the most common reason developers reach for a diagramming tool. And yet, most teams end up with a half-updated Lucidchart link buried in a Confluence page that nobody trusts.

Mermaid.js fixes this by making architecture diagrams **part of your code**. They live in your repo, they're reviewed in pull requests, and they get updated when the system changes. This guide covers every approach for drawing architecture diagrams in Mermaid.js — from simple flowcharts to layered cloud infrastructure.

## Why Mermaid.js for Architecture Diagrams?

Before picking a tool, the question is: *where does the diagram live?*

- A PNG in Google Drive goes stale in weeks
- A link to Lucidchart requires another tool's login
- A Mermaid diagram in your README stays next to the code it describes

Architecture diagrams as code means:
- **PR reviews catch stale docs** — when the code changes, reviewers see if the diagram didn't
- **No drag-and-drop overhead** — write once, render everywhere GitHub/GitLab/Notion support Mermaid
- **Diff-friendly** — `git diff` shows exactly what changed in the architecture
- **Automatable** — generate diagrams programmatically from infra configs

## Which Mermaid Diagram Type for Architecture?

Mermaid offers several diagram types. Here's which to use for architecture work:

| Use Case | Recommended Diagram Type |
|---|---|
| High-level system overview | `block-beta` or `flowchart` |
| Service-to-service flows | `flowchart` |
| API request/response | `sequenceDiagram` |
| Database schema | `erDiagram` |
| State transitions | `stateDiagram-v2` |
| Component hierarchy | `flowchart` with subgraphs |
| Cloud zone layout | `block-beta` |

## System Architecture Flowchart

The workhorse for architecture documentation. A left-to-right flowchart with subgraphs maps perfectly to layered systems:

```mermaid
flowchart LR
    subgraph Client["Client Layer"]
        Web["React SPA"]
        Mobile["iOS / Android"]
    end

    subgraph Edge["Edge Layer"]
        CDN["CloudFront CDN"]
        WAF["Web Application Firewall"]
    end

    subgraph API["API Layer"]
        GW["API Gateway"]
        Auth["Auth Service"]
    end

    subgraph Services["Business Services"]
        Users["User Service"]
        Orders["Order Service"]
        Notify["Notification Service"]
    end

    subgraph Data["Data Layer"]
        PG[("PostgreSQL")]
        Redis[("Redis Cache")]
        S3["S3 / Object Store"]
    end

    Web & Mobile --> CDN
    CDN --> WAF
    WAF --> GW
    GW --> Auth
    GW --> Users & Orders & Notify
    Users & Orders --> PG
    GW --> Redis
    Notify --> S3
```

This renders as a full system diagram with five clearly separated layers. Change a service name or add a new one — two seconds of text editing and the diagram is updated.

## Microservices Architecture Diagram

For microservices, the key is showing **service boundaries** and **communication patterns**. Subgraphs represent bounded contexts or domains:

```mermaid
flowchart TD
    subgraph Gateway["API Gateway"]
        GW["Kong / NGINX"]
    end

    subgraph Identity["Identity Domain"]
        AuthSvc["Auth Service"]
        UserSvc["User Service"]
        AuthDB[("Users DB")]
    end

    subgraph Commerce["Commerce Domain"]
        CatalogSvc["Catalog Service"]
        OrderSvc["Order Service"]
        PaySvc["Payment Service"]
        CommerceDB[("Commerce DB")]
    end

    subgraph Messaging["Async Messaging"]
        Queue["Message Broker (RabbitMQ / Kafka)"]
    end

    subgraph Infra["Shared Infrastructure"]
        Cache[("Redis")]
        Storage["Object Storage"]
    end

    Client(["Client"]) --> GW
    GW --> AuthSvc & CatalogSvc & OrderSvc
    AuthSvc --> AuthDB
    UserSvc --> AuthDB
    CatalogSvc --> CommerceDB
    OrderSvc --> CommerceDB
    OrderSvc --> Queue
    Queue --> PaySvc & Notify["Notification Service"]
    PaySvc --> CommerceDB
    GW --> Cache
```

The domain groupings immediately communicate ownership boundaries — something flat node lists can't do.

## Cloud Infrastructure Block Diagram

For cloud infrastructure, the `block-beta` syntax gives you direct grid control. It's better than a flowchart for diagrams where spatial zones carry meaning — VPCs, availability zones, security tiers:

```mermaid
block-beta
  columns 5
  block:Internet:5
    Users["Users / Internet"]
    CF["CloudFront"]
  end
  ALB["Application Load Balancer"]:5
  block:AZ1:2
    ECS1["ECS Task 1"]
    ECS2["ECS Task 2"]
  end
  block:AZ2:2
    ECS3["ECS Task 3"]
    ECS4["ECS Task 4"]
  end
  space:1
  RDS["RDS Primary (Multi-AZ)"]:2 Elastic["ElastiCache"]:2 S3Bucket["S3"]:1
```

The `columns 5` declaration controls the grid, and `:N` spans give you layout control that flowcharts can't provide.

## Sequence Diagram for Architecture Flows

System diagrams show *what exists*. Sequence diagrams show *how components interact at runtime*. Both are essential for a complete architectural picture:

```mermaid
sequenceDiagram
    actor User
    participant FE as Frontend
    participant GW as API Gateway
    participant Auth as Auth Service
    participant API as Order API
    participant DB as PostgreSQL
    participant Cache as Redis

    User->>FE: Click "Place Order"
    FE->>GW: POST /orders (+ JWT)
    GW->>Auth: Validate JWT
    Auth-->>GW: 200 OK {userId}
    GW->>API: POST /orders {userId, items}
    API->>Cache: GET cart:{userId}
    Cache-->>API: cart items
    API->>DB: INSERT order
    DB-->>API: order_id
    API-->>GW: 201 {order_id}
    GW-->>FE: 201 {order_id}
    FE-->>User: Order confirmed
```

This pairs with the structural diagram above. One shows the system layout; the other shows a critical path through it. Together they answer both "what exists?" and "how does it work?"

## Database Architecture with ER Diagrams

For data architecture, the `erDiagram` type is purpose-built. It's not just schema documentation — it communicates architectural decisions about data ownership and relationships:

```mermaid
erDiagram
    TENANT ||--o{ USER : "has many"
    TENANT ||--o{ PROJECT : "owns"
    USER ||--o{ PROJECT_MEMBER : "joins via"
    PROJECT ||--o{ PROJECT_MEMBER : "has"
    PROJECT ||--o{ TASK : "contains"
    USER ||--o{ TASK : "assigned to"
    TASK ||--o{ COMMENT : "has"
    USER ||--o{ COMMENT : "authors"

    TENANT {
        uuid id PK
        string name
        string plan
        timestamp created_at
    }
    PROJECT {
        uuid id PK
        uuid tenant_id FK
        string name
        string status
    }
    TASK {
        uuid id PK
        uuid project_id FK
        uuid assignee_id FK
        string title
        string priority
        timestamp due_at
    }
```

This communicates the multi-tenant data model and ownership hierarchy far more clearly than a list of CREATE TABLE statements.

## Combining Diagram Types in Architecture Docs

The best architecture documentation uses multiple Mermaid diagram types together. A clean structure:

**1. System context** (flowchart) — Who uses the system? What external services does it depend on?
**2. Container diagram** (flowchart with subgraphs) — What are the major deployable components?
**3. Key flows** (sequenceDiagram) — How do the most critical paths work at runtime?
**4. Data model** (erDiagram) — What are the core entities and relationships?
**5. Infrastructure** (block-beta) — Where does everything run?

This roughly follows the [C4 model](https://c4model.com/) structure, which Mermaid also supports directly via its C4 diagram type.

## Styling Architecture Diagrams

Color-code by concern to make layers immediately readable:

```mermaid
flowchart LR
    classDef frontend fill:#3b82f6,stroke:#1d4ed8,color:#fff
    classDef backend fill:#10b981,stroke:#047857,color:#fff
    classDef database fill:#8b5cf6,stroke:#6d28d9,color:#fff
    classDef external fill:#f59e0b,stroke:#b45309,color:#fff

    Web["Web App"]:::frontend
    Mobile["Mobile"]:::frontend
    API["API Server"]:::backend
    Worker["Background Worker"]:::backend
    PG[("PostgreSQL")]:::database
    Redis[("Redis")]:::database
    Stripe["Stripe API"]:::external
    SendGrid["SendGrid"]:::external

    Web & Mobile --> API
    API --> PG & Redis
    API --> Stripe
    Worker --> PG
    Worker --> SendGrid
```

Blue for frontend, green for backend, purple for databases, amber for external services — your whole team immediately knows which color means what.

## Architecture Diagram Anti-Patterns to Avoid

**1. God diagrams** — One massive diagram with 40 nodes and 80 arrows. Nobody reads these. Split by concern: one for services, one for data, one for infra.

**2. Stale topology** — A diagram that shows how the system *used* to look. Add a date or version to your diagram title: `title System Architecture (2026-Q2)`. When it drifts, it's obvious.

**3. Missing boundaries** — Flat node lists without subgraphs make it impossible to see ownership or deployment boundaries. Always group by domain or layer.

**4. Ignoring the unhappy path** — Architecture diagrams often show only the sunny path. Add failure states and fallback paths — especially for external dependencies.

**5. Over-engineering the diagram** — Mermaid can express a lot, but a 5-node diagram that your team actually updates beats a 50-node masterwork nobody understands.

## Where to Store Your Architecture Diagrams

- **`/docs/architecture.md`** — primary home, linked from README
- **ADRs (Architecture Decision Records)** — each decision gets a diagram showing before/after
- **Pull requests** — add a diagram when introducing a new service or changing a data flow
- **Runbooks** — sequence diagrams for incident response flows
- **Onboarding docs** — the first thing a new engineer should read

## Try It Live

All the examples in this guide are ready to paste into [mermaideditor.lol](https://mermaideditor.lol). The live preview updates as you type, so you can tweak layouts, add services, and experiment with styles before committing to your repo.

Start with the system architecture flowchart, adapt the service names to your stack, and you'll have a working architecture diagram in under five minutes — no Lucidchart account required.

---

*Related: [Mermaid C4 Architecture Diagrams](/blog/mermaid-c4-architecture-diagrams) · [Mermaid ER Diagram Guide](/blog/mermaid-er-diagram-database) · [Mermaid Block Diagram Tutorial](/blog/mermaid-block-diagram-tutorial)*

### Mermaid.js in MkDocs and MkDocs Material Guide
URL: https://mermaideditor.lol/blog/mermaid-in-mkdocs
Published: 2026-06-12
Updated: 2026-06-12
Description: Step-by-step guide to adding Mermaid diagrams to MkDocs and MkDocs Material sites. Covers plugin setup, dark mode, custom themes, and common fixes.

# How to Use Mermaid.js in MkDocs and MkDocs Material (2026 Guide)

MkDocs is one of the most popular static-site generators for technical documentation. Combine it with the **MkDocs Material** theme and you get a polished, searchable docs site with almost zero configuration. Add Mermaid.js to that stack and every diagram you write stays in your repo, version-controlled, and auto-rendered in the browser — no image exports, no external tools.

This guide covers every way to enable Mermaid in MkDocs, including the recommended plugin approach, dark mode support, and solutions to the most common rendering problems.

## Two Ways to Enable Mermaid in MkDocs

There are two main approaches:

1. **MkDocs Material built-in support** (recommended — zero extra dependencies if you're already on Material)
2. **mkdocs-mermaid2-plugin** (works with any MkDocs theme)

Choose based on which theme you're using. If you're on Material, use the built-in approach. If you're on a different theme, use the plugin.

## Approach 1 — MkDocs Material Built-In (Recommended)

MkDocs Material (version 8.2+) ships with native Mermaid support. You don't need any extra packages.

### Step 1: Install MkDocs Material

```bash
pip install mkdocs-material
```

If you're starting fresh:

```bash
pip install mkdocs-material
mkdocs new my-docs
cd my-docs
```

### Step 2: Enable SuperFences in mkdocs.yml

MkDocs Material renders Mermaid via the **SuperFences** extension from PyMdown Extensions. Enable it in your `mkdocs.yml`:

```yaml
site_name: My Docs
theme:
  name: material

markdown_extensions:
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format
```

That's it. You can now use Mermaid diagrams in any Markdown file.

### Step 3: Add a Diagram to Your Docs

In any `.md` file:

```mermaid
graph TD
    A[User] --> B[MkDocs Site]
    B --> C[Documentation]
    C --> D[Happy Developer]
```

Run `mkdocs serve` and open your browser — the diagram renders live.

## Approach 2 — mkdocs-mermaid2-plugin

If you're using a different theme (like ReadTheDocs or a custom theme), install the dedicated plugin:

```bash
pip install mkdocs-mermaid2-plugin
```

Then add to `mkdocs.yml`:

```yaml
site_name: My Docs

plugins:
  - search
  - mermaid2
```

Write diagrams in fenced code blocks just as you would anywhere else:

```mermaid
sequenceDiagram
    Alice->>Bob: Hello
    Bob-->>Alice: Hi there!
```

## Dark Mode Support (MkDocs Material)

MkDocs Material supports automatic light/dark mode switching. Mermaid diagrams need to match. Material handles this automatically when you configure color schemes correctly — but there's one thing you must **not** do.

### What to Avoid

Do not load Mermaid via a custom JavaScript snippet or CDN import in `extra_javascript`. If you do, you break Material's automatic color-scheme switching and diagrams will be stuck in light mode even when dark mode is active.

The built-in SuperFences integration detects the active color scheme and passes the correct Mermaid theme automatically.

### Configure Light + Dark Schemes

```yaml
theme:
  name: material
  palette:
    - scheme: default
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    - scheme: slate
      toggle:
        icon: material/brightness-4
        name: Switch to light mode
```

With this config, diagrams in light mode use Mermaid's `default` theme, and diagrams in dark mode use the `dark` theme automatically.

## Custom Mermaid Themes Per Diagram

Override the theme for individual diagrams using the `%%{init}%%` directive:

```mermaid
%%{init: {"theme": "forest"}}%%
graph LR
    A --> B --> C
```

Available themes: `default`, `dark`, `forest`, `neutral`, `base`.

For `base` (most customizable):

```mermaid
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#1a73e8", "primaryTextColor": "#fff", "primaryBorderColor": "#174ea6"}}}%%
graph TD
    A[Custom Styled Diagram]
```

## Real-World Diagram Examples for Documentation Sites

### API Request Flow (Sequence Diagram)

Place this directly in your API reference docs, right next to the endpoint description:

```mermaid
sequenceDiagram
    participant Client
    participant API
    participant DB

    Client->>API: GET /api/users
    API->>DB: SELECT * FROM users
    DB-->>API: Rows
    API-->>Client: JSON response
```

### System Architecture (Flowchart)

```mermaid
graph TB
    subgraph Frontend
        UI[React App]
    end
    subgraph Backend
        API[FastAPI]
        Worker[Celery Worker]
        Cache[Redis]
    end
    subgraph Data
        DB[(PostgreSQL)]
        S3[S3 Storage]
    end

    UI -->|HTTPS| API
    API --> Cache
    API --> DB
    API --> Worker
    Worker --> S3
```

### Data Model (ER Diagram)

```mermaid
erDiagram
    USER ||--o{ POST : creates
    POST ||--o{ COMMENT : has
    USER ||--o{ COMMENT : writes

    USER {
        int id PK
        string email
        string username
        datetime created_at
    }
    POST {
        int id PK
        int user_id FK
        string title
        text body
        datetime published_at
    }
    COMMENT {
        int id PK
        int user_id FK
        int post_id FK
        text content
    }
```

### Deployment Pipeline (Gantt Chart)

```mermaid
gantt
    title Release Pipeline
    dateFormat YYYY-MM-DD
    axisFormat %b %d

    section Build
    Lint and Type Check   :done, a1, 2026-06-01, 1d
    Unit Tests            :done, a2, after a1, 1d
    Build Docker Image    :done, a3, after a2, 1d

    section Deploy
    Staging Deploy        :active, b1, after a3, 2d
    Smoke Tests           :b2, after b1, 1d
    Production Deploy     :crit, b3, after b2, 1d
```

## Organizing Diagrams in a Larger Docs Site

### Put Diagrams Close to Their Content

Don't create a separate "diagrams" page. Embed diagrams directly in the relevant documentation section. A sequence diagram for the auth flow belongs in the auth documentation page — not in a "diagrams gallery."

### Use a Text Description Above Each Diagram

Make diagrams accessible and scannable:

```markdown
The following diagram shows the OAuth 2.0 token exchange flow:
```

### Store Complex Diagrams as .mmd Files

For very complex diagrams that appear in multiple places, store them in a `docs/diagrams/` folder as `.mmd` files and include them via a custom macro or MkDocs plugin. This avoids copy-paste drift when diagrams need updating.

## Full mkdocs.yml Reference (MkDocs Material + Mermaid)

Here's a production-ready `mkdocs.yml` with Mermaid, search, and navigation configured:

```yaml
site_name: My Project Docs
site_url: https://docs.myproject.com
repo_url: https://github.com/myorg/myproject

theme:
  name: material
  palette:
    - scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    - scheme: slate
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-4
        name: Switch to light mode
  features:
    - navigation.tabs
    - navigation.sections
    - toc.integrate
    - search.highlight

markdown_extensions:
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format
  - pymdownx.highlight:
      anchor_linenums: true
  - admonition
  - toc:
      permalink: true

plugins:
  - search
```

## Troubleshooting Common Issues

### Diagrams Show as Raw Code

**Cause:** The `pymdownx.superfences` extension is missing from `markdown_extensions`, or the `custom_fences` block is misconfigured.

**Fix:** Double-check the YAML indentation — it's whitespace-sensitive and a single misplaced space breaks the whole block. Use a YAML linter to validate your config.

### Diagrams Render in Light Mode Only (Dark Mode Broken)

**Cause:** You loaded Mermaid via `extra_javascript` in addition to the SuperFences config, creating a conflict.

**Fix:** Remove any Mermaid CDN script from `extra_javascript`. The SuperFences integration is fully self-contained.

### `!!python/name:` Causes a YAML Error

**Cause:** Some YAML parsers reject the `!!python/name:` tag when the module path is not importable.

**Fix:** Ensure `pymdownx` is installed: `pip install pymdownx`. The import path must be exactly `pymdownx.superfences.fence_code_format`.

### New Mermaid Syntax Not Rendering

**Cause:** The mkdocs-mermaid2-plugin bundles a specific Mermaid version and newer syntax (like `block-beta` or `packet`) may not be available.

**Fix:** Pin a newer Mermaid version in your `mkdocs.yml`:

```yaml
plugins:
  - mermaid2:
      version: 11.0.0
```

## Deploying MkDocs with Mermaid Diagrams

MkDocs builds to static HTML, deployable to GitHub Pages, Netlify, Vercel, or Cloudflare Pages.

### GitHub Actions Deploy

```yaml
name: Deploy Docs
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install mkdocs-material pymdownx
      - run: mkdocs gh-deploy --force
```

Mermaid diagrams render client-side in JavaScript, so no special build step is needed. The HTML output includes fenced code blocks with the `mermaid` class, and the Mermaid library renders them in the visitor's browser.

## Why MkDocs + Mermaid Is the Best Docs-as-Code Setup

Other approaches either lock diagrams in binary image files (PNG exports) or require an external tool account (Lucidchart, draw.io Cloud). The MkDocs + Mermaid combination gives you:

- **Diagrams as code** — version-controlled in the same repo as your docs
- **Automatic dark mode** — Material theme handles it with zero extra config
- **Native Markdown syntax** — no shortcodes, no plugins, no learning curve
- **Static output** — fast, cacheable, deployable anywhere
- **Git-friendly** — diffs are readable, reviews are meaningful, history is preserved

For developer-facing documentation — APIs, internal tools, open-source libraries — this is one of the highest-leverage documentation setups you can adopt in 2026.

## Conclusion

Adding Mermaid to MkDocs takes about five minutes: install Material, add the SuperFences config block to `mkdocs.yml`, and start writing ```mermaid code fences. Every architecture decision, API flow, data model, and deployment pipeline you document becomes a maintainable, version-controlled asset.

Before embedding diagrams in your docs, prototype them in a live editor to see the output instantly.

[Try Mermaid diagrams live in our free editor →](/)

### All Mermaid.js Diagram Types Explained (With Examples)
URL: https://mermaideditor.lol/blog/mermaid-diagram-types
Published: 2026-06-16
Updated: 2026-06-16
Description: A complete guide to every Mermaid.js diagram type: flowchart, sequence, class, ER, Gantt, state, mindmap, timeline, pie, quadrant, git graph, and more — with live examples.

## What Diagram Types Does Mermaid.js Support?

Mermaid.js is not just a flowchart tool. As of 2026, it supports **13+ distinct diagram types** — covering everything from database schemas and git history to user journeys and data flows. Each type has its own syntax, use cases, and strengths.

This guide walks through every major Mermaid diagram type with a quick example and a summary of when to use it.

## 1. Flowchart

The most-used diagram type. Flowcharts visualize processes, decision trees, and system flows. Mermaid supports four layout directions: **TD** (top-down), **LR** (left-right), **BT** (bottom-top), **RL** (right-left).

```mermaid
flowchart LR
    Start([Start]) --> Input[/User Input/]
    Input --> Validate{Valid?}
    Validate -->|Yes| Process[Process Data]
    Validate -->|No| Error[Show Error]
    Process --> Output([Done])
    Error --> Input
```

**Best for:** Process flows, decision trees, architecture overviews, user flows, CI/CD pipelines.

## 2. Sequence Diagram

Shows interactions between actors over time — who sends what message to whom, in what order.

```mermaid
sequenceDiagram
    autonumber
    actor User
    participant API
    participant DB

    User->>API: POST /login
    API->>DB: SELECT user WHERE email=?
    DB-->>API: User record
    API-->>User: 200 OK + JWT token
```

**Best for:** API call flows, authentication sequences, microservice communication, protocol documentation.

## 3. Class Diagram

Represents object-oriented structures: classes, attributes, methods, and their relationships (inheritance, composition, association).

```mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +speak() void
    }
    class Dog {
        +String breed
        +fetch() void
    }
    class Cat {
        +boolean indoor
        +purr() void
    }
    Animal <|-- Dog
    Animal <|-- Cat
```

**Best for:** OOP design documentation, code architecture, domain modeling, API object schemas.

## 4. Entity Relationship (ER) Diagram

Documents database schemas — tables, columns, data types, and relationships with cardinality.

```mermaid
erDiagram
    USER {
        int id PK
        string email UK
        string name
    }
    POST {
        int id PK
        string title
        int user_id FK
    }
    COMMENT {
        int id PK
        text body
        int post_id FK
        int user_id FK
    }
    USER ||--o{ POST : writes
    POST ||--o{ COMMENT : has
    USER ||--o{ COMMENT : writes
```

**Best for:** Database design, schema documentation, data modeling, migration planning.

## 5. Gantt Chart

Project timeline visualization — tasks, durations, milestones, and dependencies.

```mermaid
gantt
    title Project Roadmap Q3 2026
    dateFormat YYYY-MM-DD
    section Backend
        API design       :done,    a1, 2026-07-01, 7d
        DB schema        :done,    a2, after a1, 5d
        Core endpoints   :active,  a3, after a2, 14d
    section Frontend
        UI components    :         b1, 2026-07-10, 10d
        Integration      :         b2, after b1, 7d
    section Launch
        QA testing       :         c1, after a3, 5d
        Deploy           :milestone, c2, after c1, 0d
```

**Best for:** Project planning, sprint tracking, roadmaps, release timelines.

## 6. State Diagram

Models finite state machines — the states an entity can be in and the transitions between them.

```mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : submit
    Processing --> Success : result OK
    Processing --> Failed : result error
    Failed --> Idle : retry
    Success --> [*]
```

**Best for:** UI state machines, order lifecycles, session states, workflow engines, protocol modeling.

## 7. Mindmap

Hierarchical branching structure for brainstorming and knowledge organization.

```mermaid
mindmap
  root((Mermaid.js))
    Diagrams
      Flowchart
      Sequence
      Class
      ER
    Integrations
      GitHub
      Notion
      VS Code
      Obsidian
    Features
      Themes
      Dark mode
      Click events
```

**Best for:** Brainstorming, knowledge maps, feature breakdowns, study notes.

## 8. Timeline

Displays events along a chronological axis, grouped by time periods.

```mermaid
timeline
    title History of JavaScript Frameworks
    2010 : Backbone.js
         : AngularJS
    2013 : React
    2014 : Vue.js
    2016 : Angular 2
    2019 : Svelte 3
    2022 : SolidJS gains traction
    2024 : React Server Components mainstream
```

**Best for:** Historical timelines, product roadmaps, release histories, organizational milestones.

## 9. Pie Chart

Simple proportional visualization — how parts make up a whole.

```mermaid
pie title Browser Market Share 2026
    "Chrome" : 63
    "Safari" : 20
    "Firefox" : 7
    "Edge" : 6
    "Other" : 4
```

**Best for:** Distribution breakdowns, budget allocations, survey results, technology share snapshots. Keep slices to 5–7 max.

## 10. Quadrant Chart

Plots items on a 2×2 grid based on two axes — great for prioritization matrices.

```mermaid
quadrantChart
    title Feature Prioritization Matrix
    x-axis Low Effort --> High Effort
    y-axis Low Impact --> High Impact
    quadrant-1 Do First
    quadrant-2 Plan
    quadrant-3 Delegate
    quadrant-4 Deprioritize
    Auth Redesign: [0.3, 0.8]
    Dark Mode: [0.2, 0.5]
    Dashboard V2: [0.7, 0.9]
    Export PDF: [0.6, 0.4]
    Onboarding Tour: [0.4, 0.7]
```

**Best for:** Feature prioritization, tech debt triage, risk assessment, 2×2 strategy matrices.

## 11. Git Graph

Visualizes git branch history — commits, branches, merges, and tags.

```mermaid
gitGraph
    commit id: "init"
    branch develop
    checkout develop
    commit id: "feature A"
    commit id: "feature B"
    branch feature/login
    commit id: "login UI"
    commit id: "auth API"
    checkout develop
    merge feature/login
    checkout main
    merge develop tag: "v1.0"
```

**Best for:** Documenting branching strategies (GitFlow, trunk-based), explaining merge workflows, teaching Git concepts.

## 12. C4 Architecture Diagram

Structured system architecture at four levels: Context, Container, Component, and Code.

```mermaid
C4Context
    title System Context — E-Commerce Platform
    Person(customer, "Customer", "Shops online")
    System(shop, "E-Commerce App", "Product catalog, cart, checkout")
    System_Ext(payment, "Payment Gateway", "Stripe / Razorpay")
    System_Ext(email, "Email Service", "Order confirmations")
    Rel(customer, shop, "Browses and purchases")
    Rel(shop, payment, "Processes payments")
    Rel(shop, email, "Sends confirmations")
```

**Best for:** Enterprise architecture documentation, solution design, onboarding new engineers, stakeholder presentations.

## 13. Sankey Diagram

Shows flows and quantities between nodes — budget allocations, data pipelines, energy flows.

```mermaid
sankey-beta
    Revenue,Product Sales,600
    Revenue,Services,300
    Revenue,Licensing,100
    Product Sales,COGS,250
    Product Sales,Gross Profit,350
    Services,Delivery Cost,120
    Services,Gross Profit,180
    Licensing,Gross Profit,100
```

**Best for:** Financial flows, energy systems, budget waterfall analysis, traffic source breakdowns.

## 14. XY Chart

Bar and line charts for numeric data visualization directly in documentation.

```mermaid
xychart-beta
    title "Monthly Active Users 2026"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Users (thousands)" 0 --> 100
    bar [28, 35, 42, 55, 68, 80]
    line [28, 35, 42, 55, 68, 80]
```

**Best for:** Metrics dashboards in docs, growth charts, performance benchmarks, A/B test results.

## Choosing the Right Diagram Type

| Question | Diagram Type |
|---|---|
| How does this process work? | Flowchart |
| What happens when A calls B? | Sequence |
| How are these classes related? | Class |
| What does the DB schema look like? | ER Diagram |
| When will each task be done? | Gantt |
| What states can this object be in? | State |
| How do these ideas connect? | Mindmap |
| What happened when? | Timeline |
| What share does each part have? | Pie Chart |
| Which features should we prioritize? | Quadrant |
| How does our Git branching work? | Git Graph |
| How is the system structured? | C4 |
| Where does the data/money flow? | Sankey |
| How have metrics changed over time? | XY Chart |

## Tips for Picking the Right Diagram

1. **Match the question, not the data.** Every diagram type answers a specific question. Start with "What am I trying to communicate?" — the right type becomes obvious.

2. **Start simple.** A flowchart with 5 nodes beats a sprawling C4 diagram with 40 boxes when you're explaining a quick concept.

3. **Use multiple types together.** A README might have a C4 context diagram for the overview, an ER diagram for the data model, and a sequence diagram for a key API flow. They complement each other.

4. **Version-control them all.** Because Mermaid is text, every diagram lives in your repo alongside the code it documents. Change the code, update the diagram in the same PR.

5. **Test in a live editor first.** Before embedding a diagram in docs, prototype it in a live Mermaid editor to catch syntax errors and refine the layout.

## Conclusion

Mermaid.js gives developers a single text-based toolkit for 14+ diagram types — from simple flowcharts to full C4 architecture models. Learning which diagram type fits each situation is the real skill. Use this guide as your reference, and start prototyping your next diagram in the editor below.

[Try every diagram type in our free Mermaid editor →](/)

### Mermaid Kubernetes Architecture Diagrams: Examples
URL: https://mermaideditor.lol/blog/mermaid-kubernetes-architecture-diagrams
Published: 2026-06-19
Updated: 2026-06-19
Description: Learn how to diagram Kubernetes clusters, deployments, and microservices architecture using Mermaid.js. Includes K8s namespace, ingress, service mesh, and pod topology examples.

# Mermaid.js Kubernetes Architecture Diagrams: Complete Guide with Examples

Kubernetes architectures are notoriously hard to document. YAML files describe individual resources, but no single file shows you the whole picture — how pods connect to services, which ingresses route to which deployments, or how namespaces carve up your cluster.

Mermaid.js fixes this. Because diagrams are plain text, they live in your repo alongside your manifests, get reviewed in pull requests, and stay current when your architecture changes.

This guide shows you how to diagram real Kubernetes architectures using Mermaid — from single-cluster deployments to multi-namespace service meshes.

## Why Mermaid for Kubernetes Diagrams?

Before diving into syntax, here's why text-based diagrams beat GUI tools for K8s documentation:

- **Lives in the repo.** Your diagram is a `.md` file next to your Helm chart. Change the chart, update the diagram in the same PR.
- **Diffs like code.** When you add a sidecar or change an ingress rule, the diff shows exactly what changed — not a blob binary.
- **Renders everywhere.** GitHub, GitLab, Confluence, and Notion all render Mermaid natively. Your architecture docs look great without a separate tool.
- **Fast to write.** Once you know the syntax, you can sketch a 20-node cluster diagram in under 5 minutes.

## Basic Kubernetes Cluster Diagram

Let's start with the most common diagram: showing what's running inside a cluster.

```mermaid
flowchart TD
    subgraph Cluster["Kubernetes Cluster"]
        subgraph NS1["Namespace: production"]
            ING["Ingress nginx"]
            SVC1["Service frontend"]
            SVC2["Service backend"]
            DEP1["Deployment: frontend 3 replicas"]
            DEP2["Deployment: backend 2 replicas"]
        end
        subgraph NS2["Namespace: data"]
            SVC3["Service postgres"]
            SS1["StatefulSet: postgres"]
        end
    end
    Internet(["Internet"]) --> ING
    ING --> SVC1
    ING --> SVC2
    SVC1 --> DEP1
    SVC2 --> DEP2
    DEP2 --> SVC3
    SVC3 --> SS1
```

This single diagram answers the question most engineers ask first: *what's in this cluster and how does traffic flow through it?*

## Pod-to-Pod Communication

For deeper architectural diagrams, show pod topology and how services route between pods:

```mermaid
flowchart LR
    subgraph Node1["Node: worker-1"]
        P1["Pod: frontend-abc 10.0.0.1"]
        P2["Pod: backend-def 10.0.0.2"]
    end
    subgraph Node2["Node: worker-2"]
        P3["Pod: backend-ghi 10.0.0.3"]
        P4["Pod: redis-jkl 10.0.0.4"]
    end

    SVC_FE["Service: frontend ClusterIP"]
    SVC_BE["Service: backend ClusterIP"]
    SVC_CACHE["Service: redis ClusterIP"]
    ING["Ingress nginx"]

    ING --> SVC_FE
    SVC_FE --> P1
    P1 --> SVC_BE
    SVC_BE --> P2
    SVC_BE --> P3
    P2 --> SVC_CACHE
    P3 --> SVC_CACHE
    SVC_CACHE --> P4
```

Showing node assignments makes capacity planning much clearer — you can see at a glance that worker-2 carries both backend replicas and the cache.

## Kubernetes Deployment Rollout Flow

Use a sequence diagram to document how a deployment rollout happens step by step:

```mermaid
sequenceDiagram
    participant Dev as Developer
    participant GH as GitHub Actions
    participant REG as Container Registry
    participant K8S as Kubernetes API
    participant DEP as Deployment Controller

    Dev->>GH: git push / PR merge
    GH->>GH: Build and test
    GH->>REG: Push image tag v1.2.3
    GH->>K8S: kubectl apply new image tag
    K8S->>DEP: Update Deployment spec
    DEP->>DEP: Create new ReplicaSet
    loop Rolling Update
        DEP->>DEP: Scale up new RS by 1
        DEP->>DEP: Scale down old RS by 1
        DEP->>DEP: Wait for readiness probe
    end
    DEP->>K8S: Deployment complete
    K8S->>GH: Webhook: rollout success
    GH->>Dev: Notify: deployed to production
```

This is exactly the kind of diagram to put in your runbook — new team members understand the full CI/CD pipeline without reading three separate docs.

## Ingress and Service Mesh Architecture

For setups with Istio or Linkerd, a layered diagram captures the mesh clearly:

```mermaid
flowchart TD
    subgraph Edge["Edge Layer"]
        CF["CloudFront CDN"]
        NLB["Network Load Balancer"]
    end

    subgraph Mesh["Istio Service Mesh"]
        GW["Istio Gateway"]
        subgraph VS["Virtual Services"]
            VS1["VirtualService /api to backend"]
            VS2["VirtualService / to frontend"]
        end
        subgraph Workloads["Workloads and Sidecars"]
            direction LR
            FE["frontend pod + envoy proxy"]
            BE["backend pod + envoy proxy"]
            AUTH["auth-service + envoy proxy"]
        end
    end

    subgraph Infra["Infrastructure"]
        DB[("PostgreSQL RDS")]
        CACHE[("Redis ElastiCache")]
    end

    CF --> NLB --> GW
    GW --> VS1 --> BE
    GW --> VS2 --> FE
    BE --> AUTH
    BE --> DB
    BE --> CACHE
    FE --> BE
```

## Multi-Environment Deployment Strategy

Document how code moves from dev to staging to production:

```mermaid
flowchart LR
    subgraph Dev["Cluster: dev"]
        D_APP["app: latest"]
        D_DB[("postgres dev-db")]
    end

    subgraph Staging["Cluster: staging"]
        S_APP["app: v1.2.3-rc"]
        S_DB[("postgres staging-db")]
    end

    subgraph Prod["Cluster: production"]
        P_APP["app: v1.2.2 to v1.2.3"]
        P_DB[("postgres prod-db RDS")]
    end

    CI["CI/CD Pipeline GitHub Actions"]
    CI -->|"auto-deploy on PR merge"| Dev
    Dev -->|"promote on tag"| Staging
    Staging -->|"manual approval + canary"| Prod
```

## Kubernetes RBAC Model

Role-Based Access Control is notoriously hard to explain in prose. A diagram makes it click instantly:

```mermaid
flowchart TD
    subgraph Subjects
        U1["User: alice"]
        U2["ServiceAccount: ci-runner"]
        G1["Group: platform-eng"]
    end

    subgraph RoleBindings
        RB1["ClusterRoleBinding: cluster-admin"]
        RB2["RoleBinding ns:production deploy-role"]
        RB3["RoleBinding ns:production view-only"]
    end

    subgraph Roles
        CR1["ClusterRole: cluster-admin"]
        R1["Role: deploy-role deploys and rollouts"]
        R2["Role: view-only read all resources"]
    end

    G1 --> RB1 --> CR1
    U2 --> RB2 --> R1
    U1 --> RB3 --> R2

    classDef subject fill:#3b82f6,color:#fff,stroke:#1d4ed8
    classDef binding fill:#f59e0b,color:#fff,stroke:#b45309
    classDef role fill:#10b981,color:#fff,stroke:#047857
    class U1,U2,G1 subject
    class RB1,RB2,RB3 binding
    class CR1,R1,R2 role
```

The color coding (blue = subjects, amber = bindings, green = roles) maps directly to the three-part RBAC model and makes onboarding new engineers dramatically faster.

## StatefulSet and Persistent Volume Architecture

For databases and stateful workloads, showing how PVCs bind to PVs clarifies the storage layer:

```mermaid
flowchart TD
    subgraph StatefulSet["StatefulSet: postgres"]
        P0["Pod: postgres-0 10.0.0.10"]
        P1["Pod: postgres-1 10.0.0.11"]
        P2["Pod: postgres-2 10.0.0.12"]
    end

    subgraph PVCs["PersistentVolumeClaims"]
        PVC0["PVC: data-postgres-0"]
        PVC1["PVC: data-postgres-1"]
        PVC2["PVC: data-postgres-2"]
    end

    subgraph Storage["Storage: AWS EBS"]
        PV0["PV: vol-abc123 100Gi gp3"]
        PV1["PV: vol-def456 100Gi gp3"]
        PV2["PV: vol-ghi789 100Gi gp3"]
    end

    P0 --> PVC0 --> PV0
    P1 --> PVC1 --> PV1
    P2 --> PVC2 --> PV2

    SVC_HEAD["Headless Service postgres"]
    SVC_READ["Service postgres-read replicas only"]
    SVC_HEAD --> P0 & P1 & P2
    SVC_READ --> P1 & P2
```

This is extremely valuable in incident postmortems — you can see exactly which pod owns which volume when a storage issue hits.

## Kubernetes HPA Autoscaling Logic

Document autoscaling behavior with a state diagram:

```mermaid
stateDiagram-v2
    [*] --> Stable: Deployment healthy
    Stable --> ScalingUp: CPU over 70pct for 3m
    ScalingUp --> Stable: Replicas added and CPU normalized
    Stable --> ScalingDown: CPU under 30pct for 5m
    ScalingDown --> Stable: Replicas removed min floor hit
    ScalingUp --> MaxCapacity: maxReplicas=10 reached
    MaxCapacity --> Alerting: CPU still over 90pct
    Alerting --> [*]: PagerDuty alert sent
```

## Where to Put Each Diagram in Your Repo

| Diagram | Recommended location |
|---|---|
| Cluster overview | Main README.md |
| Rollout flow | docs/runbooks/deployments.md |
| RBAC model | docs/security/rbac.md |
| Multi-environment topology | docs/architecture/environments.md |
| StatefulSet and storage | docs/architecture/databases.md |
| HPA scaling logic | docs/runbooks/scaling.md |

All of these render natively in GitHub and GitLab. If you are on Confluence, use the Mermaid for Confluence plugin — or paste into the [Mermaid Editor](https://mermaideditor.lol) and export as PNG.

## Tips for Clean Kubernetes Diagrams

**1. Use subgraphs for every namespace.** Namespaces are the primary unit of isolation in K8s. They should always be visually distinct in your diagrams.

**2. Show services, not just pods.** Pods are ephemeral — services are how components find each other. Route your arrows through services, not pod names.

**3. Label your arrows.** An unlabeled arrow tells you nothing. Add a short label to every connection that carries meaningful context. Spend the extra two seconds — reviewers will thank you.

**4. Keep secrets and ConfigMaps implicit.** Showing every ConfigMap mount clutters the diagram. Unless the secret itself is architecturally significant (like a Vault integration), leave it out.

**5. Color-code by layer.** In complex diagrams, consistent color coding (ingress = blue, services = green, databases = purple) makes scanning much faster and helps new engineers orient themselves instantly.

**6. Update diagrams with manifests.** When you add a service or change an ingress rule, update the diagram in the same commit. Reviewers can check the diagram diff alongside the YAML diff — dramatically reducing review time.

## Common Pitfalls

- **Too many nodes in one diagram.** If your cluster diagram has 40+ nodes, split it by namespace or concern. One diagram per namespace often works well.
- **Showing pod names instead of deployment names.** Pod names are generated and change on every restart. Show the Deployment or StatefulSet name instead.
- **Mixing abstraction levels.** Don't put AWS account topology and individual pod routing in the same diagram. Pick one level of abstraction and stick to it.
- **Forgetting to update diagrams.** Stale diagrams are worse than no diagrams. Set a team convention: if you change a manifest, you update the relevant diagram in the same PR.

## Conclusion

Mermaid.js is one of the best tools for documenting Kubernetes architectures. The text-based approach fits perfectly with the Infrastructure-as-Code mindset: your architecture diagram *is* code, lives in your repo, and evolves with your cluster.

Start with a simple cluster overview in your README, then expand to rollout runbooks, RBAC models, and per-namespace topology docs as your cluster grows.

[Try building your Kubernetes architecture diagram in the free editor →](/)

### Mermaid.js in React: Complete Integration Guide
URL: https://mermaideditor.lol/blog/mermaid-js-in-react
Published: 2026-06-23
Updated: 2026-06-23
Description: Step-by-step guide to integrating Mermaid.js into a React app. Covers hooks, dynamic rendering, dark mode, SSR pitfalls, and a reusable MermaidDiagram component.

# How to Use Mermaid.js in React — Complete Integration Guide (2026)

Mermaid.js renders diagrams from plain text, and React is the most popular UI framework for building web apps. Putting them together seems obvious — but there are a few gotchas that catch most developers the first time. This guide walks you through the cleanest, most production-ready approach.

By the end you'll have a reusable `` component that handles re-renders, dark mode, and server-side rendering safely.

## Installing Mermaid

```bash
npm install mermaid
# or
yarn add mermaid
```

Mermaid v11 is the current stable release. It ships as an ES module, which works great with modern React toolchains (Vite, Next.js App Router, Create React App).

## The Problem with Naive Integration

You might try something like this:

```tsx
// ❌ Don't do this
import mermaid from 'mermaid';

function BadDiagram({ chart }: { chart: string }) {
  mermaid.initialize({ startOnLoad: true });
  return 
{chart}
; } ``` This breaks in several ways: - `initialize` runs on every render - Mermaid tries to find `.mermaid` elements in the DOM before React has committed them - On re-renders, old SVGs stack up inside the div - On Next.js (SSR), it throws because `document` doesn't exist on the server Here's the right approach. ## A Reusable MermaidDiagram Component ```tsx // components/MermaidDiagram.tsx 'use client'; // Next.js App Router only — remove for plain React/Vite import { useEffect, useRef, useState } from 'react'; import mermaid from 'mermaid'; let initialized = false; function initMermaid(theme: 'default' | 'dark' | 'neutral' | 'forest' = 'default') { if (initialized) return; mermaid.initialize({ startOnLoad: false, theme, securityLevel: 'loose', fontFamily: 'inherit', }); initialized = true; } interface MermaidDiagramProps { chart: string; theme?: 'default' | 'dark' | 'neutral' | 'forest'; className?: string; } export default function MermaidDiagram({ chart, theme = 'default', className = '', }: MermaidDiagramProps) { const containerRef = useRef(null); const [error, setError] = useState(null); const [svg, setSvg] = useState(''); useEffect(() => { initMermaid(theme); let cancelled = false; async function render() { try { const id = 'mermaid-' + Math.random().toString(36).slice(2, 9); const { svg: renderedSvg } = await mermaid.render(id, chart); if (!cancelled) { setSvg(renderedSvg); setError(null); } } catch (err) { if (!cancelled) { setError(err instanceof Error ? err.message : 'Render error'); setSvg(''); } } } render(); return () => { cancelled = true; }; }, [chart, theme]); if (error) { return (
Diagram error: {error}
); } return (
); } ``` ### Why This Works - **`startOnLoad: false`** — Mermaid won't try to scan the DOM automatically; we call `mermaid.render()` manually. - **`useEffect` with cleanup** — the `cancelled` flag prevents stale renders from updating state after a prop change races against a new render. - **Unique IDs** — `mermaid.render()` creates temporary DOM nodes; unique IDs prevent ID collisions when multiple diagrams are on the same page. - **`dangerouslySetInnerHTML`** — Mermaid returns a finished SVG string. Setting it via `innerHTML` is the correct approach; the content comes from the Mermaid library, not user input. ## Usage ```tsx import MermaidDiagram from '@/components/MermaidDiagram'; const chart = ` flowchart LR A[User] --> B[API] B --> C[(Database)] B --> D[Cache] `; export default function DocsPage() { return (

System Architecture

); } ``` ## Dynamic Charts with User Input One powerful use case is letting users write Mermaid syntax and see a live preview — exactly what [MermaidEditor.lol](https://mermaideditor.lol) does. ```tsx 'use client'; import { useState } from 'react'; import MermaidDiagram from '@/components/MermaidDiagram'; const defaultChart = `flowchart TD A[Start] --> B{Decision} B -->|Yes| C[Action 1] B -->|No| D[Action 2]`; export default function LiveEditor() { const [chart, setChart] = useState(defaultChart); return (