31

I am trying to use Choices.js within a Vue component. The component compiles successfully, but then an error is triggered:

[vue-router] Failed to resolve async component default: ReferenceError: document is not defined

In the browser I see:

ReferenceError document is not defined

I think this has something to do with the SSR in Nuxt.js? I only need Choices.js to run on the client, because it's a client only aspect I guess.

nuxt.config.js

build: {
  vendor: ['choices.js']
}

AppCountrySelect.vue

<script>
import Choices from 'choices.js'

export default {
  name: 'CountrySelect',
  created () {
    console.log(this.$refs, Choices)
    const choices = new Choices(this.$refs.select)
    console.log(choices)
  }
}
</script>

In classic Vue, this would work fine, so I'm very much still getting to grips with how I can get Nuxt.js to work this way.

Any ideas at all where I'm going wrong?

Thanks.

11 Answers 11

47

It's a common error when you start a Nuxt project ;-)

The Choices.js lib is available only for client-side! So Nuxt tried to renderer from server-side, but from Node.js window.document doesn't exist, then you have an error.
nb: window.document is only available from the browser renderer.

Since Nuxt 1.0.0 RC7, you can use <no-ssr> element to allow your component only for client-side.

<template>
  <div>
    <no-ssr placeholder="loading...">
      <your-component>
    </no-ssr>
  </div>
</template>

take a look at the official example here: https://github.com/nuxt/nuxt.js/blob/dev/examples/no-ssr/pages/index.vue


Update:

Since Nuxt >= 2.9.0, you have to use the <client-only> element instead of <no-ssr>:

<template>
  <div>
    <client-only placeholder="loading...">
      <your-component>
    </client-only>
  </div>
</template>

To know more, see nuxt docs: https://nuxtjs.org/docs/2.x/features/nuxt-components#the-client-only-component

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for this! Any idea how I could then output the element itself with SSR? As in, some JS needs to act on the client-side for a select list, but I'd still like to render the actual select list on the server.
How should the <your-component /> file look like? I have YourComponent.vue: <template><div></div></template> <script> import Plotly from 'plotly.js/dist/plotly' export default {} </script> and it still ends with document is not defined
nuxtjs.org/guide/plugins#client-side-only plugins: [ { src: '~/plugins/vue-notifications', mode: 'client' } ] I would suggest this for those that are still struggling like I was to find a solution.
@JeffBluemel Your solution saved my day. I had to add this in my nuxt.config.js { src: '~/plugins/vue-izitoast', mode: 'client' }
@JeffBluemel, Yours is the only solution worked for me after banging my head for half a day for a solution. I literally tried everything I could find on the internet.
|
31

The accepted answer (while correct) was too short for me to understand it and use it correctly, so I wrote a more detailed version. I was looking for a way to use plotly.js + nuxt.js, but it should be the same as the OP's problem of Choice.js + nuxt.js.

MyComponent.vue

<template>
  <div>
    <client-only>
      <my-chart></my-chart>
    </client-only>
  </div>
</template>
<script>
export default {
  components: {
    // this different (webpack) import did the trick together with <no-ssr>:
    'my-chart': () => import('@/components/MyChart.vue')
  }
}
</script>

MyChart.vue

<template>
  <div>
  </div>
</template>
<script>
import Plotly from 'plotly.js/dist/plotly'
export default {
  mounted () {
    // exists only on client:
    console.log(Plotly)
  },
  components: {
    Plotly
  }
}
</script>

Update: There is <client-only> tag instead of <<no-ssr> in Nuxt v>2.9.0, see @Kaz's comment.

3 Comments

This worked in my case when I was using evodiaaut.github.io/vue-marquee-text-component. Mostly no-ssr tag is enough but with this library, I had to import the way as mentioned above. @michal. Can you explain the reason behind this kind of import
@BaldeepSinghKwatra unfortunately, I came to this solution by trial/error, as far as I remember
If you are using a Nuxt version of > v2.9.0, use <client-only> instead of <no-ssr>. As <no-ssr> is deprecated from Nuxt v2.9.0
15

You need to add it as a plugin and then disable SSR for it.

As the document and window are not defined on the server-side.

Your nuxt.config.js should look like below

