How Mermaid `%%{initialize: {...}}%%` Directives Work and What Runtime Settings They Configure
Mermaid directives are special comment blocks that inject runtime configuration directly into diagram definitions, allowing per-diagram theming, logging, and layout controls without modifying global JavaScript settings.
The mermaid-js/mermaid library supports inline configuration through initialization directives embedded directly in diagram source code. These %%{initialize: {...}}%% blocks provide granular control over rendering behavior, security constraints, and layout engines. Understanding how these directives parse, sanitize, and apply settings reveals how to customize individual diagrams while maintaining the integrity of the rendering pipeline.
How Mermaid Parses Initialization Directives
Detecting Directive Blocks
When Mermaid processes diagram text, the detectDirective() function in src/utils.ts (lines 60-90) scans for any %%{ … }%% block. This function first strips ordinary comments and normalizes quotes, then executes a global directiveRegex to identify valid directives. For initialization specifically, the engine looks for keywords matching init or initialize, returning an object containing the type and parsed JSON-like args.
Building Safe Configurations
The detectInit() function, also located in src/utils.ts (lines 66-102), handles the heavy lifting of configuration assembly. It invokes detectDirective() with the regex /(?:init\b)|(?:initialize\b)/ to capture initialization-specific blocks. Before processing arguments, sanitizeDirective() sanitizes raw inputs to prevent injection attacks. When multiple directives exist in a single diagram, Mermaid merges them using assignWithDepth, allowing layered configuration where later directives override earlier ones.
Mapping to Diagram-Specific Keys
Mermaid stores diagram-specific options under top-level keys matching the diagram type (flowchart, sequence, gantt, etc.). The detectInit() function calls detectType() from src/diagram-api/detectType.ts (lines 17-34) to infer the diagram type from the remaining text. If the parsed directive contains a config property, Mermaid automatically relocates that object to the inferred diagram key (results[type] = results.config) and removes the generic config field. This ensures that flowchart-specific settings do not leak into sequence diagrams or other chart types.
Applying Runtime Settings
The resulting plain JavaScript object is passed to mermaid.initialize() in src/mermaid.ts (lines 440-460). This method stores values in the library’s current configuration object (currentConfig), which every diagram renderer references during instantiation. Because this process occurs during parsing, directive-based settings affect only the specific diagram containing the directive, leaving global defaults untouched for subsequent renders.
Runtime Settings Available Through Directives
All keys defined in MermaidConfig (generated from the JSON schema at src/config.type.ts, lines 58-200) are potentially available. However, the secure configuration array (defaulting to ["theme","themeVariables","themeCSS","logLevel",…]) restricts which keys directives may actually override.
Theme and Appearance
theme,themeVariables,themeCSS: Select built-in themes (dark,neutral,forest) or supply custom CSS and variable overrides.fontFamily,fontSize,htmlLabels,darkMode: Control font rendering and label processing globally.
Logging and Behavior
logLevel: Controls console verbosity (0 for fatal errors up to 5 for debug traces).startOnLoad: Determines whether diagrams render automatically when the page loads.deterministicIds,deterministicIDSeed: Configure reproducible SVG ID generation for testing.
Diagram-Specific Configuration
flowchart,sequence,gantt,pie,xyChart,quadrantChart,gitGraph,timeline: Each diagram type accepts its own sub-object of specialized options. ThedetectInit()function automatically routes genericconfigproperties to the appropriate diagram key.
Layout Engines
layout: Choose between default layout orelkfor the Eclipse Layout Kernel.elk: Contains extensive sub-options likenodePlacementStrategywhen using the ELK engine.
Security Constraints
secure: An array of allowed configuration keys that directives may modify. Any key not listed here is ignored unless explicitly added to the array.securityLevel: Restricts rendering capabilities (e.g., disabling HTML tags).
Practical Configuration Examples
Simple Theme and Log Level
%%{init: { "theme": "forest", "logLevel": 2 }}%%
graph TD
A --> B
This directive applies the forest theme and sets logging to info level (2) for this diagram only.
Diagram-Specific Flowchart Settings
%%{init: { "config": { "flowchart": { "htmlLabels": true, "curve": "basis" } } }}%%
flowchart LR
A[Start] --> B{Decision}
B -->|Yes| C[Result]
B -->|No| D[End]
The generic config object is automatically relocated under the flowchart key, so only flowchart diagrams receive these specific curve and label settings.
Custom Theme Variables
%%{init: { "theme": "base", "themeVariables": { "primaryColor": "#ff6600", "fontSize": 20 } }}%%
graph LR
X --> Y
This merges custom CSS variables with the base theme, overriding primary colors and font sizes without creating a complete custom theme file.
ELK Layout Configuration
%%{init: { "layout": "elk", "elk": { "nodePlacementStrategy": "NETWORK_SIMPLEX" } }}%%
flowchart TD
A --> B
B --> C
C --> D
This switches the rendering engine to ELK and applies a specific node-placement algorithm for complex hierarchical layouts.
Summary
- Mermaid directives use the
%%{initialize: {...}}%%syntax (orinitshorthand) to embed JSON configuration directly in diagram source code. - The
detectDirective()anddetectInit()functions insrc/utils.tsparse and sanitize these blocks, whiledetectType()insrc/diagram-api/detectType.tsroutes diagram-specific settings to the correct configuration key. - The
securearray restricts which configuration keys directives may override, preventing unauthorized changes to security-sensitive settings. - All runtime settings from
MermaidConfiginsrc/config.type.tsare available, including themes, logging levels, layout engines, and diagram-type-specific options. - Settings are applied through
mermaid.initialize()insrc/mermaid.ts, affecting only the diagram containing the directive while leaving global defaults intact.
Frequently Asked Questions
What is the difference between init and initialize in Mermaid directives?
There is no functional difference between %%{init: {...}}%% and %%{initialize: {...}}%%. The detectInit() function in src/utils.ts uses the regex /(?:init\b)|(?:initialize\b)/ to recognize both keywords interchangeably, treating them as identical directives for configuration injection.
Can I use multiple initialization directives in a single diagram?
Yes, you can include multiple %%{init: ...}%% blocks in one diagram. The detectInit() function merges them using assignWithDepth, where later directives override earlier ones. This allows you to separate concerns—for example, setting the theme in one directive and diagram-specific options in another.
Why are some of my configuration settings being ignored?
Mermaid ignores directive settings for keys not listed in the secure configuration array. By default, this array only includes safe keys like theme, themeVariables, themeCSS, and logLevel. To enable additional configuration keys, you must explicitly add them to the secure array in your global Mermaid configuration before the directive is processed.
How do I configure settings for a specific diagram type only?
Place your settings inside a config object within the directive. The detectInit() function automatically detects the diagram type using detectType() and moves the config object to the appropriate key (e.g., flowchart or sequence). For example, %%{init: {"config": {"flowchart": {"curve": "basis"}}}%% applies only to flowcharts, while sequence diagrams in the same document remain unaffected.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →