Nuxt Tip: Differentiate Client and Server Components
Michael Hoffmann
@mokkapps
Client Components
By adding the .client
suffix to a component you tell Nuxt to render that component only client-side.
| components/
--| MyComponent.client.vue
.client
components are rendered only after being mounted. If you need to access the rendered template in onMounted()
you need to call await nextTick()
inside the onMounted()
callback.
Alternatively, you can wrap your component with Nuxt's <ClientOnly>
component:
<template>
<div>
<ClientOnly>
<MyComponent />
</ClientOnly>
</div>
</template>
Server Components
export default defineNuxtConfig({
experimental: {
componentIslands: true,
},
})
By adding the .server
suffix to a component you tell Nuxt to always render that component on the server. Such a component adds zero JavaScript to your client bundle and does not parse markdown in your client which makes your app faster. If you update its props, a network is triggered to update the HTML.
| components/
--| MyComponent.server.vue
LearnVue produced a good video about server components:
Combine Server and Client Components
You can either use .client
and .server
components on their own or pair them.
Combining them enables advanced use cases if your components need to have separate implementations on the client and server side.
| components/
--| MyComponent.client.vue
--| MyComponent.server.vue
Be aware that the client component needs to be able to hydrate the HTML which was generated by the server component to avoid hydration mismatches.
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :