forked from
smokesignal.events/smokesignal
The smokesignal.events web application
1/**
2 * htmx Auth Refresh Extension
3 *
4 * Automatically refreshes the OAuth session before HTMX requests.
5 * This ensures that the access token is valid before navigation,
6 * preventing users from being redirected to login mid-navigation.
7 */
8
9import type { HtmxApi, HtmxConfirmEvent } from '../types'
10import { refreshSession } from '../auth'
11
12export function initAuthRefreshExtension(htmx: HtmxApi): void {
13 htmx.defineExtension('auth-refresh', {
14 onEvent(name: string, evt: HtmxConfirmEvent) {
15 if (name === 'htmx:confirm') {
16 // Prevent the default request behavior
17 evt.preventDefault()
18
19 // Refresh session, then issue the request
20 refreshSession()
21 .catch((error) => {
22 console.warn('Auth refresh before request failed:', error)
23 })
24 .finally(() => {
25 // Always issue the request, even if refresh failed
26 // The server will handle 401 responses appropriately
27 evt.detail.issueRequest()
28 })
29 }
30 },
31 })
32}