/** * htmx Auth Refresh Extension * * Automatically refreshes the OAuth session before HTMX requests. * This ensures that the access token is valid before navigation, * preventing users from being redirected to login mid-navigation. */ import type { HtmxApi, HtmxConfirmEvent } from '../types' import { refreshSession } from '../auth' export function initAuthRefreshExtension(htmx: HtmxApi): void { htmx.defineExtension('auth-refresh', { onEvent(name: string, evt: HtmxConfirmEvent) { if (name === 'htmx:confirm') { // Prevent the default request behavior evt.preventDefault() // Refresh session, then issue the request refreshSession() .catch((error) => { console.warn('Auth refresh before request failed:', error) }) .finally(() => { // Always issue the request, even if refresh failed // The server will handle 401 responses appropriately evt.detail.issueRequest() }) } }, }) }