'How to implement Twak.to widget in a Next JS website?
I have tried what is written on their @tawk.to/tawk-messenger-react plugin docs?
I have made a component like /components/Chat.js
import TawkMessengerReact from "@tawk.to/tawk-messenger-react";
export default function Chat() {
return (
<div className="chat">
<TawkMessengerReact
propertyId={process.env.NEXT_PUBLIC_TWAKTO_PROPERTY_ID}
widgetId={process.env.NEXT_PUBLIC_TWAKTO_WIDGET_ID}
/>
</div>
);
}
But after importing the component on Layout.js
or in _app.js
it's giving an error like
E:\PROJECT\FOLDER\node_modules\@tawk.to\tawk-messenger-react\src\index.js:4
import { forwardRef, useEffect, useImperativeHandle } from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at [email protected]/tawk-messenger-react (E:\Projects\motocorp\.next\server\pages\_app.js:240:18)
at __webpack_require__ (E:\PROJECT\FOLDER\.next\server\webpack-runtime.js:33:42)
What should I do to get it functioning properly?
Solution 1:[1]
Okay, so i have encountered a similar issue, this happens because tawk.to is not meant to be executed on the server. Cannot say the solution is the most elegant, but as a workaround i did a dynamic import of the TawkMessengerReact
component. And only render it when the app is loaded in the browser. Again, i am sure there might be some more beautiful way to do it, but hey, it is a working quick-and-dirty solution.
const TawkMessengerReact = dynamic(() =>
import('node_modules/@tawk.to/tawk-messenger-react'),
);
const App = ({ Component, pageProps }) => {
const initialRenderRef = useRef(false);
useEffect(() => {
initialRenderRef.current = true;
}, []);
return (
<div>
{initialRenderRef.current && (
<TawkMessengerReact
propertyId='asdfasdasdadwswdadw'
widgetId='asdwer'
/>)}
<Component {...pageProps} />
</div>
}
Solution 2:[2]
To use the chat widget of Tawk.to I used the Script component with the lazyOnload strategy. You can read more in the docs.
import Script from 'next/script';
// inside the return statement of your page
return (
<>
<Script
strategy="lazyOnload"
src="https://embed.tawk.to/PROPERTY_ID"
/>
</>
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bguiz |
Solution 2 | Rafael |