Custom Logic with Callbacks
Customize your login and registration behavior
Passage is designed to work out-of-the-box for most applications, but there may be times where you need to customize or add additional login and registration behavior to the authentication workflow. All three Passage elements support a
beforeAuth
and an onSuccess
callback.The
beforeAuth
callback is executed when the user presses the Login or Register button after entering their email or phone number. A common use case for this would be collecting and validating additional user information when the user is registering for the first time. The
beforeAuth
callback is set as a property on the element that accepts a function with the following prototype:type BeforeAuthCallback = (identifier: string) => boolean
When the callback is invoked, the user's identifier is provided as a parameter. After doing additional work to validate any other requirements, the callback should return
true
to continue with the registration/login, or return false
to cancel the registration/login.An example of assigning this callback might look like:
const beforeAuth = (identifier: string) =>{
const success = validateAndStoreUserInfo(identifier)
return success
}
const passageAuth = document.querySelector("passage-auth") as PassageElement
passageAuth.beforeAuth = beforeAuth
The default behavior for this callback is to do nothing and return
true
.The
onSuccess
callback is executed when a user is successfully logged in. This allows you to customize the behavior for handling successful authentication. An example of this would be storing the authorization token to be used by your backend code, customizing where users should be redirected after a login, or setting other fields client-side.The
onSuccess
callback is set as a property on the element that accepts a function with the following prototype:interface authResult {
redirect_url: string;
auth_token: string;
refresh_token?: string; // only if you have refresh tokens enabled.
refresh_token_expiration?: number; // only if you have refresh tokens enabled
}
type OnSuccessCallback = (authResult: authResult) => void
If you provide a custom
onSuccess
callback, the auth token and redirect URL will be provided for use within the callback. The auth token will still be automatically stored for use in your application in a cookie called psg_auth_token
. An example
onSuccess
callback might look like:const onSuccess = (authResult: authResult) =>{
localStorage.setItem('psg_auth_token', authResult.auth_token)
window.location.href = authResult.redirect_url
}
const passageAuth = document.querySelector("passage-auth") as PassageElement
passageAuth.onSuccess = onSuccess
The default behavior for this callback is to set the Passage auth token (
psg_auth_token
) in a cookie and in local storage, then redirect to the app's redirect URL.