How To Set Up Customer Facing Analytics With Next.js

Click, Code, Create: Next.js Meets Databrain for Stunning Dashboards!

Getting Started: Setting up the basic project. 

Step 1: Create a Next.js App

First, open your terminal and run the following command to create a new Next.js app:

npx create-next-app@latest

This command prompts you to select options like Name, Typescript, ESLint, etc.

Select only the options you require. The installation process will start once you've made your choices.

Step 2: Navigate to the Project Directory

Once the installation is complete, change into the newly created project directory using the cd command:

cd my-app

Step 3: Start the Development Server

To start the development server and preview your app, run the following command:

npm run dev

Now, you'll see a ready-made template like this. 

Step 4: Clean the template

Open the pages.js file. Delete everything between the main tags to start with a clean slate.

Open the pages.css file and clear the entire code. It will allow you to add your custom styles later.

Open the globals.css file and remove any background color styling to default it to white.

Now, your browser will look clean and ready to create a dashboard. 

Create a Dashboard:

Step 1: Login or Sign up

Create an account, or log in using your existing account on Databrain.

Step 2: Connect the Database:

Before you do anything, connect a database. It ensures your data is ready and accessible to create a dashboard with ease. 

In the menu, click Datasources. 

Click on ‘Add New Datasource’. 

Now, you can choose from the following database to connect from. 

Select your preferred database and follow the instructions to connect the database to your databrain account. 

For example, if you choose MongoDB as a database, the connection page will look similar to the one below. 

Fill in the necessary details and hit authenticate to proceed further. 

Here is a closer look at the instructions:

Step 3: Create a Workspace and Dashboard

Creating a workspace and a dashboard is simple:

In the home:

Click the "Create a Workspace" button, and enter the necessary details to set up a workspace.

In the Workspace:

Click the "Create a Dashboard" button and provide the details to create a dashboard.

Remember, a workspace allows you to create multiple dashboards, while a dashboard is where you can generate different metrics like pie charts, single value charts, bar charts, and more.

Step 4: Create a Metric:

After you create a workspace and a dashboard, open your dashboard and click the “Create Metric” button. It opens the following page. 

To create a metric, follow these steps:

1. Click on "Public."

2. Choose a table.

3. Select attributes.

4. Drag and drop them on the Dimensions and Measures tabs (X and Y axis).

5. Choose the chart type from the available options and save. 

The appearance of the charts will vary based on the data, where you place the data (X and Y axis), and the selected chart type.

Let’s put the above process to the test and see it in action.

Drag the amount to the Measures tab and name to the Dimensions tab. Here, ‘name’ and ‘amount’ are attributes. 

Click on charts and select line chart.

Now the chart looks like this - 

This process creates a line chart showing each customer with the order amount. 

It is just a sample of what databrain is capable of, and it takes less than 5 minutes to create the chart. 

If you have something more complex visualizations in mind, databrain can handle it.

Now, you have created a single metric. Repeat the same process until you get all the metrics to create a complete dashboard. 

Step 5: Customization: 

In databrain, there are various customizations available. In this guide, we will explore three of them. 

Let’s take the line chart example from the above section and see how you can customize it per your requirements. 

Adding chart labels: This can be helpful for viewers who want to see the exact values of the data points.

- Head to "Settings."

- Move to the "Appearance" section.

- Under "Chart Label," choose the label position to display your data labels.

Adding a legend: A legend can help identify multiple lines on the chart.

- Go to "Settings."

- Select "Appearance."

- In the "Chart Legend" section, toggle the switch.

- Choose your preferred legend position.

Changing the chart title and description: The chart title and description can make the chart more informative and easier to understand.

- Navigate to "Settings."

- Access the "Appearance" section.

- Enable the Chart title and description settings.

- Provide a title and description for your chart.

- Choose the preferred position.

After we implement the above changes, the chart looks like this- 

Connect the dashboard to your next.js app. 

Step 1: Install the databrain package. 

Install the databrain package by running the following command. 

npm install @databrainhq/plugin

Step 2: Import the package:

Import the databrain package in the page.js file as follows:

"use client";
import "@databrainhq/plugin/web";

