Now that we've explored the basics of Supabase Auth, let's dive into the practical implementation of user sign-in and sign-out. This is a fundamental part of any application, and Supabase makes it remarkably straightforward. We'll cover both email/password authentication and how to manage the user's session.
To sign a user in, we'll use the signInWithPassword method from the Supabase client. This method requires an object containing the user's email and password. If the credentials are valid, Supabase will return a session object, indicating a successful sign-in.
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';
const supabase = createClient(supabaseUrl, supabaseAnonKey);
async function handleSignIn(email, password) {
const { data, error } = await supabase.auth.signInWithPassword({
email: email,
password: password,
});
if (error) {
console.error('Sign-in error:', error.message);
return null;
}
console.log('User signed in:', data.user);
return data.session;
}In a real-world application, you would typically call this function when a user submits a sign-in form. You'd then handle any errors gracefully and redirect the user or update your UI to reflect their logged-in state.
Signing a user out is just as simple. The signOut method from supabase.auth will invalidate the current user's session and clear any associated tokens. This effectively logs the user out of your application.
async function handleSignOut() {
const { error } = await supabase.auth.signOut();
if (error) {
console.error('Sign-out error:', error.message);
return;
}
console.log('User signed out successfully.');
// Redirect user or update UI to reflect logged-out state
}