Blog

Using Luzmo for Data Visualization in Astro: A Set-up Guide

Data Engineering
Aug 28, 2024
Using Luzmo for Data Visualization in Astro: A Set-up Guide

Building data visualizations from scratch can be both time-consuming and cumbersome, requiring significant effort to design and implement. Developing these capabilities in-house often involves complex coding, ongoing maintenance, and a deep understanding of data management and visualization best practices.

Luzmo addresses these challenges by offering an analytics platform that integrates with your application to provide powerful data visualization and insights. It supports real-time data syncing, customizable dashboards with a drag-and-drop interface, and AI-enhanced chart creation

With its API-first design and advanced query engine, Luzmo offers a flexible, scalable solution for turning data into actionable insights, making it an essential tool for modern digital environments.

Whether you are using Next.js, Astro, or other app frameworks, you can create and embed low-code Luzmo dashboards, or build custom charts through code using our new Flex SDK. But whichever approach you take, you’ll need to generate an access token server-side first.

For any data product you’re building on top of Luzmo, this server-side token is the stepping stone to securely access and manage data. It ensures that only authorized requests are made and protects sensitive information. In this guide, we’ll explain how you can use Astro with Luzmo’s Node.js SDK to generate a token for use with our client-side components.

For your reference, we’ve prepared a GitHub repository which you can find on the following link.

How to create Luzmo API tokens

If you don’t already have a Luzmo account, sign up now before moving to the next step. 

With your account created, click on your initial (in the top right of the screen) and select Profile, then API Tokens. To create a new API token, click the Create API token button.

Profile settings in Luzmo to create an API token

Make a note of the API key and API token generated, as you’ll need them in the following step. You might also like to give your API token a description so you know which application it's for. 

Creating an API key and token in Luzmo

That completes the Luzmo setup part of this guide. In the next step, you’ll create an Astro site using the React UI integration to enable client-side hydration, and the Netlify SSR adapter to enable server-side rendering.

Getting started with Astro

To create a new Astro site, head over to the docs, and follow the install instructions.

For reference, these are the options we selected from the available CLI prompts.

  • create-astro@4.8.1 Ok to proceed? › y
  • Where should we create your new project? › luzmo-getting-started-astro
  • How would you like to start your new project? › Empty
  • Do you plan to write TypeScript? › Yes
  • How strict should TypeScript be? › Strict (recommended)
  • Install dependencies? › Yes
  • Initialize a new git repository? › Yes

Environment variables

Create a new file at the root of your new project named .env and add the following variable names. By default, Astro won’t expose environment variables to client-side code. For variables that are required by client-side code, you can prefix them with PUBLIC. You can read more about environment variables in the Astro documentation.

// .env

LUZMO_API_KEY=
LUZMO_API_TOKEN=

# Ensure you don't include a trailing slash with any URLs. 
PUBLIC_LUZMO_APP_SERVER=
PUBLIC_LUZMO_API_HOST=

Add the LUZMO_API_KEY and LUZMO_API_TOKEN generated in the first step.

Depending on which region your account has been created in, you’ll either use the US or EU addresses listed below for PUBLIC_LUZMO_APP_SERVER and PUBLIC_LUZMO_API_HOST.

Ensure you don’t include a trailing slash with any URLs. 

How to install Astro’s React UI integration

As you probably know, Astro is a static site builder and ships zero JavaScript to the client by default. To use Luzmo’s client-side React components, you’ll need to enable client-side hydration using React and install the integration. To add the React UI integration to your site, run the following in your terminal. 

For reference, these are the options we selected from the available CLI prompts. 

Astro will run the following command | Continue: › Yes

Astro will make the following changes to your config file | Continue: › Yes

Astro will make the following changes to your tsconfig.json: | Continue: › Yes

npx astro add react

How to install Astro’s Netlify SSR integration

In the next step, we’ll be making a server-side request using Luzmo’s Node.js SDK to generate access tokens for use with Luzmo’s client-side components. To enable server-side capabilities with Astro, you’ll need to install an integration. In this guide, we’ll be using the Netlify integration. To add the Netlify integration to your site, run the following in your terminal.

For reference, these are the options we selected from the available CLI prompts. 

Astro will run the following command Continue: › Yes

Astro will make the following changes to your config file Continue: › Yes

npx astro add netlify

You can read more about Astro’s Netlify integration in the Astro documentation

How to install Luzmo’s Node.js SDK

Luzmo’s Node.js SDK is used server-side to generate access tokens for use with client-side components. 

⚠️ This is for security reasons, you do not want to expose your API key & token client-side, as that would mean that users would be able to change filters or grant access to your securables.

To get started, run the following in your terminal to install the dependency.

npm install @luzmo/nodejs-sdk

Create authorization

In your Astro project, locate src/pages/index.astro and update it with the following code. This page runs on the server only, environment variables without the PUBLIC prefix won’t ever be available to the client.

In your Astro project, locate src/pages/index.astro and update it with the following code. This page runs on the server only, environment variables without the PUBLIC prefix won’t ever be available to the client.

// src/pages/index.astro

