sveltekitsupabasesupabase-js

get User id in +server.ts


So, I am trying to create an API route in sveltekit to access the supabase Database to retrieve some data but I can't manage to do it because I can't get the user object in the +server.ts file that I have created. Here is the code

import type { RequestHandler } from './$types';
import { supabase } from '$lib/supabaseClient';
export const GET: RequestHandler = async () => 
{   
    //get the user id to access the db row
    const user = await supabase.auth.getUser();
    const userid = user.data.user?.id;
    console.log(user);

    //get the user info from the db (not working returns null)
    const { data, error } = await supabase
        .from('profiles')
        .select('credits')
        .eq('id', userid)
        .single();

    console.log(data);

    if (data != null)
    {
        return new Response(data.credits);
    }
    else
    {
        return new Response("No data found", { status: 404 });
    }
};

Anyway, the error that I'm getting is this: error: AuthSessionMissingError: Auth session missing! And by logging the user, I get data: { user: null }


Solution

  • First I wanted to say that I followed the guide to set up everything in https://supabase.com/docs/guides/auth/server-side/sveltekit

    Then I found the solution by looking at a project made by supabase https://supabase.com/docs/guides/getting-started/tutorials/with-sveltekit So I edited the code according to the guide and it worked

    import type { RequestHandler } from './$types';
    export const GET: RequestHandler = async ({locals : {supabase, safeGetSession}}) => {   
    //get the user id to access the db row
    const { session } = await safeGetSession();
    
    console.log(session?.user.id);
    
    //get the user info from the db (not working returns null)
    const { data, error } = await supabase
        .from('profiles')
        .select('credits')
        .eq('id', session?.user.id)
        .single();
    
    if (data != null)
    {
        return new Response(data.credits);
    }
    else
    {
        return new Response("No data found", {status: 404 });
    }
    };