コンテンツにスキップ

イベント

@authrim/web は認証関連イベントを購読するための auth.on() を公開しています。ログイン、ログアウト、トークン更新が SDK から emit されたときに、UI 更新、analytics 記録、ローカル状態の cleanup などを実行できます。

多くの Direct Auth / OAuth エラーはイベントではなく AuthResponse<T> で返ります。エラーは呼び出し元で処理し、イベントは横断的な副作用に使ってください。

auth.on() でイベントハンドラーを登録します。

const unsubscribe = auth.on('auth:login', (payload) => {
console.log('ログインしました:', payload.user);
console.log('方法:', payload.method);
});
// 後でサブスクライブ解除
unsubscribe();

auth.on() はサブスクライブ解除関数を返します。呼び出すとハンドラーが削除されます。

Direct Auth のログイン成功後、または Smart Handoff 保存後に発火します。

auth.on('auth:login', (payload) => {
// payload.session: Session
// payload.user: User
// payload.method: 'passkey' | 'emailCode' | 'social'
});

以下の後に発火します。

  • auth.passkey.login() または auth.passkey.signUp()
  • auth.emailCode.verify()
  • auth.social.loginWithPopup() または auth.social.handleCallback()
  • auth.handoff.verifyAndSave()

auth.signOut() の後に発火します。

auth.on('auth:logout', (payload) => {
// payload.redirectUri?: string
});

signOutApplicationGroup()signOutAll()signOut() に委譲するため、同じ logout event 経路を使います。

OAuth popup flow で token set が返されたあとに発火します。

auth.on('token:refreshed', (payload) => {
// payload.session: Session 相当の expiry metadata
console.log('トークン有効期限:', payload.session.expiresAt);
});

Direct Auth の refresh helper は値を直接返すため、呼び出し元で処理してください。

型にはあるが主経路ではないイベント

Section titled “型にはあるが主経路ではないイベント”

公開 event 型には、互換性と将来/内部連携向けに以下も含まれます。

イベントペイロード現在の扱い
session:changed{ session, user }明示的な session check と Tab Sync broadcast を優先
session:expired{ reason }auth.session.validate() や protected API failure で検知
auth:error{ error }Direct Auth / OAuth メソッドは通常 AuthResponse<T> の error を返す
auth.on('auth:login', ({ user }) => {
document.getElementById('user-name')!.textContent =
user.name ?? user.email ?? '';
document.getElementById('auth-section')!.classList.add('authenticated');
});
auth.on('auth:logout', () => {
document.getElementById('auth-section')!.classList.remove('authenticated');
});
auth.on('auth:login', ({ method, user }) => {
analytics.track('login', {
method,
userId: user.id,
});
});
auth.on('auth:logout', () => {
analytics.track('logout');
});
const result = await auth.emailCode.verify(email, code);
if (result.error) {
analytics.track('auth_error', {
code: result.error.code,
message: result.error.message,
});
showError(result.error.message);
return;
}

同じイベントに複数のハンドラーを登録できます。

auth.on('auth:login', ({ user }) => {
updateUI(user);
});
auth.on('auth:login', ({ method }) => {
analytics.track('login', { method });
});

コンポーネントやページのアンマウント時は必ずサブスクライブを解除します。

const handlers = [
auth.on('auth:login', handleLogin),
auth.on('auth:logout', handleLogout),
auth.on('token:refreshed', handleTokenRefresh),
];
function cleanup() {
handlers.forEach((unsubscribe) => unsubscribe());
}
window.addEventListener('beforeunload', cleanup);