Blog

Using Luzmo for Data Visualization in Next.js: A Set-up Guide

Data Engineering
Aug 28, 2024
Using Luzmo for Data Visualization in Next.js: 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 Next.js App Router 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. 

Luzmo profile settings to generate API tokens

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.

Generating API key and token in Luzmo

That completes the Luzmo setup part of this guide. In the next step, you’ll create a Next.js application using the App Router

Getting started with Next.js App Router

To create a new Next.js application, head over to the docs, and follow the install instructions.

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

  • What is your project named? › luzmo-getting-started-next-js
  • Would you like to use TypeScript? › Yes
  • Would you like to use ESLint? › Yes 
  • Would you like to use Tailwind CSS? › Yes
  • Would you like to use `src/` directory? › Yes
  • Would you like to use App Router? (recommended) › Yes
  • Would you like to customize the default import alias (@/*)? › No

Environment variables

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

// .env.local

LUZMO_API_KEY=
LUZMO_API_TOKEN=

# Ensure you don’t include a trailing slash with any URLs. 
NEXT_PUBLIC_LUZMO_APP_SERVER=
NEXT_PUBLIC_LUZMO_API_HOST=

Add theLUZMO_API_KEY and LUZMO_API_TOKENgenerated 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 forNEXT_PUBLIC_LUZMO_APP_SERVER and NEXT_PUBLIC_LUZMO_API_HOST.

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

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 Next.js project, locate src/app/page.tsx and update it with the following code. This page runs on the server only, environment variables without the NEXT_PUBLIC prefix won’t ever be available to the client.

// src/app/page.tsx

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

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

export default async function Home() {
  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;

  return <pre>{JSON.stringify({ id, token }, null, 2)}</pre>;
}

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 Next.js component. 

Client-side Next.js component

As you probably know, Next.js is now server-first, meaning, unless you explicitly tell Next.js that your code is to run on the client, it will assume it will only run on the server. To tell Next.js that a component is to be used on the client, you can use React’s use client directive at the top of the file.

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

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

'use client';

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 application, make the following changes to your page.tsx.

// src/app/page.tsx

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

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

export default async function Home() {
  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',
        },
      ],
    },
  });

  if (!response) return null;

  const { id, token } = response;

+  return <LuzmoClientComponent authKey={id} authToken={token} />;
-  return <pre>{JSON.stringify({ id, token }, null, 2)}</pre>;
}

Start building data products with Luzmo and Next.js

That just about wraps things up! You now have all the pieces in place to build with Luzmo and Next.js. You can create low-code dashboards and embed them into your application, 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