Zendesk Chat in a React application | Community
Skip to main content

Zendesk Chat in a React application

  • March 13, 2024
  • 3 replies
  • 0 views

Nhlalala

I'm having issues with the Chatbot where it attempts to make a call to https://xxxx.zendesk.com/sc/sdk/v2/apps/xxxxxx/appusers/xxxxxxxx before I even attempt to Authenticate the user, this makes the request return 401. Is there a way I can prevent this call from being made before I authenticate??? 

Below is my react code.

const loadChatbotScript = () => {
constscriptId='ze-snippet'
if (document.getElementById(scriptId)) {
return
}

constzendeskScript=document.createElement('script')
zendeskScript.src=process.env.ZENDESK
zendeskScript.async=true
zendeskScript.id=scriptId
document.body.appendChild(zendeskScript)

zendeskScript.onload= () => {
window.zE('messenger:on', 'open', function () {
refetch()
})
}
}

useEffect(() => {
if (isAuthed) {
loadChatbotScript()
}
}, [isAuthed])

useEffect(() => {
if (token) {
window.zE('messenger', 'loginUser', callback=> {
callback(token)
})
}
}, [token])

3 replies

Greg29
  • March 13, 2024

Hi Nhlalala! Could you share the logic for setting the `isAuthed` and `token` vars? If the underlying code for that isn't checking if `isAuthed` is true, then that effect will run if any value is present there.


Nhlalala
  • Author
  • March 13, 2024

Subject: Clarification on Authentication Flow and Chatbot Script Loading

Hi Greg,

I wanted to provide some clarity regarding our chatbot's authentication and initialization process. The variable isAuthed is determined at the application level, and it ensures that the chatbot script is not loaded until a user is authenticated. This precaution prevents unauthorized access and interactions with the chatbot.

Upon opening the chatbot, triggered by window.zE('messenger:on', 'open', function () { refetch() }), we initiate a refetch() call. This function is crucial as it's designed to retrieve the authentication token necessary for the chatbot's operation.

However, we've encountered a timing issue where the system prematurely makes an appusers call before it executes the login call. Consequently, this results in a 401 error since the appusers call occurs without the necessary authentication token. Importantly, even after a user is authenticated on our side, the system does not reattempt the appusers call, leading to a persistent authorization error.

This sequence is at the core of our concern. We're looking for a way to ensure that the chatbot's login call, which authenticates the user within the chatbot service, is successfully completed before any other requests are made. Your insights or suggestions on how to rectify this issue would be greatly appreciated.


Greg29
  • March 18, 2024
Hi Nhlalala! The reason that I was asking about the isAuthed var specifically is that even if it returned false in your application, the effect would fire and would lead to the issues that you're seeing.