Search code examples
sveltesveltekitcsr

How to enable csr on a SvelteKit component?


I'm aware that I can enable/disable csr on SvelteKit routes, but can I do it on a single component?

My current code looks like this:

layout.ts:

export const prerender = true;
export const ssr = true;

page.svelte:

<script lang="ts">
  import MyComponent from '$lib/components/MyComponent.svelte'
<script>

something to be rendered on the server

<MyComponent /> <!-- To be rendered on the client -->

I've tried this on MyComponent.svelte but it didn't work

<script lang="ts">
  export const csr = true;
</script>
....

Solution

  • There is no component-level setting.

    There is a SvelteKit specific browser flag you could use:

    import { browser } from '$app/environment';
    
    {#if browser}
        <Component />
    {/if}
    

    You could also wrap the component in #await, though this is a bit of a hack:

    {#await Promise.resolve() then _}
        <Component />
    {/await}