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.
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.