KambleSonam / clevertap-next-demo

CleverTap Web SDK Sample Next.js App
https://clevertap-next-demo.vercel.app
2 stars 0 forks source link

ReferenceError: HTMLElement is not defined #2

Open EjDadivas opened 10 months ago

EjDadivas commented 10 months ago

This happens when I don't use .tsx

Server Error
ReferenceError: HTMLElement is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/node_modules/.pnpm/clevertap-web-sdk@1.6.9/node_modules/clevertap-web-sdk/clevertap.js (3474:36)
<unknown>
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/node_modules/.pnpm/clevertap-web-sdk@1.6.9/node_modules/clevertap-web-sdk/clevertap.js (2:83)
Object.<anonymous>
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/node_modules/.pnpm/clevertap-web-sdk@1.6.9/node_modules/clevertap-web-sdk/clevertap.js (5:2)
Module._compile
node:internal/modules/cjs/loader (1256:14)
Module._extensions..js
node:internal/modules/cjs/loader (1310:10)
Module.load
node:internal/modules/cjs/loader (1119:32)
Module._load
node:internal/modules/cjs/loader (960:12)
Module.require
node:internal/modules/cjs/loader (1143:19)
mod.require
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/require-hook.js (65:28)
require
node:internal/modules/cjs/helpers (121:18)
clevertap-web-sdk/clevertap
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/.next/server/pages/index.js (87:18)
__webpack_require__
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/.next/server/webpack-runtime.js (33:42)
eval
webpack-internal:///./pages/index.js (9:85)
./pages/index.js
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/.next/server/pages/index.js (55:1)
__webpack_require__
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/.next/server/webpack-runtime.js (33:42)

in my package.json:

"dependencies": {
    "clevertap": "^1.3.0",
    "clevertap-web-sdk": "^1.6.9",
    "next": "14.0.4",
"react": "^18",
    "react-dom": "^18"

index.js

import { useState, useEffect } from "react";
import CleverTap from "clevertap-web-sdk/clevertap";

const profileApiUrl = "/profile";
export default function Home() {
  const [clevertapModule, setClevertapModule] = useState(null);

  useEffect(() => {
    clevertapInit();
  }, []);

  const clevertapInit = async () => {
    let clevertap = clevertapModule;
    if (!clevertap) {
      clevertap = await initializeClevertap();
    }

    if (clevertap) {
      clevertap.event.push("Amee"); // Popup Campaign
      clevertap.event.push("webpopup test"); // Banner Campaign
      clevertap.event.push("InternalTest2"); // Inbox Campaign
    }
  };

  const profileData = {
    d: [
      {
        identity: "345543",
        type: "profile",
        profileData: {
          Name: "John Doe",
          Email: "john03aug@abc.com",
        },
      },
    ],
  };

    fetch("/clevertap/upload", {
      method: "POST",
      headers: {
        "X-CleverTap-Account-Id": "******",
        "X-CleverTap-Passcode": "*******",
        "Content-Type": "application/json",
        // Add any other required headers here
      },
      body: JSON.stringify(profileData),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        // Handle the API response data here
        console.log(data);
      })
      .catch((error) => {
        // Handle any errors that occurred during the API call
        console.error("Error:", error);
      });

  return (
    <div>
      {/* Navigation Bar */}
      <nav style={{ backgroundColor: "#333", padding: "10px", color: "#fff" }}>
        <ul
          style={{
            listStyle: "none",
            display: "flex",
            justifyContent: "space-between",
            maxWidth: "300px",
          }}
        >
          <li>Home</li>
          <li>About</li>
          <li>Contact</li>
          <li id="inbox">Inbox</li>
        </ul>
      </nav>

      {/* Hero Section */}
      <section
        style={{
          backgroundColor: "#f2f2f2",
          padding: "140px 0",
          textAlign: "center",
        }}
      >
        <div>
          <h1 style={{ fontSize: "36px" }}>Welcome to Our Website</h1>
          <p style={{ fontSize: "20px", color: "#666" }}>
            We provide amazing services for you.
          </p>
          <button
            style={{
              padding: "10px 20px",
              fontSize: "16px",
              background: "#007bff",
              color: "#fff",
              border: "none",
              borderRadius: "5px",
              cursor: "pointer",
            }}
          >
            Get Started
          </button>
        </div>
      </section>

      {/* Clevertap Banner / carousel */}
      <div id="heroDiv"></div>

      {/* Call-to-action Section */}
      <section
        style={{
          backgroundColor: "#007bff",
          padding: "60px 0",
          textAlign: "center",
          color: "#fff",
        }}
      >
        <h2 style={{ fontSize: "30px" }}>Sign Up Now</h2>
        <p style={{ fontSize: "18px" }}>
          Join us and experience the best services.
        </p>
        <button
          style={{
            padding: "10px 20px",
            fontSize: "16px",
            background: "#fff",
            color: "#007bff",
            border: "none",
            borderRadius: "5px",
            cursor: "pointer",
          }}
        >
          Sign Up
        </button>
      </section>
    </div>
  );
}

async function initializeClevertap() {
  const clevertapModule = await import("clevertap-web-sdk");

  clevertapModule.default.init("*******");
  clevertapModule.default.privacy.push({ optOut: false });
  clevertapModule.default.privacy.push({ useIP: false });
  clevertapModule.default.setLogLevel(3);

  return clevertapModule.default;
}
EjDadivas commented 10 months ago

Also, if there's a way to initialize it on _app.js so I don't have to initialize it on every page

KambleSonam commented 10 months ago

Hello @EjDadivas . Agreed that Next js doesn't work with jsx in the same way as it works with tsx. The index.jsx file will be updated as below

import { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';

const CleverTapComponent = dynamic(() => import('clevertap-web-sdk/clevertap'), {
  ssr: false, // This ensures CleverTap is not imported during server-side rendering
});

export default function Home() {
  const [clevertapModule, setClevertapModule] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch data only on the client side
        const response = await fetch('/clevertap/upload', {
          method: 'POST',
          headers: {
            'X-CleverTap-Account-Id': 'W9R-486-4W5Z',
            'X-CleverTap-Passcode': '96921fadbf3445a7b416039d0e9d046d',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(profileData)
        });

        if (!response.ok) {
          throw new Error('Network response was not ok');
        }

        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('Error:', error);
      }
    };

    // Check if the code is running on the client side
    if (typeof window !== 'undefined') {
      clevertapInit();
      fetchData();
    }
  }, []);

  const clevertapInit = async () => {
    // Check if CleverTap module is already initialized
    let clevertap = clevertapModule;
    if (!clevertap) {
      clevertap = await import('clevertap-web-sdk/clevertap');
      clevertap.default.init("ZWW-WWW-WWRZ");
      clevertap.default.privacy.push({ optOut: false });
      clevertap.default.privacy.push({ useIP: false });
      clevertap.default.setLogLevel(3);
      setClevertapModule(clevertap.default);
    }

    if (clevertap) {
      clevertap.event.push('CM 3333'); // Popup Campaign
      clevertap.event.push('webpopup test'); // Banner Campaign
      clevertap.event.push('InternalTest2'); // Inbox Campaign
    }
  };

  const profileData = {
    "d": [
      {
        "identity": "345543",
        "type": "profile",
        "profileData": {
            "Name": "John Doe",
            "Email": "john03aug@abc.com"
        }
      }
    ]
  };

  return (
    <div>
      {/* Navigation Bar */}
      <nav style={{ backgroundColor: '#333', padding: '10px', color: '#fff' }}>
        <ul style={{ listStyle: 'none', display: 'flex', justifyContent: 'space-between', maxWidth: '300px' }}>
          <li>Home</li>
          <li>About</li>
          <li>Contact</li>
          <li id='inbox'>Inbox</li>
        </ul>
      </nav>

      {/* Hero Section */}
      <section style={{ backgroundColor: '#f2f2f2', padding: '140px 0', textAlign: 'center' }}>
        <div>
          <h1 style={{ fontSize: '36px' }}>Welcome to Our Website</h1>
          <p style={{ fontSize: '20px', color: '#666' }}>We provide amazing services for you.</p>
          <button style={{ padding: '10px 20px', fontSize: '16px', background: '#007bff', color: '#fff', border: 'none', borderRadius: '5px', cursor: 'pointer' }}>
            Get Started
          </button>
        </div>
      </section>

      {/* Clevertap Banner / carousel */}
      <div id='heroDiv'></div>

      {/* Call-to-action Section */}
      <section style={{ backgroundColor: '#007bff', padding: '60px 0', textAlign: 'center', color: '#fff' }}>
        <h2 style={{ fontSize: '30px' }}>Sign Up Now</h2>
        <p style={{ fontSize: '18px' }}>Join us and experience the best services.</p>
        <button style={{ padding: '10px 20px', fontSize: '16px', background: '#fff', color: '#007bff', border: 'none', borderRadius: '5px', cursor: 'pointer' }}>
          Sign Up
        </button>
      </section>
    </div>
  );
}

For your query to initialize it on _app.js, give me some time I will work on it and revert. Thank You

Rohitdhende commented 10 months ago

@KambleSonam I am getting same issue. It would be great if you could find any solution for this.

Thanks in advance!

KambleSonam commented 10 months ago

@Rohitdhende Kindly refer the repo https://github.com/PraveenCTzen/nextJs-demo/tree/main If this doesn't solve your issue, do let us know.

Rohitdhende commented 10 months ago

@KambleSonam thanks! It worked, but I believe this issue should be addressed within the package. Currently, we had to add extra lines of code for it.

Rohitdhende commented 10 months ago

@KambleSonam Hey, I am facing some issue. The event.push method isn't working properly, sometimes it works and sometimes it not. Don't know the exact reason, my observation is the scripts are not getting loaded after refresh.

And I have one more question that to use any event's method, we need to necessarily logon user?

PraveenCTzen commented 10 months ago

1- Currently it working properly on our end, kindly raise a ticket to clevertap for debugging your issue.

2- No you don't need to do onuserlogin for events to work.