Here, "use client"  enables the next.js project to handle the server-side tasks. 

If you don’t use "use client". It throws errors and prevents you from moving forward in creating a dashboard.  

Step 3: Embed the dashboard:

To see the dashboard you created in Databrain live in your Next.js project, utilize the provided code. 

    
        <dbn-dashboard       
            token="copy your token here"       
            dashboard-id="react-dashboard"       
            disable-fullscreen       
            is-hide-chart-settings       
            is-hide-table-preview       
            enable-download-csv       
            enable-email-csv       
            enable-multi-metric-filters       
            options-icon="kebab-menu-vertical | download"       
        ></dbn-dashboard>
    

In this example, Write the dashboard code directly in the `page.js` file where you've imported the Databrain package. 

If you see the above code, there are two main elements to it - a token and dashboard ID, which you can get as follows. 

Getting the token and dashboard ID:

Click preview, select expiry, and click generate link. 

Copy the token and dashboard ID and paste them into the above code. 

Step 4: Whitelist the IP address. 

Till now, you have set up the Next.js project, got the token and dashboard ID, and installed the databrain package. 

The last thing left to do is to whitelist your domain to make sure the dashboard is live and running. Here's how to do it:

Navigate to the settings and access the "Embed Settings" section. 

Within this section, locate the "Whitelist Domains" option and input your URL into the provided field. 

Subsequently, click the add button to include the specified domain. Be sure to save your changes. 

If you have created a few metrics and saved them to the dashboard, it will look like this - 

For your reference, here’s the basic file structure of this project. 

Conclusion:

In conclusion, the seamless integration of Next.js and Databrain transforms raw data into dynamic, insightful dashboards. Armed with the tools provided by these technologies, you can craft visually stunning representations of your data—turning complexity into clarity.

From setting up your Next.js app to connecting databases and creating custom metrics, you've witnessed the simplicity and power of this dynamic duo. Now, with the knowledge to connect, create, and customize, you can turn the data into a compelling visual narrative.

Embrace the potential, experiment with diverse visualizations, and watch as your Next.js app evolves into a hub of information, making a lasting impact on both developers and end-users alike.

Getting Started: Setting Up Next.js for Dashboard Development

Before diving into the Next.js dashboard project, ensure that you have Node.js and npm installed on your system. If you need help, you can download and install them from the official website.

Now, open your terminal and run the following command to create a new Next.js app:

    
npx create-next-app@latest

  

During the installation, you'll be prompted to make choices based on your project requirements, such as project name and styling preferences. Tailor the selections according to your needs.

Navigate to the newly created project folder using the terminal:

    
cd nextjs_dashboard

  

Start the development server:

    
npm run dev

  

This will launch the server, and your dashboard will be accessible at `localhost:3000`. But you will have a pre-made next js template. 

To start fresh with an empty page:

1. Open the `page.js` file and delete everything between the `main` tags.

2. In the `page.css` file, clear the entire code.

3. Open the `globals.css` file and remove any background color styling to default it to white.

Your project is now stripped of the default template, providing a clean starting point for your dashboard development. Customize and build upon this foundation to create your ideal dashboard.

To organize the project structure according to the dashboard layout, create a "components" folder under the "src" directory. 

Inside this folder, establish three subfolders – "Navbar," "Stats," and "Table." 

For each of these components, create both a JavaScript (JS) file and a Cascading Style Sheets (CSS) file. 

Make sure to link these files together within each component. This approach ensures a clear and modular organization, promoting maintainability in your project.

