Why is my `client-only` component in nuxt complaining that `window is not defined`? Why is my `client-only` component in nuxt complaining that `window is not defined`? vue.js vue.js

Why is my `client-only` component in nuxt complaining that `window is not defined`?


I found a way that works though I'm not sure how. In the parent component, you move the import statement inside component declarations.

<template>  <client-only>    <map/>  </client-only></template><script>export default {  name: 'parent-component',  components: {    Map: () => if(process.client){return import('../components/Map.vue')},  },}</script>


    <template>      <client-only>        <map/>      </client-only>    </template>    <script>      export default {        name: 'parent-component',        components: {          Map: () =>            if (process.client) {              return import ('../components/Map.vue')            },        },      }    </script>

The solutions above did not work for me.

Why? This took me a while to find out so I hope it helps someone else.

The "problem" is that Nuxt automatically includes Components from the "components" folder so you don't have to include them manually. This means that even if you load it dynamically only on process.client it will still load it server side due to this automatism.

I have found the following two solutions:

  1. Rename the "components" folder to something else to stop the automatic import and then use the solution above (process.client).

  2. (and better option IMO) there is yet another feature to lazy load the automatically loaded components. To do this prefix the component name with "lazy-". This, in combination with will prevent the component from being rendered server-side.

In the end your setup should look like thisFiles:

./components/map.vue./pages/index.html

index.html:

    <template>      <client-only>        <lazy-map/>      </client-only>    </template>    <script>    export default {    }    </script>


The <client-only> component doesn’t do what you think it does. Yes, it skips rendering your component on the server side, but it still gets executed!

https://deltener.com/blog/common-problems-with-the-nuxt-client-only-component/