Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the Tawk chat widget script to nextjs react app

I'm trying to figure out how to add a chat widget from Tawk to a next.js react app.

In my _app.js, I have added the script import tag and tried to set the widget as follows:

import Script from 'next/script'

      {/* <!--Start of Tawk.to Script--> */}
      <Script id="tawk" strategy="lazyOnload">
        dangerouslySetInnerHTML={{
            __html: `
            
            var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
            (function(){
            var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
            s1.async=true;
            s1.src='https://embed.tawk.to/[]/[]';
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
            })();
           
            `,
        }}
      </Script>

When I try this, I get an error that says:

Unhandled Runtime Error SyntaxError: Unexpected identifier

Call Stack loadScript ../../node_modules/next/dist/client/script.js (148:18) eval ../../node_modules/next/dist/client/script.js (167:62)

I contacted the tawk dev support team, who acknowledged an issue with react, and suggested that a fix had been pushed with a new version 2.0.1 heres the link https://www.npmjs.com/package/@tawk.to/tawk-messenger-react

When I try that both in _app.tsx and _document.tsx, I get more than 10 errors with that package.

Has anyone figured out how to use tawk in a next.js react app?

like image 373
Mel Avatar asked Nov 21 '25 16:11

Mel


1 Answers

I made a working project with a real Tawk.to account: https://codesandbox.io/s/tawk-test-ovmsqy?file=/pages/_app.js

You should change the ids at s1.src line!

import Script from "next/script";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      <Script id="tawk" strategy="lazyOnload">
        {`
            var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
            (function(){
            var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
            s1.async=true;
            s1.src='https://embed.tawk.to/62f4b8c537898912e962654a/1ga5v3hhr';
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
            })();  
        `}
      </Script>
    </>
  );
}

export default MyApp;
like image 167
kepes Avatar answered Nov 24 '25 08:11

kepes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!