Create a Navbar:

    
      // components/Navbar.js
      "use client";
      import { useState } from "react";
      import Link from "next/link";
      import "./Navbar.css";

      const Navbar = () => {
        const [isNavbarVisible, setNavbarVisibility] = useState(false);
        const toggleNavbar = () => {
          setNavbarVisibility(!isNavbarVisible);
        };
        const closeNavbar = () => {
          setNavbarVisibility(false);
        };
        const navItems = [
          { id: 1, label: "Overview", route: "/" },
          { id: 2, label: "Task", route: "/about" },
          { id: 3, label: "Documents", route: "/services" },
          { id: 4, label: "Team", route: "/contact" },
          { id: 5, label: "Invoice", route: "/contact" },
          { id: 6, label: "Settings", route: "/contact" },
        ];

        return (
          <div>
            {/* Hamburger Menu Icon */}
            <div className="hamburger" onClick={toggleNavbar}>
              <i className={isNavbarVisible ? "close-icon" : "menu-icon"}></i>
            </div>
            {/* Navbar */}
            <div className={`navbar ${isNavbarVisible ? "active" : ""}`}>
              {/* Overlay for mobile */}
              <div
                className="mobile-overlay"
                onClick={closeNavbar}
                style={{ display: isNavbarVisible ? "block" : "none" }}
              ></div>
              {/* Logo/Name */}
              <div className="logo">
                <p className="logo-text">
                  <span className="learning">Project</span>
                  <span className="hub">Hub</span>
                </p>
              </div>
              {/* Navigation Items */}
              <div className="nav-items">
                {navItems.map((item) => (
                  <div className="nav-item" key={item.id}>
                    <Link href={item.route} className="nav-link">
                      {item.label}
                    </Link>
                  </div>
                ))}
              </div>
            </div>
          </div>
        );
      };
    
  


export default Navbar;

    
      /* Hamburger Icon Styles */
      .hamburger {
        display: none;
        cursor: pointer;
        font-size: 24px;
        padding: 10px;
        position: absolute;
        top: 2px;
        left: -8px;
        z-index: 2; /* Ensure it's above the navbar */
      }

      /* Navbar Styles */
      .navbar {
        background-color: black;
        background-color: white; /* Note: This line seems redundant */
        display: flex;
        flex-direction: column;
        align-items: center; /* Center items horizontally */
        width: 200px;
        height: 100vh;
        padding: 20px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); /* Add box shadow */
        position: relative;
        top: 0;
        left: 0;
        transition: left 0.3s ease-in-out; /* Smooth transition for reveal */
      }

      .navbar.active {
        left: 0; /* Show navbar when active */
      }

      /* Remove default anchor color and add gap between icon and text */
      .nav-link {
        text-decoration: none;
        color: inherit; /* Remove default anchor color */
        display: flex;
        align-items: center; /* Center items vertically */
        gap: 10px; /* Gap between icon and text */
        padding: 10px; /* Padding for hover */
        border-radius: 5px; /* Add border-radius for round edges */
      }

      /* Styling on hover */
      .nav-link:hover {
        background-color: #00a5ff; /* Sky blue background color on hover */
        color: #fff; /* White text color on hover */
      }

      .nav-item {
        padding: 10px 0;
        text-align: center; /* Align items horizontally in the center */
      }

      .logo {
        text-align: center; /* Center the logo text horizontally */
        margin-bottom: 20px; /* Add margin below the logo */
      }

      .logo-text {
        font-family: "Pacifico", cursive; /* Apply Pacifico font for "Learning" */
        font-size: 28px; /* Adjust the font size */
      }

      .learning {
        font-family: "Roboto"; /* Apply Pacifico font for "Learning" */
        font-size: 28px; /* Adjust the font size */
        color: #333; /* Adjust the color for "Learning" */
        font-weight: bold;
      }

      .hub {
        font-family: "Roboto", sans-serif; /* Apply Roboto font for "Hub" */
        font-size: 26px; /* Adjust the font size */
        color: #00a5ff; /* Sky blue color for "Hub" */
        font-weight: 700; /* Bold for "Hub" */
        padding-left: 5px;
      }

      /* Navbar Icon Styles */
      .close-icon::before {
        content: "\2715"; /* Unicode character for multiplication symbol (✕) */
      }

      .menu-icon::before {
        content: "\2261"; /* Unicode character for hamburger icon (≡) */
      }

      /* Media query for small screens (e.g., mobile and tablet) */
      @media screen and (max-width: 768px) {
        /* Show hamburger menu icon */
        .hamburger {
          display: block;
          font-size: 16px;
        }

        /* Hide navbar by default */
        .navbar {
          position: absolute;
          left: -200px; /* Adjust left position for the hamburger menu width */
          z-index: 3px; /* Note: It should be an integer value, not '3px' */
        }

        /* Additional styling for small screens */
        .logo-text {
          margin-top: 30px;
        }
      }
    
  

