htmx

How can I make HTMX display a 403 error page returned from a hx-delete request?


In my project, when the web browser submits a hx-delete request, and the backend determines the user doesn't have the required permissions for that request, the backend returns a full 403 error page. By default HTMX ignores this response. I would like HTMX to instead display the full 403 error page.

How can I do this?


Solution

  • I solved my problem by adding this code to the page.

    /***
     * Swaps in the body of error pages returned from htmx requests 
     */
    document.addEventListener("htmx:beforeOnLoad", function (event) {
        const xhr = event.detail.xhr
        if (xhr.status == 500 || xhr.status == 403 || xhr.status == 404) {
            event.stopPropagation() // Tell htmx not to process these requests
            document.children[0].innerHTML = xhr.response // Swap in body of response instead
        }
    })