JavaScript: Listen to auth events (original) (raw)
- Introduction
- Installing
- Initializing
- TypeScript support
- Database
- Fetch data
- Insert data
- Update data
- Upsert data
- Delete data
- Call a Postgres function
- Using filters
- Column is equal to a value
- Column is not equal to a value
- Column is greater than a value
- Column is greater than or equal to a value
- Column is less than a value
- Column is less than or equal to a value
- Column matches a pattern
- Column matches a case-insensitive pattern
- Column is a value
- Column is in an array
- Column contains every element in a value
- Contained by value
- Greater than a range
- Greater than or equal to a range
- Less than a range
- Less than or equal to a range
- Mutually exclusive to a range
- With a common element
- Match a string
- Match an associated value
- Don't match the filter
- Match at least one filter
- Match the filter
- Using modifiers
- Return data after inserting
- Order the results
- Limit the number of rows returned
- Limit the query to a range
- Set an abort signal
- Retrieve one row of data
- Retrieve zero or one row of data
- Retrieve as a CSV
- Override type of successful response
- Partially override or replace type of successful response
- Using explain
- Auth
- Overview
- Create a new user
- Listen to auth events
- Create an anonymous user
- Sign in a user
- Sign in with ID Token
- Sign in a user through OTP
- Sign in a user through OAuth
- Sign in a user through SSO
- Sign out a user
- Send a password reset request
- Verify and log in through OTP
- Retrieve a session
- Retrieve a new session
- Retrieve a user
- Update a user
- Retrieve identities linked to a user
- Link an identity to a user
- Unlink an identity from a user
- Send a password reauthentication nonce
- Resend an OTP
- Set the session data
- Exchange an auth code for a session
- Start auto-refresh session (non-browser)
- Stop auto-refresh session (non-browser)
- Auth MFA
- Enroll a factor
- Create a challenge
- Verify a challenge
- Create and verify a challenge
- Unenroll a factor
- Get Authenticator Assurance Level
- Auth Admin
- Retrieve a user
- List all users
- Create a user
- Delete a user
- Send an email invite link
- Generate an email link
- Update a user
- Delete a factor for a user
- Edge Functions
- Invokes a Supabase Edge Function.
- Realtime
- Subscribe to channel
- Unsubscribe from a channel
- Unsubscribe from all channels
- Retrieve all channels
- Broadcast a message
- Storage
- Create a bucket
- Retrieve a bucket
- List all buckets
- Update a bucket
- Delete a bucket
- Empty a bucket
- Upload a file
- Download a file
- List all files in a bucket
- Replace an existing file
- Move an existing file
- Copy an existing file
- Delete files in a bucket
- Create a signed URL
- Create signed URLs
- Create signed upload URL
- Upload to a signed URL
- Retrieve public URL
- Misc
- Release Notes
Receive a notification every time an auth event happens.
- Subscribes to important events occurring on the user's session.
- Use on the frontend/client. It is less useful on the server.
- Events are emitted across tabs to keep your application's UI up-to-date. Some events can fire very frequently, based on the number of tabs open. Use a quick and efficient callback function, and defer or debounce as many operations as you can to be performed outside of the callback.
- Important: A callback can be an
async
function and it runs synchronously during the processing of the changes causing the event. You can easily create a dead-lock by usingawait
on a call to another method of the Supabase library.- Avoid using
async
functions as callbacks. - Limit the number of
await
calls inasync
callbacks. - Do not use other Supabase functions in the callback function. If you must, dispatch the functions once the callback has finished executing. Use this as a quick way to achieve this:
supabase.auth.onAuthStateChange((event, session) => { setTimeout(async () => { // await on other Supabase function here // this runs right after the callback has finished }, 0) })
- Avoid using
- Emitted events:
INITIAL_SESSION
* Emitted right after the Supabase client is constructed and the initial session from storage is loaded.SIGNED_IN
* Emitted each time a user session is confirmed or re-established, including on user sign in and when refocusing a tab.
* Avoid making assumptions as to when this event is fired, this may occur even when the user is already signed in. Instead, check the user object attached to the event to see if a new user has signed in and update your application's UI.
* This event can fire very frequently depending on the number of tabs open in your application.SIGNED_OUT
* Emitted when the user signs out. This can be after:
* A call tosupabase.auth.signOut()
.
* After the user's session has expired for any reason:
* User has signed out on another device.
* The session has reached its timebox limit or inactivity timeout.
* User has signed in on another device with single session per user enabled.
* Check the User Sessions docs for more information.
* Use this to clean up any local storage your application has associated with the user.TOKEN_REFRESHED
* Emitted each time a new access and refresh token are fetched for the signed in user.
* It's best practice and highly recommended to extract the access token (JWT) and store it in memory for further use in your application.
* Avoid frequent calls tosupabase.auth.getSession()
for the same purpose.
* There is a background process that keeps track of when the session should be refreshed so you will always receive valid tokens by listening to this event.
* The frequency of this event is related to the JWT expiry limit configured on your project.USER_UPDATED
* Emitted each time thesupabase.auth.updateUser()
method finishes successfully. Listen to it to update your application's UI based on new profile information.PASSWORD_RECOVERY
* Emitted instead of theSIGNED_IN
event when the user lands on a page that includes a password recovery link in the URL.
* Use it to show a UI to the user where they can reset their password.
Parameters
callback
(Required)
A callback function to be invoked when an auth event happens.
Examples
Listen to auth changes
const { data } = supabase.auth.onAuthStateChange((event, session) => {
console.log(event, session)
if (event === 'INITIAL_SESSION') {
// handle initial session
} else if (event === 'SIGNED_IN') {
// handle sign in event
} else if (event === 'SIGNED_OUT') {
// handle sign out event
} else if (event === 'PASSWORD_RECOVERY') {
// handle password recovery event
} else if (event === 'TOKEN_REFRESHED') {
// handle token refreshed event
} else if (event === 'USER_UPDATED') {
// handle user updated event
}
})
// call unsubscribe to remove the callback
data.subscription.unsubscribe()
Listen to sign out
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
console.log('SIGNED_OUT', session)
// clear local and session storage
[
window.localStorage,
window.sessionStorage,
].forEach((storage) => {
Object.entries(storage)
.forEach(([key]) => {
storage.removeItem(key)
})
})
}
})
Store OAuth provider tokens on sign in
// Register this immediately after calling createClient!
// Because signInWithOAuth causes a redirect, you need to fetch the
// provider tokens from the callback.
supabase.auth.onAuthStateChange((event, session) => {
if (session && session.provider_token) {
window.localStorage.setItem('oauth_provider_token', session.provider_token)
}
if (session && session.provider_refresh_token) {
window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)
}
if (event === 'SIGNED_OUT') {
window.localStorage.removeItem('oauth_provider_token')
window.localStorage.removeItem('oauth_provider_refresh_token')
}
})
Use React Context for the User's session
const SessionContext = React.createContext(null)
function main() {
const [session, setSession] = React.useState(null)
React.useEffect(() => {
const {data: { subscription }} = supabase.auth.onAuthStateChange(
(event, session) => {
if (event === 'SIGNED_OUT') {
setSession(null)
} else if (session) {
setSession(session)
}
})
return () => {
subscription.unsubscribe()
}
}, [])
return (
<SessionContext.Provider value={session}>
<App />
</SessionContext.Provider>
)
}
Listen to password recovery events
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'PASSWORD_RECOVERY') {
console.log('PASSWORD_RECOVERY', session)
// show screen to update user's password
showPasswordResetScreen(true)
}
})
Listen to sign in
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') console.log('SIGNED_IN', session)
})
Listen to token refresh
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session)
})
Listen to user updates
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'USER_UPDATED') console.log('USER_UPDATED', session)
})