Navbar.js is a React component that manages a responsive navigation bar. It includes a hamburger icon, which toggles the visibility of the navigation menu 

The menu contains links to various sections like "Overview," "Task," "Documents," "Team," "Invoice," and "Settings." The component uses the state to track whether the menu is visible or hidden. 

The styles are defined in a corresponding CSS file (Navbar.css). The hamburger icon changes between a close icon and a menu icon based on the menu's visibility. The component provides a clean and straightforward user interface for navigating different sections of a web application.

Create a Stats Component:

    
      {/* Stats.js */}
      import "./Stats.css";

      const Stats = () => {
        return (
          <div className="stats-container">
            <h2>Project Expanse</h2>
            <div className="stats-sections">
              <div className="stats-section">
                <div className="details">
                  <h3>237 </h3>
                  <span>Hrs</span>
                </div>
                <p>Total Hours</p>
              </div>
              <div className="stats-section">
                <div className="details">
                  <h3>$158000</h3>
                  <span>USD</span>
                </div>
                <p>Cost To Company</p>
              </div>
              <div className="stats-section">
                <div className="details">
                  <h3>200000</h3>
                  <span>USD</span>
                </div>
                <p>Project Budget</p>
              </div>
              <div className="stats-section">
                <div className="details">
                  <h4>79%</h4>
                  <span className="used"> Used</span>
                </div>
                <p>Budget Usage</p>
              </div>
            </div>
          </div>
        );
      };
    
  


export default Stats;

CSS

    
      /* Stats Component Styles */
      .stats-container {
        padding: 20px;
        margin: 10px;
        background-color: #fff; /* White background */
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); /* Smoother box-shadow with a slightly larger spread */
        border-radius: 10px; /* Add border-radius for smoother edges */
      }

      .stats-sections {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
      }

      .stats-section {
        flex: 1;
        padding: 10px;
        margin-right: 10px;
      }

      .details {
        display: flex;
        gap: 5px;
        align-items: center;
        margin-bottom: 10px;
      }

      .details span {
        font-size: 12px;
      }

      .stats-section p {
        font-size: 14px;
        color: gray;
      }

      .used {
        color: red;
      }

      /* Responsive Styles */
      @media screen and (max-width: 768px) {
        .stats-sections {
          flex-direction: column;
          align-items: left;
        }

        .stats-section {
          margin-right: 0;
          margin-bottom: 20px; /* Increase the gap between sections */
          margin-left: 0; /* Ensure all sections start at the same point */
        }
      }
    
  


Stats.js is a React component representing project statistics. It features key metrics like total hours, cost to the company, project budget, and budget usage percentage. 

The component has a clean layout with a white background, rounded corners, and a subtle box-shadow for a polished look. The responsive design adjusts the layout for smaller screens, optimizing readability. 

CSS styles enhance visual appeal with consistent spacing, font sizes, and color coding for better user understanding. The code follows best practices, promoting maintainability and a positive user experience.

