Nuxt Tip: Render Component Only on Client-Side
By default, Nuxt uses universal (client-side + server-side) rendering to render your application.
It's a typical use case to access browser APIs like localStorage
in your Nuxt components:
1<script setup>
2localStorage.setItem('test', 'A test string')
3
4const localStorageItem = ref('')
5
6onMounted(() => {
7 localStorageItem.value = localStorage.getItem('test')
8})
9</script>
10
11<template>
12 <div style="display: flex; flex-direction: column; gap: 10px">
13 <span>Hello from client</span>
14 <span>Local storage item: {{ localStorageItem }}</span>
15 </div>
16</template>
If you try to run your app, Nuxt will throw an error:
Error
localStorage is not defined
This error occurs because the code is first executed on the Node.js server which does not support localStorage
.
You can solve this problem by using Nuxt 3's ClientOnly component:
1<template>
2 <div>
3 <ClientOnly fallback-tag="span" fallback="Loading on server...">
4 <MyComponent />
5 </ClientOnly>
6 </div>
7</template>
The <ClientOnly>
component renders its slot only in client-side. To import a component only on the client, register the component in a client-side only plugin.
Try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Validate Events and Prop Types
You can validate prop types and events in Vue. If a requirement is not met, Vue will warn you in the browser's JavaScript console.
Vue Tip: Optimize Performance Using shallowRef
shallowRef() is typically used for performance optimizations of large data structures, or integration with external state management systems.