Kirtan Patel
Kirtan Patel

Reputation: 166

How to perform redirect in HTMX based on response from the Spring boot JSON rest API?

I am checking examples of Htmx + Spring. All examples use server-side template engines ( like Thymeleaf or Jte).

Htmx expects an HTML response from Spring, but Nowadays, most Spring applications provide a Rest API with a JSON response instead.

Is there any way to redirect in HTMX based on Rest Response from Spring boot Rest API?

Basic requirement:
Login.html 
    -> on login action using hx-post="/login" 
        -> Check the response
            -> If successful, then redirect to the dashboard.html 
            -> If error, stay on the same page and show an error message.

Manage-User.html
   -> Submit new user request hx-post="/users"
        -> Check the response
            -> If successful, then go to view user page with data (using client-side template engine like moustache)
            -> If error, stay on the same page and show the error message.

I know it can be achieved by writing JavaScript, but I want to know if any other way exists.

Htmx supports hx-redirect but it will only work if the server sends in the header but there is no way to define redirect based on response code/response data.

Upvotes: 1

Views: 93

Answers (1)

Slava Semushin
Slava Semushin

Reputation: 15204

Htmx supports hx-redirect but it will only work if the server sends in the header but there is no way to define redirect based on response code/response data

Redirect on a client-side is possible with <meta http-equiv="refresh"> tag but HTMX don't work with <head> by default. head-support extension might help to address this.

UPDATE: there is also another approach: you may write a listener for htmx:beforeSwap event and set window.location.href to a desired URL. See for details: https://refine.dev/blog/what-is-htmx/#6-handling-different-http-error-codes


But it seems like we're trying to implement a routing and it is out-of-scope for HTMX: HTMX client side routing?

I found some attempts but all of them are stale now:

Upvotes: 0

Related Questions