How to fix navigator / window / document is undefined in Nuxt

This is the solution to fix:

  • navigator is undefined
  • window is undefined
  • document is not defined

Here is an example on how you should wrap your logic JS code

<script>
import { jsPlumb } from 'jsplumb' // client-side library only, no SSR support

export default {
  mounted() {
    if (process.client) {
      // your JS code here like >> jsPlumb.ready(function () {})
    }
  },
}
</script>

As shown here: https://nuxtjs.org/docs/2.x/internals-glossary/context

PS: mounted + process.client are kinda redundant because mounted only runs on the client.


Also, wrapping your component into <client-only> if you want it to be only client side rendered is also a good idea.

<template>
  <div>
    <p>this will be rendered on both: server + client</p>
    
    <client-only>
      <p>this one will only be rendered on client</p>
    </client-only>
  <div>
</template>

The documentation for this one is here: https://nuxtjs.org/docs/2.x/features/nuxt-components/#the-client-only-component

PS: beware because this client-only tag will only skip the rendering, not the execution, as explained here.


Some packages do not support SSR when you import them, for that you could either:

  • use a condition with a dynamic import (if the library is meant to be used later on)
  • directly like this (if you want to load a component like vue-editor)
export default {
  components: {
    [process.client && 'VueEditor']: () => import('vue2-editor'),
  }
}

Leave a Comment