Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Nuxt Tip: Differentiate Client and Server Components

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jul 5, 2023
1 min read
|
145 views
Nuxt
Nuxt Tip: Differentiate Client and Server Components Image

Client Components

By adding the .client suffix to a component you tell Nuxt to render that component only client-side.

bash
1
| components/
2
--| 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:

App.vue
1
<template>
2
<div>
3
<ClientOnly>
4
<MyComponent />
5
</ClientOnly>
6
</div>
7
</template>

Server Components

Warning

Server components are currently experimental. You can enable them in your Nuxt config:

nuxt.config.ts
1
export default defineNuxtConfig({
2
experimental: {
3
componentIslands: true,
4
},
5
})

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.

bash
1
| components/
2
--| 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.

bash
1
| components/
2
--| MyComponent.client.vue
3
--| 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 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.