OvidijusParsiunas / deep-chat

Fully customizable AI chatbot component for your website
https://deepchat.dev
MIT License
1.24k stars 163 forks source link

Nuxt - navigator is not defined #195

Open admiral20 opened 1 month ago

admiral20 commented 1 month ago

in nuxt3, i not use vue3 defineAsyncComponent API , the deep-chat error info: navigator is not defined;

after i use defineAsyncComponent API, the dom is not render;

image

OvidijusParsiunas commented 1 month ago

Hi @admiral20.

I have experimented with Deep Chat in Nuxt quite a while back, but haven't had a chance to add it to the framework examples as I would inherently need to also update the example servers directory.

The trick is to render the component on the client side and not in the server itself. The reason for this is because Deep Chat uses a variety of global variables/APIs that are not available during server render time such as window and document, hence it needs to wait for its code to be interpreted in the browser.

In Nuxt, the way you can do this is by checking the process.client flag on the mounted lifecycle hook. Once this flag has passed, you can dynamically import Deep Chat and render it conditionally by using a data state variable such as isLoaded. Here is example code below:

<template>
  <deep-chat
    v-if="isLoaded"
    :demo="true"
    :textInput="{ placeholder: { text: 'Welcome to the demo!' } }"
    :initialMessages="initialMessages"
  />
</template>

<script lang="ts">
export default {
  async mounted() {
    if (process.client) {
      // dynamically import the component and conditionally render it via isLoaded when it has finished importing
      await import('deep-chat');
      this.isLoaded = true;
    }
  },
  data() {
    return {
      initialMessages: [
        { role: 'user', text: 'Hey, how are you today?' },
        { role: 'ai', text: 'I am doing very well!' },
      ],
      isLoaded: false,
    };
  },
};
</script>

You can also find a live example for this here, however the link may change in the future when an official example will be added to the repo/documentation.

Let me know if this helps. Thanks!

OvidijusParsiunas commented 1 day ago

Quick update, I have been quite busy with my work obligations and and have not had much time to create a full code sample for Nuxt, so instead I will simply add the live code example to our documentation and close this issue as soon as possible. Stay tuned for further updates!

IllamosSalaman commented 1 day ago

Hi @OvidijusParsiunas, would it be possible to create a nitro (the default server layer for Nuxt) server template? I would love to use deepchat in my current Nuxt application, but am puzzled and confused in how I can make it work properly. Here a link to the Nitro website: https://nitro.unjs.io/

OvidijusParsiunas commented 1 day ago

@IllamosSalaman I'll try to get some free time to experiment with it and see if I can get it to work.