Skip to main content
Mermaid needs to be initialized before it can render diagrams. The initialization process sets up the rendering engine, applies configuration, and prepares Mermaid to find and process diagram code.

Quick start

The simplest way to initialize Mermaid is to call initialize() before rendering:
import mermaid from 'mermaid';

mermaid.initialize({ startOnLoad: true });
With startOnLoad: true, Mermaid automatically finds and renders all elements with the class mermaid when the page loads.

Initialization methods

The easiest method for static pages:
<!DOCTYPE html>
<html>
  <head>
    <script type="module">
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.esm.min.mjs';
      mermaid.initialize({ startOnLoad: true });
    </script>
  </head>
  <body>
    <div class="mermaid">
      flowchart LR
        A --> B
    </div>
  </body>
</html>
Mermaid listens for the load event and automatically processes all .mermaid elements.

Configuration options

The initialize() function accepts a configuration object. Here are the most commonly used options:

Basic options

mermaid.initialize({
  // Auto-render on page load
  startOnLoad: true,
  
  // Visual theme
  theme: 'default', // 'default' | 'dark' | 'forest' | 'neutral' | 'base'
  
  // Logging level
  logLevel: 'error', // 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
  
  // Security level
  securityLevel: 'strict', // 'strict' | 'loose' | 'sandbox'
  
  // Generate deterministic IDs
  deterministicIds: false,
  deterministicIDSeed: undefined,
});

Security levels

  • strict (default): Prevents potentially dangerous features. Tags in text are encoded, click functionality is disabled.
  • loose: Allows more features but can be a security risk. Enables click events and allows some HTML.
  • sandbox: Renders diagrams in a sandboxed iframe for maximum security.
mermaid.initialize({
  securityLevel: 'strict', // Recommended for user-generated content
});

Theme configuration

mermaid.initialize({
  theme: 'base',
  themeVariables: {
    primaryColor: '#BB2528',
    primaryTextColor: '#fff',
    primaryBorderColor: '#7C0000',
    lineColor: '#F8B229',
    secondaryColor: '#006100',
    tertiaryColor: '#fff'
  }
});
See the theming guide for more details.

The run() function

The run() function is the modern way to render diagrams:
interface RunOptions {
  // CSS selector for finding diagrams (default: '.mermaid')
  querySelector?: string;
  
  // Specific nodes to render (overrides querySelector)
  nodes?: ArrayLike<HTMLElement>;
  
  // Callback after each diagram renders
  postRenderCallback?: (id: string) => unknown;
  
  // Suppress errors instead of throwing
  suppressErrors?: boolean;
}

await mermaid.run(options);

Examples

// Only render diagrams in a specific container
await mermaid.run({
  querySelector: '#content .diagram'
});

The render() function

For programmatic diagram generation without DOM elements:
const graphDefinition = `
  flowchart TB
    A[Start] --> B{Decision}
    B -->|Yes| C[Continue]
    B -->|No| D[Stop]
`;

const { svg, bindFunctions } = await mermaid.render(
  'myDiagramId',
  graphDefinition,
  container // optional container element
);

// svg is a string containing the SVG markup
console.log(svg);

// Insert into page
const element = document.querySelector('#target');
element.innerHTML = svg;

// Bind interactive features (clicks, etc.)
if (bindFunctions) {
  bindFunctions(element);
}
The render() function returns a Promise that resolves with the SVG string and optional bind functions. Multiple calls are automatically queued and executed serially.

Parsing and validation

Use the parse() function to validate diagram syntax without rendering:
// Returns diagram type if valid
try {
  const result = await mermaid.parse('flowchart LR\nA-->B');
  console.log(result); // { diagramType: 'flowchart-v2' }
} catch (error) {
  console.error('Invalid syntax:', error);
}

// Or suppress errors
const result = await mermaid.parse(
  'invalid syntax',
  { suppressErrors: true }
);
console.log(result); // false

Deprecated: init() function

The init() function is deprecated. Use initialize() and run() instead.
Old pattern:
// Deprecated - don't use
mermaid.init(config, '.mermaid');
New pattern:
// Use this instead
mermaid.initialize(config);
await mermaid.run({ querySelector: '.mermaid' });

Framework integration patterns

import { useEffect, useRef } from 'react';
import mermaid from 'mermaid';

mermaid.initialize({ startOnLoad: false });

function MermaidDiagram({ chart }) {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
      mermaid.run({
        nodes: [ref.current]
      });
    }
  }, [chart]);

  return (
    <div ref={ref} className="mermaid">
      {chart}
    </div>
  );
}

Best practices

  1. Initialize once - Call initialize() only once, typically at application startup
  2. Use run() for SPAs - Set startOnLoad: false and manually call run() when needed
  3. Handle errors - Always wrap render calls in try-catch or use suppressErrors
  4. Avoid re-initialization - Don’t call initialize() multiple times; use updateSiteConfig() instead
  5. Process diagrams selectively - Use the nodes option for better performance with many diagrams

Next steps

Configuration

Explore detailed configuration options

Theming

Customize diagram appearance

API reference

Complete API documentation

Deployment

Learn about different deployment methods

Build docs developers (and LLMs) love