#How to check if code is running on client

3 messages · Page 1 of 1 (latest)

modern halo
#

How can one check if the code is running on the client vs during astro render from within UI framework components? (Vue.js in my case)

gilded perchBOT
#

Hi @modern halo. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can use the import.meta.env.SSR property to check if the code is running on the server or the client. This property is available in all ESM modules and Astro adds import.meta.env through Vite.

Here's an example of how you can use it:

export default function () {  
  return import.meta.env.SSR ? <div class="spinner"></div> : <FancyComponent />;
}

In this example, if the code is running on the server (during Astro's render), it will return a div with the class "spinner". If it's running on the client, it will return the FancyComponent.

However, please note that this is a general method and not specific to Vue.js. For Vue.js or any other UI framework components, you can use the client:* directives provided by Astro to control how your components are hydrated on the page. For instance, client:load will load and hydrate the component JavaScript immediately on page load.

<SomeVueComponent client:load />

In this case, the SomeVueComponent will be hydrated and become interactive on the client as soon as the page loads.

For more information, you can refer to the Astro API Reference (https://docs.astro.build/en/reference/api-reference/#importmeta) and Astro Directives Reference (https://docs.astro.build/en/reference/directives-reference/#client-directives).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: