Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Nuxt Tip: Render Component Only on Client-Side

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Apr 5, 2023
1 min read
Nuxt Tip: Render Component Only on Client-Side Image

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:

<script setup>
localStorage.setItem('test', 'A test string')

const localStorageItem = ref('')

onMounted(() => {
  localStorageItem.value = localStorage.getItem('test')

  <div style="display: flex; flex-direction: column; gap: 10px">
    <span>Hello from client</span>
    <span>Local storage item: {{ localStorageItem }}</span>

If you try to run your app, Nuxt will throw an 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:

    <ClientOnly fallback-tag="span" fallback="Loading on server...">
      <MyComponent />

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 newsletter:

New Vue & Nuxt tips delivered to your inbox:
I will never share any of your personal data.