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
}Again, you'd typically trigger this function when a user clicks a 'Sign Out' button. After a successful sign-out, it's crucial to update your application's state to reflect that the user is no longer authenticated.
Supabase Auth automatically manages the user's session. When a user signs in, a session is created, and tokens are stored. When the application loads, you'll want to check if there's an active session to determine if the user is already logged in. The auth.getSession() method is perfect for this.
async function checkSession() {
const { data: { session }, error } = await supabase.auth.getSession();
if (error) {
console.error('Error fetching session:', error.message);
return null;
}
if (session) {
console.log('User is already signed in:', session.user);
return session;
} else {
console.log('No active session found.');
return null;
}
}You can call checkSession() when your application initializes. Based on the result, you can either show the logged-in view or the login/signup forms. Supabase also provides real-time session change listeners, which are invaluable for instantly updating your UI when a user's authentication state changes (e.g., if they sign in on another device).
supabase.auth.onAuthStateChange((event, session) => {
console.log('Auth state changed:', event, session);
// Update your UI or application state based on the event and session
});graph TD
A[User Clicks Sign In] --> B{Enter Email & Password};
B --> C[Call supabase.auth.signInWithPassword];
C --> D{Credentials Valid?};
D -- Yes --> E[Session Created & Returned];
D -- No --> F[Display Error Message];
E --> G[Update UI/Redirect];
G --> H(User Signed In);
H --> I[Listen for Auth State Changes];
I --> J{Sign Out Clicked?};
J -- Yes --> K[Call supabase.auth.signOut];
K --> L[Session Invalidated];
L --> M[Update UI/Redirect];
M --> N(User Signed Out);