Svelte TypeError [ERR_INVALID_URL]: Invalid URL when fetching endpoint in reactive statement

Viewed 646

Using SvelteKit, I have the following component:

/index.svelte

<script lang="ts">
    $: {
        fetchEndpoint();
    }

    async function fetchEndpoint() {
        try {
            const res = await fetch('/api/demo');
        } catch(e) {
            console.log(`Failed load endpoint. ${e}`);
        }
    }
</script>

/api/demo.ts

export async function get() {
    return {
        status: 200,
        body: 'Hi',
    };
}

On the first load of the page I get the following error message:

Failed load endpoint. TypeError [ERR_INVALID_URL]: Invalid URL

Why exactly is that and how can it be fixed?

1 Answers

Yeah, the problem is that your <script lang="ts"> runs both on the server and on the front end. When it runs on the server, it won't know what /api/demo is referring to. One way to fix that by running it only in the browser, like so:

import { browser } from '$app/env';

async function fetchEndpoint() {
  if(browser) {
    try {
      const res = await fetch('/api/demo');
    } catch(e) {
      console.log(`Failed load endpoint. ${e}`);
    }
  }
}
Related