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>
2.
Create a
<template> <div> <client-only> <p>This will only be rendered on client</p> </client-only> </div> </template>
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'), }, }
Note:
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!