plugins: [
  { src: '~/plugins/choices.js' } // both sides
  { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side
  { src: '~/plugins/server-only.js', mode: 'server' } // only on server side
],

2 Comments

now the syntax looks like this { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side { src: '~/plugins/server-only.js', mode: 'server' } // only on server side
Thanks for the pointer @ArifIkhsanudin I just update the Answer.
7

I found that now the no-ssr is replace by , i am using echart and have the same problem but now it´s working!

    <client-only>
        <chart-component></chart-component>
    </client-only>

1 Comment

<no-ssr> is deprecated from Nuxt version v2.9.0.
7

I had this error with lightgallery.js adding mode: 'client' seems helped

nuxt.config.js

 plugins: [
    { src: '~/plugins/lightgallery.js',  mode: 'client' }
  ],

plugins/lightgallery.js

import Vue from 'vue'
import lightGallery from 'lightgallery.js/dist/js/lightgallery.min.js'
import 'lightgallery.js/dist/css/lightgallery.min.css'

Vue.use(lightGallery)

ImageGallery.vue

<template>
  <section class="image-gallery-container">
    <div class="image-gallery-row">
      <div
        ref="lightgallery"
        class="image-gallery"
      >
        <a
          v-for="image in group.images"
          :key="image.mediaItemUrl"
          :href="image.mediaItemUrl"
          class="image-gallery__link"
        >
          <img
            :src="image.sourceUrl"
            :alt="image.altText"
            class="image-gallery__image"
          >
        </a>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'ImageGallery',
  props: {
    group: {
      type: Object,
      required: true
    }
  },
  mounted() {
    let vm = this;

    if (this.group && vm.$refs.lightgallery !== 'undefined') {
      window.lightGallery(this.$refs.lightgallery, {
        cssEasing: 'cubic-bezier(0.680, -0.550, 0.265, 1.550)'
      });
    }
  }
}
</script>

Comments

6

This thread is a bit old, but I will leave my solution here so maybe someone finds it useful.

I had similar issue with vue-star-rating and few other plugins recently.


Below steps can be followed and adjusted depending on the plugin name, import / usage settings:

  1. Go to your plugins folder and create new js file, in this case vue-star-rating.js, then edit it to setup the plugin:

import Vue from 'vue'
import VueStarRating from 'vue-star-rating'

Vue.component('vue-star-rating', VueStarRating); //<--- the name you used to register the plugin will be the same to use when in the component (vue-star-rating)
  1. Go to your nuxt.config.js file and add plugin:

  plugins: [{
      src: '~/plugins/vue-star-rating', // <--- file name
      mode: 'client'
    },
    //you can simply keep adding plugins like this:
    {
      src: '~/plugins/vue-slider-component',
      mode: 'client'
    }]
  1. Now you are ready to use the plugin anywhere in the application. However, to do that you will need to wrap it in the container <client-only>. Example:

<client-only placeholder="loading...">
   <vue-star-rating />
</client-only>

Notes:

You do not need to import anything locally to the component, simply using it like above should fix the problem.

Please make sure you are naming the plugin the same way in both places, step 1 and step 3. In this case it would be vue-star-rating.

Comments

5
<script>
import Choices from 'choices.js'

export default {
  name: 'CountrySelect',
  created () {
    if(process.client) {
      console.log(this.$refs, Choices)
      const choices = new Choices(this.$refs.select)
      console.log(choices)
    }
  }
}
</script>

I guess this should help, nuxt will touch insides of computed after it renders on server and window will be defined

Comments

0

if you still want to do it, document object can be taken this way:

const d = typeof document === 'undefined' ? null : document

1 Comment

I'm not sure this will solve the problem.
0

For completeness, it's worth mentioning that instead of the object syntax in Yusuf Adeyemo answer (which I prefer as it separates out the file from how it is used), you can also set plugins to operate in client or server side only by naming the files like so:

export default {
  plugins: [
    '~/plugins/foo.client.js', // only in client side
    '~/plugins/bar.server.js', // only in server side
    '~/plugins/baz.js' // both client & server
  ]
}

src: https://nuxtjs.org/docs/directory-structure/plugins/#client-or-server-side-only

Comments

0

On top of all the answers here, you can also face some other packages that are not compatible with SSR out of the box (like in your case) and that will require some hacks to work properly. Here is my answer in details.

The TLDR is that you'll sometimes need to:

  • use process.client
  • use the <client-only> tag (be careful, it will not render but still execute the code inside)
  • use a dynamic import if needed later on, like const Ace = await import('ace-builds/src-noconflict/ace')
  • load a component conditionally components: { [process.client && 'VueEditor']: () => import('vue2-editor') }

With all of this, you're pretty much covered for every possible case.

Comments

0

I was trying to access document in created hook so when I moved the logic from created hook to mounted hook, my problem was solved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.