How to Conditionally Run Code Only on the Server or Only on the Client in a Nuxt App

Discover how Nuxt improves performance and SEO with its server-side and client-side rendering capabilities. Learn best practices for managing code execution to avoid hydration mismatches and ensure efficient rendering in your applications.

Mostafa Said
Nuxt 3

The Mastering Nuxt FullStack Unleashed Course is here!

Get notified when we release new tutorials, lessons, and other expert Nuxt content.

Click here to view course

Nuxt runs on both the server and the client. The former means full fledged HTML sent to the browser with content already filled in. This is great for performance and SEO. I also runs in the browser by “hyrdrating” the server side rendered page. Then on every subsequent page visit it runs only on the client, behaving as a SPA.

Sometimes it’s useful to keep some logic ONLY on the server or ONLY on the client.

Using import.meta

You can use ESM import.meta.client variable to check if the code is running in the browser (or on the “client”). It will be

import.meta.client // true if in browser, false if on server

You can use import.meta.server variable to check if the code is running on the server.

import.meta.server // true if on server, false if in browser

Then you can create conditionals to only run code in your environment of choice.

if(import.meta.server){
  // do something only on the server
}

if(import.meta.client{
  // do something only on the client 
}

These values exist in page components, other Vue components, in middleware, and in composable.

Be careful though, to not cause a hydration mismatch by rendering something differently at hydration time then what was rendered on the server. If a difference in rendering is required, consider having some state (some reactive ref) set to false initially in script setup and then onMounted you can set it to true and use a v-if to control the rendering.

<script setup lang="ts">
const show = ref(false);

onMounted(()=> show.value = true)
<script>

<template>
<div v-if="show">The thing I only want to render on the client</div>
</template>

Conclusion

When working in components, middleware, and composables you have plenty of control over where your code runs: client or server.

Mostafa Said
Mostafa is a full-stack developer, a full-time Instructor at Vue School, and a Vue.js Jedi.

Follow MasteringNuxt on