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.

./lib/auth.ts
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

HookSignatureCalled
onSessionSaving(session, tokens?, metadata?) => Session | nullBefore 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?) => voidAfter a session is saved, including when its expiration is renewed by the session endpoint.
onUserSaving(user, tokens?, metadata?) => User | nullBefore 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?) => voidAfter a user is saved by the user adapter.
onLogin(session, providerName) => voidAfter a successful sign in, with an OAuth provider or with the credentials provider.
onLogout(session, providerName) => voidDuring a sign out, once the user is deleted and the tokens revoked, before the session cookie is deleted.
onRegister(session, providerName) => voidAfter a credentials registration, when the new user is signed in (autoLogin, default). onLogin is not called in this case.
onSessionExpired(session) => voidWhen the session endpoint finds an expired session, before deleting it.
onTokenRefresh(user, providerName) => voidAfter the access token of a user has been refreshed by getUser().
onPasswordReset(email) => voidAfter a password reset request of the credentials provider.
onError(error, eventName) => voidWhen 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

FlowHooks, in order
OAuth sign inonGetOAuth2Tokens (provider) → onSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onLogin
Credentials loginonSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onLogin
Credentials registrationonSessionSaving → onSessionSaved → onUserSaving → onUserSaved → onRegister
Sign in or registration failureonError(error, "login" | "register")
Password reset requestonPasswordReset
Sign outonLogout
Session read by the browseronSessionSaved when the expiration is renewed, onSessionExpired when the session has expired
getUser() with an expiring access tokenonGetOAuth2Tokens (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.

./lib/auth.ts
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;
  },
});

More details on custom properties in Session and 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, onUserSaving or onLogin interrupts the sign in: the error is given to onError, then the user is redirected to the callback URL (OAuth) or receives a 500 response (credentials).
  • Exceptions thrown by onLogout, onSessionExpired and onPasswordReset are caught: they never break the flow.
  • An exception thrown by onTokenRefresh makes getUser() return null.
  • onError itself must not throw.
The 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.