CleverTap / clevertap-web-sdk

CleverTap Web SDK
https://clevertap.com/
MIT License
12 stars 18 forks source link

HTMLElement is not defined when integrating Clevertap in NextJS application #183

Open EjDadivas opened 6 months ago

EjDadivas commented 6 months ago

Error I receive:

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
file:///C:/Users/ASUS/Desktop/Self-Study/NEXT_REACT/clevertap-next-integration/.next/server/pages/index.js (76: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 (7:75)
./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 _app.js

import "@/styles/globals.css";
import clevertap from "clevertap-web-sdk"
 clevertap.init("********");

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

Inside my index.js I created a simple app:


import clevertap from "clevertap-web-sdk";

export default function Home() {
  return (
    <div className="App">
      <h3>CleverTap Web SDK using React</h3>
      <div>
        <button onClick={handleEventPushClick}>Push Event</button>
      </div>
    </div>
  );
}

function handleEventPushClick() {
  clevertap.event.push("Product Viewed", {
    "Product name": "Casio Chronograph Watch",
    Category: "Mens Accessories",
    Price: 59.99,
    Date: new Date(),
  }); // Replace Payload as per your event schema and design
clevertap.onUserLogin.push({
 "Site": {
   "Name": "Jack Montana",            // String
   "Identity": 61026032,              // String or number
   "Email": "jack@gmail.com",         // Email address of the user
   "Phone": "+14155551234",           // Phone (with the country code)
   "Gender": "M",                     // Can be either M or F
   "DOB": new Date(),                 // Date of Birth. Date object
// optional fields. controls whether the user will be sent email, push etc.
   "MSG-email": false,                // Disable email notifications
   "MSG-push": true,                  // Enable push notifications
   "MSG-sms": true,                   // Enable sms notifications
   "MSG-whatsapp": true,              // Enable WhatsApp notifications
 }
})
}

I tried this: https://github.com/KambleSonam/clevertap-next-demo but it still doesn't work

Rohitdhende commented 5 months ago

Hi,

Is this issue solved for you? I am getting the same issue.

kkyusuftk commented 5 months ago

Just FYI: This issue comes since you are trying to initialize the sdk on the server. Note in next js all the components are by default server side rendered. Initialize the SDK on the client side, it should work correctly. In your case try to add use client to make the page not server side rendered. I faced a similar issue while integrating in nuxt.js and I was able to resolve it by disabling SSR from the config.

jayantbh commented 3 months ago

For those that can't exactly use use client, you can try dynamic imports.

typeof window !== 'undefined' &&
  import('clevertap-web-sdk').then((ct) =>
    ct.default.init(process.env.NEXT_PUBLIC_CLEVERTAP)
  );

typeof window !== 'undefined' &&
  import('clevertap-web-sdk').then((ct) =>
    ct.default.event.push(ev, flattenObj(props))
  );

Not a fan of how simply importing the package in server side code might break things. But for now, this works for me.

vagnermaltauro commented 2 months ago

works for me!

in _app.js


const [clevertapModule, setClevertapModule] = useState(null);
...
...
useEffect(() => {
    clevertapInit()
  }, []);
...
...
  const clevertapInit = async () => {
    let clevertap = clevertapModule
    if (!clevertap) {
      clevertap = await initializeClevertap()
    }
  };
...
...
 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;
  }
  ``
zeyios commented 3 days ago

works for me

import type CleverTap from 'clevertap-web-sdk'
type CleverTapType = typeof CleverTap

let clevertap: CleverTapType

if (typeof window !== 'undefined') {
  const cleverTapKey =  'xxxx'
  if (cleverTapKey) {
    clevertap = require('clevertap-web-sdk')
    clevertap.init(cleverTapKey)
  }
}