Web Component
Embed Semaphor dashboard in your HTML project
This example is based on the assumption that you are working with vanilla JavaScript in an HTML environment. It involves a script that fetches the token and passes it to the auth-token
attribute once the token is retrieved.
Let's first initialize a vanilla JavaScript project using Vite's guide.
1. Install Semaphor Package
After running the above commands, open the project in your editor and install the semaphor
package.
2. Obtain the Auth Token
First, create a dashboard.js
file at the root of your project and paste the following code. This code retrieves the AuthToken
, which provides access to the dashboard.
Note: auth-token
is used as an attribute of a web component. Web components adhere to the kebab-case
naming convention, which involves writing words in lowercase and separating them with hyphens -
. This convention is used for attribute names and CSS class names, as camelCase
is not supported.
Security Note
Do not expose DASHBOARD_SECRET
in client-side code in production. Use a
backend service to fetch the token securely.
3. Render the Dashboard
And finally, let's add the following three lines to the index.html
file as below:
- Styles
<link rel="stylesheet" href="./node_modules/semaphor/dist/style.css" />
initalizes the styles. This is IMPORTANT for your dashboard styles to load properly. - Web Component
<semaphor-dashboard id="d_cf007a8b-19bc-46ad-8787-2915445b7b86" />
is the web component that renders the dashbaord, - Token
<script type="module" src="./dashboard.js"></script>
references the code fetches theAuthToken
.
Now, you can run the app by typing the following command in your terminal window.
Passing styles
Create a custom class in your style.css.
And then you can reference this class in dashboard.js
, like so.
Since the style
attribute is a complex type, you need to pass the JSON string value to the style attribite.
Key Considerations
- Security: Keep the
DASHBOARD_SECRET
secure and do not expose it in client-side code in production. The example above is for demonstration purposes. When deploying in production, obtain the authentication token from a secure, server-side environment. - Error Handling: The code includes basic error handling for the fetch call and element selection. Depending on your application's complexity and requirements, you might want to implement more sophisticated error handling.
- DOM Ready: The script waits for the
DOMContentLoaded
event, ensuring the DOM is fully loaded before attempting to manipulate elements or fetch data. This is crucial for accessing elements that are defined later in the HTML document.