Embedding charts using JavaScript

Last modified by Aurelie Bertrand on 2026/11/24 11:18

🙋 This tutorial is intended for DigDash BI administrators.

⏱ It is designed to be completed independently in 2 hours.



Introduction

In this tutorial, we will set up a complete architecture (back-end and front-end) to use DigDash Flows (charts) embedded via the JavaScript library.

To do this, we will implement a lightweight back-end using Python FastAPI. This component allows us to generate personalisation tokens (newAuthTokenAs) using an API key, whilst hiding this critical key from end users (front-end). We will then need to modify our reverse proxy. Finally, we will create an HTML page with JavaScript to call this API.

Solution Architecture

For security reasons, the DigDash API key must never be transmitted via the client’s browser. The authentication flow is therefore organised as follows:

  • The front-end (JavaScript) calls a secure route on the web server (/generate-user-token).
  • Nginx forwards this request locally to the FastAPI server.
  • FastAPI queries DigDash directly by passing the API key and the required headers, then retrieves the token.
  • The token is returned to our front-end, which can then use it to authenticate and display the flows (charts).

Prerequisites

For this tutorial, and in order to use the `newAuthTokenAs` method, you must enable impersonation. To do this, please follow the instructions in the Advanced: Identity borrowing on the page URL Anonymisation.

In this implementation example, we use an API key for administrator authentication on the DigDash platform. You will therefore need to create a key to use in our back-end API. To do this, please follow the procedure Create an API key.

Step 1: Configuring the Back-end

ℹ This section describes how to install the API server on an Ubuntu machine that is already hosting DigDash Enterprise.

Installing system prerequisites

Log in to your server via SSH and run the following commands to install Python 3 and the virtual environment manager. Python will be the core technology for our back-end.

# Update system repositories
sudo apt update

# Install Python 3, pip, and the venv module
sudo apt install -y python3 python3-venv python3-pip

Initialising the application environment

Create and navigate to a directory of your choice (for example,/var/www/embedded/) to initialise the application:

# Create application folders at the root
mkdir -p /var/www/embedded/

# Navigate to the folder
cd /var/www/embedded/

# Create the Python virtual environment
python3 -m venv venv

# Activate the virtual environment
source venv/bin/activate

# Install required dependencies
pip install fastapi uvicorn httpx

Writing the source code (main.py)

  1. Create a file named main.py in the directory you set up earlier
    sudo vi main.py
  2. Then add the following code to it:

    ⚠ Replace theAPI_KEY variableand the "DIGDASH_DOMAIN" headerwith your own settings.

    from fastapi import FastAPI, HTTPException
    import httpx

    app = FastAPI(title="DigDash Token API")

    # Local configuration: FastAPI communicates directly with Tomcat on port 8080
    DIGDASH_LOCAL_URL = "http://127.0.0.1:8080"

    # CONFIGURATION TO COMPLETE
    API_KEY = "<YOUR_DIGDASH_API_KEY>"
    DIGDASH_DOMAIN = "<YOUR_PUBLIC_DOMAIN_EG_client.digdash.com>"

    @app.get("/generate-user-token")
    async def generate_user_token(target_user: str):
       """
        Generates an authentication token for a target user (newAuthTokenAs).
        """

       # Explicit URL construction for DigDash
        url = f"{DIGDASH_LOCAL_URL}/ddenterpriseapi/DDEnterpriseServlet?method=newAuthTokenAs&userId={target_user}"
       
       # Required headers to identify the DigDash environment and pass the API Key
        headers = {
           "X-API-KEY": API_KEY,
           "Accept": "application/json",
           "Host": DIGDASH_DOMAIN
        }

        async with httpx.AsyncClient() as client:
           try:
                response = await client.get(url, headers=headers)

               # If Tomcat returns an error (401, 404, 500, etc.)
               if response.status_code != 200:
                   raise HTTPException(
                        status_code=response.status_code,
                        detail=f"DigDash Backend Error: {response.text}"
                    )

               # The servlet returns the token to be forwarded to the front-end
                raw_token = response.text
               return {"token": raw_token}

           except httpx.RequestError as exc:
               raise HTTPException(
                    status_code=500,
                    detail=f"Internal communication error with Tomcat: {str(exc)}"
                )

    if __name__ == "__main__":
       import uvicorn
       # Launch the server locally on port 8000
        uvicorn.run(app, host="127.0.0.1", port=8000)

    💡 For production environments, it is recommended to use “.env” files so that the key is not hard-coded directly into the Python file.
    Setting up logs is also strongly recommended for tracking API usage and debugging.

Starting the service

To test that it is working, you can start the process using uvicorn. This will take up your terminal, so you will need to open a new one for the next steps.

# Launch the application (make sure the venv is active)
uvicorn main:app --host 127.0.0.1 --port 8000 --reload

