How to create a Git graph (gitGraph) diagram in MermaidJS

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 Git graph, start the definition with gitGraph. Add commits with commit, create a branch with branch name, switch the active branch with checkout name, and bring one branch's history into another with merge name. Optionally tag a merge commit with tag: "label".

gitGraph
    commit id: "init"
    commit id: "setup"
    branch develop
    checkout develop
    commit id: "feature-a"
    commit id: "feature-b"
    checkout main
    commit id: "hotfix"
    checkout develop
    merge main
    commit id: "feature-c"
    checkout main
    merge develop tag: "v1.0"

Here, develop branches off main after the initial commits, picks up its own feature commits, absorbs a hotfix landed directly on main via merge main, then is merged back into main and tagged v1.0.

3. Branches, cherry-picks, and commit types

Use branch name / checkout name to create and switch branches, cherry-pick id: "id" to bring a single commit from another branch onto the current one, and type: HIGHLIGHT (or NORMAL/REVERSE) to change how a commit is drawn:

ElementSyntaxMeaning
Commitcommit id: "c1"Adds a commit on the current branch (round dot)
Branchbranch featureCreates a new branch from the current commit
Checkoutcheckout featureSwitches the active branch for subsequent commands
Cherry-pickcherry-pick id: "c2"Copies a commit from another branch onto the current one
Highlighted commitcommit id: "c3" type: HIGHLIGHTDraws the commit as a filled square instead of a dot

4. Merges and tags

Use merge name to merge another branch into the currently checked-out branch (as shown for both merge main and merge develop above), and append tag: "label" to a merge or commit to attach a version label to that point in history.

5. 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">
      gitGraph
        commit id: "init"
        commit id: "setup"
        branch develop
        checkout develop
        commit id: "feature-a"
        commit id: "feature-b"
        checkout main
        commit id: "hotfix"
        checkout develop
        merge main
        commit id: "feature-c"
        checkout main
        merge develop tag: "v1.0"
    </div>
  </body>
</html>

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