0

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.

2
  • could be that your request isn't making to supabase, when on server. where are you running this - localhost? Commented Oct 21, 2023 at 6:26
  • 1
    This is due to SvelteKit being a SSR framework and cannot get the session from localStorage since that is only available on the client-side. Please take a look at the @supabase/auth-helpers-sveltekit in order to have access to the session on both client and server. Please follow this more detailed guide for better understanding of how it works supabase.com/docs/guides/getting-started/tutorials/… Commented Oct 23, 2023 at 14:47

1 Answer 1

0

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'
   },
  })
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.