Zendesk Widget in Next.js app hiding after navigation

106 Views Asked by At

I'm having problems implementing the Zendesk Messaging Widget into my Next.js app. I created the following component to load the script and it works perfectly on the initial loading of the page. The little button appears at the corner and I can click it to open up the widget. However, if I navigate through the app (and Next.js renders pages without a full page refresh) the button and the widget is not visible anymore. Checking the browser inspector I can see that the iframe is not included in the website anymore.

const ZendeskWidget = () => {

    useEffect(() => {
        const script = document.createElement('script');
        script.id = 'ze-snippet'
        script.type = 'text/javascript';
        script.src = 'https://static.zdassets.com/ekr/snippet.js?key='+ZENDESK_KEY;
        script.async = true;
        script.onload = () => {
            handleLoaded();
        };
        document.body.appendChild(script);

        return () => {
            if (script) {
                document.body.removeChild(script);
            }
        };

    }, []);

    const handleLoaded = () => {
        // Sign in the user
        zE("messenger", "loginUser", function (callback) {
            fetch('/api/zendesk').then(function (res) {
                res.json().then(jsonRes => {
                    if (jsonRes.success) {
                        callback(jsonRes.token)
                    }
                })
            });
        });
    };

    return null;
};

I tried implementing this component either in the layout.js or separately on all pages where it should show up. All with the same result. I also tried loading the script via next/script as follows but it had the same behavior.

<Script
     id="ze-snippet"
     type="text/javascript"
     src="https://static.zdassets.com/ekr/snippet.js?key=<KEY>"
     onReady={handleLoaded}
/>

I guess it's basic behavior of Next.js that I have to deal with. Any help is greatly appreciated.

I am using App Router on Next.js 14.1.

0

There are 0 best solutions below