How to create Sequence diagram in MermaidJS

Last modified: March 1, 2023

1. Install MermaidJS

You can install MermaidJS by including the MermaidJS library in your project or by installing it via npm.

npm i mermaid

2. Define the diagram

To create a sequence diagram, you first need to define the diagram using MermaidJS syntax. The syntax for a sequence diagram is as follows

sequenceDiagram
  participant A
  participant B
  A->>B: Message1
  B-->>A: Message2

In this example, we define two participants, A and B, and show two messages being sent between them.

3. Render the diagram

Once you have defined the diagram, you can render it on your webpage by including the MermaidJS library and calling the mermaid function with the diagram definition as a string. Here is an example of how to do this

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
      mermaid.initialize({
        startOnLoad: true
      });
    </script>
  </head>
  <body>
    <div class="mermaid">
      sequenceDiagram
        participant A
        participant B
        A->>B: Message1
        B-->>A: Message2
    </div>
  </body>
</html>

4. Here is how the output looks like

You can use this MermaidJS Playground Link to explore that particular example.