Events
React to the authentication events of Light-Auth.
Overview
The CreateLightAuth configuration accepts hooks, called by Light-Auth during the authentication flows. Use them to log an audit trail, send a welcome email, keep your own database in sync, or add custom properties to the session and the user.
export const { providers, handlers, signIn, signOut, getAuthSession, getUser } = CreateLightAuth({
providers: [googleProvider, credentialsProvider],
onLogin: async (session, providerName) => {
await audit.log("login", { userId: session.providerUserId, providerName });
},
onLogout: async (session, providerName) => {
await audit.log("logout", { userId: session.providerUserId, providerName });
},
onRegister: async (session) => {
await sendWelcomeEmail(session.email);
},
onSessionExpired: async (session) => {
console.info(`the session of ${session.email} has expired`);
},
onTokenRefresh: async (user, providerName) => {
console.info(`the ${providerName} access token of ${user.email} has been refreshed`);
},
onPasswordReset: async (email) => {
await audit.log("password-reset-requested", { email });
},
onError: async (error, eventName) => {
console.error(`light-auth ${eventName} failed:`, error);
},
});All the hooks are optional, and can be synchronous or asynchronous.
Available hooks
| Hook | Signature | Called |
|---|---|---|
| onSessionSaving | (session, tokens?, metadata?) => Session | null | Before a session is saved: OAuth sign in (with the provider tokens), credentials login and registration, setAuthSession(). Return the session to save, null keeps the original one. |
| onSessionSaved | (session, metadata?) => void | After a session is saved, including when its expiration is renewed by the session endpoint. |
| onUserSaving | (user, tokens?, metadata?) => User | null | Before a user is saved: OAuth sign in, access token refresh (with the new tokens), credentials login and registration, setUser(). Return the user to save, null keeps the original one. |
| onUserSaved | (user, metadata?) => void | After a user is saved by the user adapter. |
| onLogin | (session, providerName) => void | After a successful sign in, with an OAuth provider or with the credentials provider. |
| onLogout | (session, providerName) => void | During a sign out, once the user is deleted and the tokens revoked, before the session cookie is deleted. |
| onRegister | (session, providerName) => void | After a credentials registration, when the new user is signed in (autoLogin, default). onLogin is not called in this case. |
| onSessionExpired | (session) => void | When the session endpoint finds an expired session, before deleting it. |
| onTokenRefresh | (user, providerName) => void | After the access token of a user has been refreshed by getUser(). |
| onPasswordReset | (email) => void | After a password reset request of the credentials provider. |
| onError | (error, eventName) => void | When a sign in ("login") or a credentials registration ("register") fails. |
Each OAuth provider also accepts an onGetOAuth2Tokens(tokens, metadata) hook, called with the tokens returned by the provider at sign in and on each refresh. See Providers.
Order of the hooks
| Flow | Hooks, in order |
|---|---|
| OAuth sign in | onGetOAuth2Tokens (provider) → onSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onLogin |
| Credentials login | onSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onLogin |
| Credentials registration | onSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onRegister |
| Sign in or registration failure | onError(error, "login" | "register") |
| Password reset request | onPasswordReset |
| Sign out | onLogout |
| Session read by the browser | onSessionSaved when the expiration is renewed, onSessionExpired when the session has expired |
| getUser() with an expiring access token | onGetOAuth2Tokens (provider) → onUserSaving → onUserSaved → onTokenRefresh |
| setAuthSession() / setUser() | onSessionSaving → onSessionSaved / onUserSaving → onUserSaved |
The onUserSaving / onUserSaved hooks are only called when a user adapter is configured, which is the case by default.
Saving hooks
onSessionSaving and onUserSaving receive the object about to be saved, and the tokens returned by the OAuth provider when there are some. Return the object to save: this is the place to add your own properties, from the validated id_token claims for instance.
export const { handlers, signIn, signOut, getAuthSession, getUser } = CreateLightAuth<MyLightAuthSession, MyLightAuthUser>({
providers: [googleProvider],
onSessionSaving: async (session, tokens) => {
// tokens is only set for OAuth sign ins
const claims = tokens?.idTokenClaims;
if (typeof claims?.given_name === "string") session.firstName = claims.given_name;
return session;
},
onUserSaving: async (user, tokens) => {
if (tokens?.scopes) user.grantedScopes = tokens.scopes;
return user;
},
});Errors and metadata
- The hooks run inside the request: keep them fast, and move long tasks (emails, webhooks...) to a queue when you can.
- An exception thrown by
onSessionSaving,onUserSavingoronLogininterrupts the sign in: the error is given toonError, then the user is redirected to the callback URL (OAuth) or receives a500response (credentials). - Exceptions thrown by
onLogout,onSessionExpiredandonPasswordResetare caught: they never break the flow. - An exception thrown by
onTokenRefreshmakesgetUser()returnnull. onErroritself must not throw.
metadata argument is the context of the current request: the objects given by your framework adapter (req, event, context...) and the values being processed, which may include the submitted form fields of a credentials login. Never log or store it as a whole.