Step-by-step guide on integrating the Tawk chat widget script into a Next.js React application

I am currently working on integrating a chat widget from Tawk into a next.js react app.

In my _app.js file, I have added the script import tag and attempted to set up the widget like this:

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>

Unfortunately, when attempting this setup, I encountered an error message stating:

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 reached out to the Tawk developer support team, who acknowledged a compatibility issue with React. They mentioned that a fix has been implemented in version 2.0.1 which can be found here: https://www.npmjs.com/package/@tawk.to/tawk-messenger-react

After trying to implement the suggested solution in both _app.tsx and _document.tsx files, I encountered more than 10 errors related to that package.

I am wondering if anyone has successfully integrated Tawk into a next.js react app?

Answer №1

I successfully created a functional project using an actual Tawk.to account: Check it out here.

Remember to update the IDs in the 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;

Answer №2

The issue here is that the dangerouslySetInnerHTML code is currently placed outside the tag in this format:

<Script id="tawk" strategy="lazyOnload">
        dangerouslySetInnerHTML={{

It should actually be structured like this:

<Script id="tawk" strategy="lazyOnload" dangerouslySetInnerHTML={"your data"} />
        

Nevertheless, it is recommended to place the code within the tag itself. Your _app.js file should resemble the following:

import "../styles/globals.css";
import Script from "next/script";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      {/* <!--Start of Tawk.to Script--> */}
      <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/[]/[]';
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
            })();
        `}
      </Script>
    </>
  );
}

export default MyApp;

Answer №3

To successfully incorporate a twik.js file into your project, simply create it in the public directory and load it using next/script without encountering any problems.

Answer №4

For a more streamlined method, try implementing @tawk.to/tawk-messenger-react from NPM

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Edit script: Iterate through the different div elements at regular intervals AND pick a specific div by pressing a button

Check out this interesting discussion about displaying and hiding divs at specific time intervals using jQuery on the page here. The script mentioned is designed to loop through DIVs, showing one after the other while hiding the rest. It's titled "Lo ...

What is the best way to implement a promise function in this scenario using JavaScript?

I am currently working on an app using AngularJS and the MediaFire JavaScript SDK to perform various tasks. One specific task I am struggling with is creating a folder during an upload process, which returns a 'folderkey'. I would like to use .t ...

Comparing E-commerce: Laravel's Full MVC Approach vs Next.JS for Dynamic Views

Seeking guidance. Who here is knowledgeable about Next.js (or its rival Nuxt.JS)? In the near future, I have a challenging task of developing a fully customized E-commerce website. This platform needs to be efficient and particularly well optimized for ...

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...

Angular directive ng-clickIs the directive in angular known as

I am struggling to understand why my ng-click function in my directive is not triggering the fooControls clickTest. Why isn't clickTest logging to the console? Is there a more efficient way to accomplish this? Custom Directive app.directive('fo ...

Having trouble with AngularJS ngRepeat not functioning properly?

Currently, I am utilizing AngularJs to showcase Google maps with markers. Upon clicking a marker, I am aiming to display the details of the clicked marker. Here is the content of my Controller.js: function createMarker(latitude,longitude,name,address,lo ...

What is the best way to show only one div at a time when selecting from navbar buttons?

To only display the appropriate div when clicking a button on the left navbar and hide all others, you can use this code: For example: If "Profile" is clicked in the left navbar, the My Profile Form div will be displayed (and all others will remain hidde ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

How can I declare CSS variables in Next.js components' module.css just like in global CSS?

When writing CSS in our global file, we often define variables and styles like this: :root{ --orange:#e67e22; --black:#333; --light-color:#777; --border:.1rem solid rgba(0,0,0,.2); --box-shadow:0 .5rem 1rem rgba(0,0,0,.1); } *{ mar ...

Modifying iframe elements dynamically across domains

I am faced with the challenge of embedding an iframe form from a web application that I use onto my website. This custom inquiry form is integrated into my diary within the web app, and now I want it to be displayed on my main website while maintaining a c ...

JavaScript Age Calculator - Counting Days

Hey there! I've got an interesting problem. I currently have three text boxes on my webpage, and what I want to achieve is having a fourth text box generated when the user clicks a button. The content of this new text box should be filled with the dat ...

Confirm that only the days of the present month are eligible for selection

I have been given the responsibility of validating a date field that is populated when an invoice is created. The date field consists of a text box and three button objects allowing users to select a date from a calendar, input today's date, or remove ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Issue with model not displaying after material added in OBLLoader + MTLLoader

After loading a material using MTLLoader and applying it to my model loaded with OBJLoader, the model itself mysteriously disappears. MTLLoader.setPath( 'models/' ); var url = "model.mtl"; MTLLoader.load( url, function( materials ) { materi ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

Extend the center of the image horizontally

Is there a way to horizontally stretch only the middle section of an image? Let's say I have this specific image: https://i.sstatic.net/pty5A.jpg (source: lawrenceinspections.com) I need the rounded corners to remain unchanged, so simply stretchi ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

What does the use of square brackets signify in Vuex mutations?

I'm curious about the use of mutation values within brackets in Vuex. What does the code "" represent? export const SOME_MUTATION = 'SOME_MUTATION' Is this just a constant name for a function? If so, why is it enclosed in brackets "[]"? ...

Node.js failing to log chat messages

The goal is to log the chat message entered by the user in the console (terminal). Currently, there seems to be an issue with logging and I'm struggling to debug it. Keep in mind that I am a novice when it comes to NodeJS and only have basic knowledge ...

Looking for the Mustache template library?

Can you provide some examples of how mustache can be used effectively? I recently came across it, but I'm struggling to grasp how it differs from the traditional approach of creating template files within frameworks like cakePHP or django, or simply ...