If this command runs successfully, you should see the following message:

INFO: Application startup complete.

💡 For long-term production deployment, it is recommended that you package this command and create a service that starts when your server boots up.

Testing

To verify that our back-end is working, you can run a local `curl` command on our DigDash server.

⚠ Replace the `target_user ` variable with your own test user.

curl -X GET "http://127.0.0.1:8000/generate-user-token?target_user=username" -H "accept: application/json"

If you receive a “Connection refused” message, this means your back-end is not responding and that a previous step has not worked correctly.
If you receive any other response resembling {“token”:”xxx”}, then DigDash has indeed returned a response and you can proceed to the next steps.

Step 2: Front-end configuration

For our client-side architecture, we’ll create an index.html file in our /var/www/embedded/ directory. The API call is made transparently usingfetch.

  1. Create an index.html file .
    sudo vi index.html
  2. Then add the following HTML/CSS/JavaScript code to it:

    ⚠ Replace the variable `myUser ` and the Flow identifiers (here ` c74b5ca3 ` and ` ee54be60`) with your own details.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Embedded Dashboard</title>
        <script src="/digdash_dashboard/digdash.dashboard.js"></script>
        <style>
            .dashboard-container { display: flex; flex-wrap: wrap; gap: 20px; padding: 20px; }
            .chart-box { border: 1px solid #ccc; width: 45%; height: 400px; background: #f9f9f9; }
        </style>
    </head>
    <body>
        <div class="dashboard-container">
            <div id="chart-1" class="chart-box"></div>
            <div id="chart-2" class="chart-box"></div>
        </div>

        <script>
           // DigDash initialization function
           async function init() {
               const myUser = 'User1';
               const response = await fetch('/generate-user-token?target_user=' + myUser, {
                    method: 'GET'
                });

               if (!response.ok) throw new Error("Error retrieving token");
               
               const data = await response.json();
               const authToken = data.token;
                console.log("Token successfully retrieved:", authToken);

                console.log("Parent: Initializing DigDash...");
                DigDash.init({
                   "url": "/digdash_dashboard", // Using relative path via Nginx
                   "user": myUser,
                   "authToken": authToken
                });
            }

           function renderChildChart(containerId, flowId) {
                console.log(`Child [${containerId}]: Waiting for initialization...`);
               // Function to wait for DigDash initialization
               function waitForInit(callback) {
                   if (DigDash.parameters && DigDash.parameters.size > 0) {
                        callback();
                    } else {
                        setTimeout(() => waitForInit(callback), 100);
                    }
                }

                waitForInit(() => {
                    console.log(`Child [${containerId}]: Drawing flow ${flowId}`);
                    DigDash.drawPortlet(containerId, {
                       "type": "flow",
                       "flowId": flowId
                    });
                });
            }

            init();

            renderChildChart("chart-1", "c74b5ca3");
            renderChildChart("chart-2", "ee54be60");
        </script>
    </body>
    </html>

💡 Once the connection to DigDash has been established, you can use the functions available in DDCtrl.

Step 3: Configurung Nginx

ℹ In this section, we describe the procedure for opening up our API for an Nginx server that has already been installed, following the DigDash installation documentation.

To make this API and website accessible from outside without opening any additional ports on your firewall, you must add two routing rules to your existing Nginx configuration file.

  1. Open your Nginx configuration file (usually /etc/nginx/sites-available/001-digdash.com.conf): 
    sudo vi /etc/nginx/sites-available/001-digdash.com.conf
  2. Locate the server block that listens on port 443 (SSL).
  3. Insert the following two ` location ` directives inside this block, after the other `location` directives:
     # Routing to the FastAPI authentication proxy
       location /generate-user-token {
            proxy_pass http://127.0.0.1:8000;
            include proxy_params;
           
           # Mandatory disabling of Nginx error interception
           # to allow FastAPI to pass its own error messages to the client
           proxy_intercept_errors off;
       }

       # Routing to our index.html
       location /embedded/ {
           alias /var/www/embedded/;
            index index.html;
            try_files $uri $uri/ =404;
       }
  4. Test the configuration syntax and reload Nginx: 
    # Vérification de la configuration Nginx
    sudo nginx -t

    # Si le test est positif, rechargement à chaud de la configuration
    sudo systemctl reload nginx

Step 4: Testing

To finish this tutorial, you can test access to your web page via the following URL:

https://VOTRE_DOMAINE.digdash.com/embedded/index.html

The page displayed should contain two flows (graphs) side by side, for example:

Flux embarqués

ℹ In the browser console, a few logs appear to aid development and debugging. For production use, it is recommended that you remove these elements.

Congratulations!

You have successfully set up your first DigDash charts in embedded mode.
All you need to do now is apply this principle to the charts you wish to embed in your web pages!