I am working on a SvelteKit application and using Supabase for user authentication. I have implemented the sign-in functionality in my /signin/+page.server.ts file using the supabase.auth.signInWithPassword method. However, I am unable to figure out how to check if a user is currently signed in or not.
I have searched online for solutions but most of the information is outdated and based on SvelteKit helpers for Supabase. I am looking for a way to check if a user is signed in without using these helpers, if possible.
Here is how I sign them in, inside my /signin/+page.server.ts:
import type { Actions } from "./$types";
import { supabase } from "$lib/supabaseClient";
export const actions = {
default: async ({ request }) => {
const formData = await request.formData();
const email = formData.get("email");
const password = formData.get("password");
let { data, error } = await supabase.auth.signInWithPassword({
email: email,
password: password,
});
console.log(data, error);
},
} satisfies Actions;
This is how my supabaseClient is initialized in my src/lib/supabaseClient.js:
import { createClient } from "@supabase/supabase-js";
const supabaseUrl = import.meta.env.VITE_SUPABASEURL;
const supabaseKey = import.meta.env.VITE_SUPABASEKEY;
export const supabase = createClient(supabaseUrl, supabaseKey);
How can I check if a user is signed in or not using just Supabase? If possible, please provide an example without using the SvelteKit helpers for Supabase.
The Sveltekit helpers make this very straightforward.
const { data: { session }, } = await supabase.auth.getSession()
and you could call that in your hooks.server.ts to protect any routes that require authentication. This video does a good job of explaining how and this one explains why doing it in hooks is safer than in layout.server.
If you really don't want to use the Sveltekit helpers, you could drop down to one of the lower layers of abstraction underlying them:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With