message: 'TypeError: fetch failed' - SvelteKit + Supabase

184 views Asked by At

I am creating a Sveltekit project and decided to use Supabase as my database.

src/lib/supabaseClient.js

import { createClient } from '@supabase/supabase-js'
import {SUPABASE_URL, SUPABASE_KEY} from '$env/static/private'

export const supabase = createClient( SUPABASE_URL, SUPABASE_KEY)

src/routes/+page.server.js

import { supabase } from "$lib/supabaseClient";

  export async function load() {
    const { data, error } = await supabase.from("myBooks").select();
    console.log('Data : ', data)
    console.log('Error : ', error)
    return {
      myBooks: data ?? [],
    };
  }

src/routes/+page.svelte

<script>
    import BookCard from '../components/BookCard.svelte';
    export let data = [];
</script>

<div>
    {#each data.myBooks as book}
      <BookCard
        title={book.title}
        description={book.description}
        siteUrl={book.author}
    />
    {/each}
</div>

I have created the appropriate table in Supabase and enabled RLS on it. When I run my code, my terminal displays the following error:

Data :  null
Error : {
  message: 'TypeError: fetch failed',
  details: 'TypeError: fetch failed\n' +
    '    at fetch (C:\\Users\\User\\Desktop\\Code\\Books\\node_modules\\undici\\index.js:110:15)\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n' +
    '    at async load (C:/Users/User/Desktop/Code/Books/src/routes/+page.server.js:7:29)\n' +
    '    at async Module.load_server_data (C:/Users/User/Desktop/Code/Books/node_modules/@sveltejs/kit/src/runtime/server/page/load_data.js:57:17)\n' +
    '    at async eval (C:/Users/User/Desktop/Code/Books/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:150:13)',
  hint: '',
  code: ''
}

I am not sure how to fix it. I tried following the exact Supabase documentation for fetching items from the database

Edit : I tried fetching the data client side via onMount (just for testing purposes), and it works properly. So, there is no issue in the setting up of the database.

1

There are 1 answers

0
PatrickS On

Please check the docs here: Creating a Supabase client for SSR

For your use case, you need to create a Supabase server client since you're attempting to fetch data from +page.server.js

Here a server client is created in hooks.server.js, client that you can then access via the event.locals property.

import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from 
'$env/static/public'
import { createServerClient } from '@supabase/ssr'
import type { Handle } from '@sveltejs/kit'

export const handle: Handle = async ({ event, resolve }) => {
event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, 
PUBLIC_SUPABASE_ANON_KEY, {
cookies: {
  get: (key) => event.cookies.get(key),
  /**
   * Note: You have to add the `path` variable to the
   * set and remove method due to sveltekit's cookie API
   * requiring this to be set, setting the path to an empty string
   * will replicate previous/standard behaviour 
 (https://kit.svelte.dev/docs/types#public-types-cookies)
   */
  set: (key, value, options) => {
    event.cookies.set(key, value, { ...options, path: '/' })
  },
  remove: (key, options) => {
    event.cookies.delete(key, { ...options, path: '/' })
  },
},
  })

  /**
  * a little helper that is written for convenience so that instead
  * of calling `const { data: { session } } = await 
  supabase.auth.getSession()`
  * you just call this `await getSession()`
  */
  event.locals.getSession = async () => {
  const {
   data: { session },
  } = await event.locals.supabase.auth.getSession()
  return session
  }

 return resolve(event, {
    filterSerializedResponseHeaders(name) {
    return name === 'content-range'
   },
  })
  }