---
import Luzmo from '@luzmo/nodejs-sdk';

const client = new Luzmo({
  api_key: import.meta.env.LUZMO_API_KEY!,
  api_token: import.meta.env.LUZMO_API_TOKEN!,
  host: import.meta.env.PUBLIC_LUZMO_API_HOST!,
});

const response = await client.create('authorization', {
  type: 'embed',
  username: 'user id',
  name: 'first name last name',
  email: 'name@email.com',
  access: {
    datasets: [
      {
        id: '<dataset_id>',
        rights: 'use',
      },
    ],
  },
});

const { id, token } = response;
---

<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <link rel='icon' type='image/svg+xml' href='/favicon.svg' />
    <meta name='viewport' content='width=device-width' />
    <meta name='generator' content={Astro.generator} />
    <title>Astro</title>
  </head>
  <body>
    <pre>{JSON.stringify({ id, token }, null, 2)}</pre>
  </body>
</html>

The above code sets up the Luzmo Node.js SDK client and is provided with the environment variables you set earlier. 

With a client defined, you can now make a “create” request for authorization credentials that are safe to use with client-side code.

There are a number of options available which can be defined within the access object, depending on which kind of application you’re building. For demonstration purposes, we’re using datasets. You can read more about creating datasets in our documentation.

You could, however, include dashboards or collections in the request if you’re planning on using Dashboard embedding or Collections in your application.

E.g.

     ...
     access: {
      datasets: [
        {
          id: '<dataset_id>',
          rights: 'use',
        },
      ],
      dashboards: [
        {
          id: '<dashboard_id>',
          rights: 'use',
        },
      ],
      collections: [
        {
          id: '<collection_id>',
          rights: 'use',
        },
      ],
    },

For development purposes, you can use hardcoded values for username, name and email. For production environments, these would be replaced with authenticated user information. You can read more about creating authenticated users in the following blog post: Embedding A Luzmo Dashboard In Next.js Apps Using Clerk on Vercel.

Within the response will be an id and a token. We’ve destructured these values from the response and returned them using an HTML pre element.

In the next step, we’ll show you how to use those values with a client-side React component. 

Client-side React component

As mentioned above, Astro is a static site builder and ships zero JavaScript to the client by default. To tell Astro that a component is to be used on the client, you can use one of the client directives.

Create a new directory under src named components. Then create a new file named luzmo-client-component.tsx and add the following code.

// src/components/luzmo-client-component.tsx

interface Props {
  authKey: string;
  authToken: string;
}

export default function LuzmoClientComponent({ authKey, authToken }: Props) {
  console.log({ authKey, authToken });

  return <section>Luzmo client component</section>;
}

This component accepts two props, the authKey and authToken. These are the id and token values from the server-side authorization request.

These can now be used with one of Luzmo’s client components which would be used in place of the HTML section element shown in the above code snippet.

  1. LuzmoDashboardComponent: for adding a dashboard created through Luzmo’s low-code editor
  2. LuzmoVizItemComponent: for adding visualization widgets, generated on the fly via code

To display your Luzmo client component in your site, make the following changes to your index.astro.

Notice the use of the client:load directive attribute on the LuzmoClientComponent.

// src/pages/index.astro

---
import Luzmo from '@luzmo/nodejs-sdk';
+ import LuzmoClientComponent from '../components/luzmo-client-component';

const client = new Luzmo({
  api_key: import.meta.env.LUZMO_API_KEY!,
  api_token: import.meta.env.LUZMO_API_TOKEN!,
  host: import.meta.env.PUBLIC_LUZMO_API_HOST!,
});

const response = await client.create('authorization', {
  type: 'embed',
  username: 'user id',
  name: 'first name last name',
  email: 'name@email.com',
  access: {
    datasets: [
      {
        id: '<dataset_id>',
        rights: 'use',
      },
    ],
  },
});

const { id, token } = response;
---

<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <link rel='icon' type='image/svg+xml' href='/favicon.svg' />
    <meta name='viewport' content='width=device-width' />
    <meta name='generator' content={Astro.generator} />
    <title>Astro</title>
  </head>
  <body>
+   <LuzmoClientComponent authKey={id} authToken={token} client:load />
-   <pre>{JSON.stringify({ id, token }, null, 2)}</pre>
  </body>
</html>

Start building data products with Luzmo and Astro

That just about wraps things up! You now have all the pieces in place to build with Luzmo and Astro. You can create low-code dashboards and embed them into your site, personalize charts and dashboards based on user logins, and render charts dynamically using Luzmo Flex. 

These features allow you to efficiently create and customize data visualizations, improving your application’s functionality and end-user experience.

Paul Scanlon

Paul Scanlon

Independent Developer Advocate

Paul is a Senior Software Engineer, Independent Developer Advocate and Technical Writer. He has ~20 years of experience and regularly writes for major tech publications such as The New Stack, Smashing Magazine and CSS Tricks. More from Paul can be found on his website, paulie.dev.

Build your first embedded dashboard in less than 15 min

Experience the power of Luzmo. Talk to our product experts for a guided demo  or get your hands dirty with a free 10-day trial.

Dashboard