📖 Scenario: You are building a simple web app that needs to react when users log in or log out. You will use Supabase's authentication state change listeners to detect these changes and update the app accordingly.
🎯 Goal: Create a Supabase client and set up an authentication state change listener that logs the current user status whenever it changes.
📋 What You'll Learn
Create a Supabase client with the given URL and anon key
Set up a variable to hold the current user
Add an auth state change listener using supabase.auth.onAuthStateChange
Update the current user variable inside the listener callback
💡 Why This Matters
🌍 Real World
Web apps often need to know when users log in or out to update the interface or restrict access. Using auth state change listeners helps apps react instantly to these changes.
💼 Career
Understanding how to listen for authentication changes is key for frontend and backend developers working with user sessions and security in cloud-based applications.
Progress0 / 4 steps
1
Create the Supabase client
Create a constant called supabase by calling createClient with the URL 'https://xyzcompany.supabase.co' and the anon key 'public-anon-key'.
Supabase
Hint
Use createClient from @supabase/supabase-js with the exact URL and anon key.
2
Create a variable to hold the current user
Create a variable called currentUser and set it to null.
Supabase
Hint
Use let to declare currentUser and initialize it to null.
3
Set up the auth state change listener
Use supabase.auth.onAuthStateChange with a callback that takes event and session as parameters. Inside the callback, set currentUser to session?.user ?? null.
Supabase
Hint
Use optional chaining session?.user to safely get the user or set null if no session.
4
Complete by exporting the current user variable
Add the line export { currentUser }; at the end of the file to allow other parts of the app to access the current user.
Supabase
Hint
Use export to share currentUser with other modules.
Practice
(1/5)
1. What is the main purpose of an auth state change listener in Supabase?
easy
A. To send emails to users automatically
B. To store user data permanently in the database
C. To detect when a user logs in or logs out and update the app accordingly
D. To encrypt user passwords before login
Solution
Step 1: Understand auth state change listener role
An auth state change listener watches for user login or logout events.
Step 2: Identify its main use in app behavior
It updates the app UI or logic based on whether the user is signed in or out.
Final Answer:
To detect when a user logs in or logs out and update the app accordingly -> Option C
Quick Check:
Auth listener updates app on login/logout [OK]
Hint: Auth listeners track login/logout to update app UI [OK]
Common Mistakes:
Thinking it sends emails automatically
Confusing with data storage functions
Assuming it encrypts passwords
2. Which of the following is the correct way to subscribe to auth state changes in Supabase?
easy
A. supabase.auth.subscribe((event, session) => { /* handler */ })
B. supabase.auth.onAuthStateChange((event, session) => { /* handler */ })
C. supabase.auth.listenAuthChange((event, session) => { /* handler */ })
D. supabase.auth.watchStateChange((event, session) => { /* handler */ })
Solution
Step 1: Recall Supabase auth listener method
The correct method to listen for auth changes is onAuthStateChange.
Step 2: Verify method signature
It takes a callback with parameters event and session.
Hint: Use onAuthStateChange method to listen auth events [OK]
Common Mistakes:
Using non-existent methods like listenAuthChange
Confusing subscribe or watchStateChange methods
Incorrect callback parameters
3. What will be logged by this code snippet when a user signs out?
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
console.log(event);
});
// User signs out here
supabase.auth.signOut();
medium
A. "SIGNED_OUT"
B. "SIGNED_IN"
C. "USER_UPDATED"
D. No output
Solution
Step 1: Understand event on user sign out
When a user signs out, the event emitted is "SIGNED_OUT".
Step 2: Check console.log output
The listener logs the event string, so it will print "SIGNED_OUT".
Final Answer:
"SIGNED_OUT" -> Option A
Quick Check:
Sign out triggers SIGNED_OUT event [OK]
Hint: Sign out triggers SIGNED_OUT event logged [OK]
Common Mistakes:
Expecting SIGNED_IN on sign out
Thinking USER_UPDATED triggers on sign out
Assuming no event is logged
4. Identify the error in this code that listens for auth state changes:
const authListener = supabase.auth.onAuthStateChange((event, session) => {
if(event === 'SIGNED_IN') {
console.log('User signed in');
}
});
// Later in code
authListener.unsubscribe();
medium
A. authListener.unsubscribe() is incorrect; should use authListener.data.subscription.unsubscribe()
B. Callback function parameters are wrong
C. Event name 'SIGNED_IN' is invalid
D. No need to unsubscribe from authListener
Solution
Step 1: Check how onAuthStateChange returns subscription
It returns an object with a data property containing the subscription.
Step 2: Verify unsubscribe method call
Unsubscribe should be called on authListener.data.subscription.unsubscribe(), not directly on authListener.unsubscribe().
Final Answer:
authListener.unsubscribe() is incorrect; should use authListener.data.subscription.unsubscribe() -> Option A
Quick Check:
Unsubscribe via authListener.data.subscription.unsubscribe() [OK]
Hint: Call unsubscribe on data.subscription, not directly [OK]
Common Mistakes:
Calling unsubscribe directly on listener object
Misnaming event strings
Skipping unsubscribe causing memory leaks
5. You want to update your app UI only when a user signs in or signs out, but not on other auth events. Which code snippet correctly implements this using Supabase auth state change listener?