Home > Web Front-end > JS Tutorial > body text

Why are `navigator`, `window`, and `document` undefined in my Nuxt application?

Susan Sarandon
Release: 2024-11-10 22:46:02
Original
980 people have browsed it

Why are `navigator`, `window`, and `document` undefined in my Nuxt application?

How to Address Undefined navigator / window / document in Nuxt Applications

Introduction

In Nuxt applications, accessing global browser variables like navigator, window, and document can sometimes result in undefined errors. This is because the Nuxt framework utilizes server-side rendering (SSR), where code is initially executed on the server before being rendered on the client.

Solution

The key to resolving this issue is to limit browser-dependent code to the client-side. To achieve this, there are several strategies:

1. Conditional Code Wrapping

Wrap your code within an if (process.client) condition to execute it only on the client-side. This ensures that the code is only run after the SSR phase.

<script>
  export default {
    mounted() {
      if (process.client) {
        // Your JS code here
      }
    },
  }
</script>
Copy after login

2. Component

Create a component to wrap elements that should be rendered only on the client. This prevents them from being executed during SSR.

<template>
  <div>
    <client-only>
      <p>This will only be rendered on client</p>
    </client-only>
  </div>
</template>
Copy after login

3. Dynamic Imports

If a library doesn't support SSR, you can use dynamic imports. This delays library loading until it's needed on the client-side, ensuring that it isn't executed during SSR.

export default {
  components: {
    [process.client &&& 'VueEditor']: () => import('vue2-editor'),
  },
}
Copy after login

Note:

  • Wrapping your component in skips rendering, not execution.
  • Some packages may require extra configuration to work properly with SSR.

The above is the detailed content of Why are `navigator`, `window`, and `document` undefined in my Nuxt application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template