Create a Table Component:

    
      {/* Table.js */}
      import React from "react";
      import "./Table.css";

      const Table = () => {
        const tableData = [
          { id: 1, fullName: "John Doe", designation: "Developer", hoursWorked: 40, ctc: 25000 },
          { id: 2, fullName: "Jane Smith", designation: "Designer", hoursWorked: 35, ctc: 18000 },
          { id: 3, fullName: "Bob Johnson", designation: "Manager", hoursWorked: 45, ctc: 35000 },
          { id: 4, fullName: "Alice Williams", designation: "Engineer", hoursWorked: 38, ctc: 28000 },
          { id: 5, fullName: "Charlie Brown", designation: "Analyst", hoursWorked: 42, ctc: 32000 },
          { id: 6, fullName: "Eva Davis", designation: "Administrator", hoursWorked: 37, ctc: 21000 },
        ];

        return (
          <div className="table-container">
            <h2>Team</h2>
            <table>
              <thead>
                <tr>
                  <th>Full Name</th>
                  <th>Designation</th>
                  <th>Hours Worked</th>
                  <th>Cost To Company</th>
                </tr>
              </thead>
              <tbody>
                {tableData.map((entry) => (
                  <tr key={entry.id}>
                    <td>{entry.fullName}</td>
                    <td>{entry.designation}</td>
                    <td>{entry.hoursWorked}</td>
                    <td>${entry.ctc.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );
      };
    
  


export default Table;

CSS

    
      /* Table Component Styles */
      .table-container {
        padding: 20px;
        margin: 10px;
        background-color: #fff; /* White background */
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); /* Smoother box-shadow with a slightly larger spread */
        border-radius: 10px; /* Add border-radius for smoother edges */
        overflow: hidden; /* Ensure that the border-radius doesn't create overflow */
      }

      table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
      }

      th, td {
        padding: 12px;
        text-align: left;
        border: none; /* Remove all borders */
      }

      th {
        background-color: #f2f2f2;
      }

      td {
        background-color: #fff;
        border-bottom: 1px solid #ddd; /* Add a bottom border after each row */
      }

      tfoot td {
        font-weight: bold;
      }

      /* Hover effect for better interaction */
      tbody tr:hover {
        background-color: #f5f5f5;
      }

      /* Remove alternating background colors */
      tbody tr:nth-child(even) {
        background-color: transparent;
      }

      /* Remove vertical lines */
      th, td {
        border-right: none;
        padding: 15px; /* Adjust the padding to add more space between columns */
        text-align: left;
      }

      @media screen and (max-width: 768px) {
        .table-container {
          overflow-x: auto; /* Add horizontal scroll for small screens */
        }
      }
    
  

Table.js is a React component presenting team details in a tabular format. It features a clean design with a white background, rounded corners, and a subtle box-shadow for a polished appearance. 

The table includes columns for Full Name, Designation, Hours Worked, and Cost To Company. Realistic data is dynamically populated for six team members. 

The table employs responsive design practices, ensuring optimal viewing on various screen sizes. The CSS styles enhance visual appeal with consistent spacing, font sizes, and a hover effect for improved interaction. The code adheres to best practices, promoting maintainability and a positive user experience.

Put Together All The Components

In the Home.js file, bring together the previously created components – Navbar, Stats, and Table – to form a cohesive dashboard layout. 

Utilize the main container and flexbox properties to orchestrate the positioning of these components. Apply responsive design principles for optimal viewing across different devices. 

Employ CSS styling to enhance the visual appeal, ensuring a clean and user-friendly interface. This approach guarantees a seamless integration of components, contributing to an organized and visually pleasing dashboard.

When you put together all the components, it looks like this

    
      {/* page.js */}
      import Navbar from "./components/Navbar/Navbar";
      import "./page.css";
      import Stats from "./components/Stats/Stats";
      import Table from "./components/Table/Table";
      // import Font Awesome CSS

      export default function Home() {
        return (
          <main>
            <div className="left">
              <Navbar />
            </div>
            <div className="right">
              <Stats />
              <Table />
            </div>
          </main>
        );
      }
    
  


/* page.css */

    
      /* Body Styles */
      body {
        margin: 0;
        padding: 0;
        background-color: #f4f4f4; /* Set a background color for the page */
        font-family: "Arial", sans-serif; /* Optional: Define a default font family */
      }

      main {
        display: flex;
        justify-content: space-between;
        height: 100vh; /* Utilize full viewport height */
      }

      .right {
        width: 100%;
        margin: 2%;
      }
    
  

Page.js coordinates a responsive layout featuring a Navbar, Stats, and Table components. 

The body has a subdued background color, enhancing visual comfort. The main container utilizes a flexbox for optimal space distribution, spanning the entire viewport height. 

The right section, containing Stats and Table, occupies 100% width with a subtle margin. CSS rules in page.css ensure a clean and visually appealing design. The code adheres to best practices, ensuring maintainability and a positive user experience.

Here’s the overview of the project structure to give you an idea. 

Hope you enjoy this tutorial. See you in the next one.

Make customer facing analytics your competitive advantage