Astrojs "window is not defined" error, even though i'm using client:only directive

44 Views Asked by At

We're trying to use Astro to have a website where each top component can be developed by a different team using whatever framework they want. We start with a very simple example using Svelte as the component framework, with a purely client-side component (notice it calls window):

// ------index.astro
---
import MyAppTest from '../MyAppTest.svelte'
---
<MyAppTest client:only="svelte"/>

// ------MyAppTest.svelte
<script lang="ts">
  const myhost = window.location.host
  console.log(myhost)
</script>

<div>{myhost}</div>

This works perfectly! But if we try to improve the design by moving the function to an outside imported .ts module, it fails:

// ------MyAppTest.svelte
<script lang="ts">
  import { myhost } from "./myhostlocation"
  console.log(myhost)
</script>

<div>{myhost}</div>

// ------myhostlocation.ts
export const myhost = window.location.host

by throwing a "ReferenceError: window is not defined. Browser APIs are not available on the server."

I have already set the client:only directive as seen above, and the svelte component works correctly when the window call is inside it. But fails when it is in an imported file. I don't know how to resolve this issue, can anyone help?

I have already tried setting client:only="ts" and client:only. It doesn't help. Neither does using .js instead of .ts.

0

There are 0 best solutions below