How to change Browser URL in HTMX

Published 1 Jul, 2022

Reading time: 1 Mins


To change browser URL in HTMX you have to use hx-push-url

Changing Browser URL is important in any single page application. This makes the SPA much like alive and give more flexibility. For example user visited any of your webpage and all of sudden there is a refresh happened then user lost all of it. Which is not a great user experience in any web application.

Best thing you have to do in single page application is to change it to particular url in the browser so that user will come to know which page they are currently visiting or visited.

If you know react-router then you may know that changing browser url is easy like this.props.router.push("/page/2") . In this blog post I am going to tell you how to do that in HTMX. I see HTMX is the server side single page application framework. And using this technique you can change your HTMX url easily.

Assuming you have a GET method and that changes the screen page. To change the browser url you need to use hx-push-url

<div hx-get="/page/2" hx-target="#main" hx-push-url="true">

Above code will make the GET request to server and change the #main element with the response. And in the meantime it will change the browser url from / to /page/2

This article published under development on htmx tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.


You might also like