非同期認証

このサンプルは、htmx の非同期認証トークンフローを実装する方法を示します。

ここでは、htmx:confirm イベントを使用してリクエストを遅延させることができるという事実を利用した手法を使用します。

最初に、認証トークンが取得されるまでリクエストを発行しないボタンを用意します。

  <button hx-post="/example" hx-target="next output">
    An htmx-Powered button
  </button>
  <output>
    --
  </output>

次に、auth プロミス(ライブラリから返される)と一緒に動作するスクリプティングを追加します。

<script>
  // auth is a promise returned by our authentication system

  // await the auth token and store it somewhere
  let authToken = null;
  auth.then((token) => {
    authToken = token
  })
  
  // gate htmx requests on the auth token
  htmx.on("htmx:confirm", (e)=> {
    // if there is no auth token
    if(authToken == null) {
      // stop the regular request from being issued
      e.preventDefault() 
      // only issue it once the auth promise has resolved
      auth.then(() => e.detail.issueRequest()) 
    }
  })

  // add the auth token to the request as a header
  htmx.on("htmx:configRequest", (e)=> {
    e.detail.headers["AUTH"] = authToken
  })
</script>

ここではグローバル変数を使用していますが、localStorage や、認証トークンを htmx:configRequest イベントに渡すために望むメカニズムを使用できます。

このコードを配置すると、htmx は auth プロミスが解決されるまでリクエストを発行しません。