DEV Community

Ace-Code
Ace-Code

Posted on

I Used HTMX to Create NextJS Intercepted Route

Photo by [Joshua Sortino](https://unsplash.com/@sortino?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)

First of all, I would like to say from the short time that I had experienced HTMX I had so much fun working with it.
In a way, HTMX does what NextJS does, however, there are some aspects that are made better and some that aren’t.

What is intercepted route?

Intercepting routes allows you to load a route within the current layout while keeping the context for the current page. This routing paradigm can be useful when you want to “intercept” a certain route to show a different route.

https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes

Example:

Let's just say you want to have a Sign In page.
There are 2 ways to get to the Sign In page:
By pressing a button on the Home page, the Sign In page loads in a modal.
By going there with a URL, the Sign In page loads entirely.

Home screen with a Sign In Button

Sign In modal opened in the Home Screen

Sign In web page loaded entirely

Please note!
The important part is the URL.
Even though the pages show different information the page loaded from the same URL!

Thats cool! How is it possible?

There is something that is called History API and it allows you to do something sneaky.
I can push and replace a new URL without reloading the entire page!
That allows me to have the same URL on different pages.

How did you Code This?

<!-- frontend -->
    <div id="signIn" />
    <button
      hx-get="component/signIn"
      hx-replace-url="/signIn"
      hx-target="#signIn"
      className="mr-4 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition duration-200"
    >
      Sign In
    </button>
Enter fullscreen mode Exit fullscreen mode

This is the basis of how to start the process:
hx-get — Create a GET request to get the component from the Server
hx-replace-url — Changes the URL to *
/signIn**
hx-target=”#signIn” — Tells HTMX where I would like to place my content*

Essentially get a component from the server and put it in the inner HTML of

// signInModal.tsx
    export default function SignInModal() {
      return <>
        <div className="animate-fade animate-once animate-duration-300 fixed top-1/2 left-1/2 transform -translate-y-1/2 -translate-x-1/2 bg-white p-5 rounded-md shadow-lg z-20">
          {/* Login Form */}
          <h2 className="font-bold text-lg mb-2 text-blue-500">Sign In</h2>
          <form hx-post={API_SIGNIN}>
            <input
              type="text"
              name={EMAIL}
              placeholder="Email"
              className="w-full p-2 mb-4 border border-gray-200 text-gray-800 rounded"
            />
            <input
              type="password"
              name={PASSWORD}
              placeholder="Password"
              className="w-full p-2 mb-4 border border-gray-200 text-gray-800 rounded"
            />
            <button
              type="submit"
              className="text-white w-full bg-blue-500 hover:bg-blue-600 font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition duration-200"
            >
              <svg aria-hidden="true" role="status" className="htmx-indicator inline w-4 h-4 mr-3 text-white animate-spin" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="#E5E7EB" />
                <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentColor" />
              </svg>
              Sign In
            </button>
          </form>
        </div>
        <button
          hx-on="click: {history.replaceState(null, '', '/'); document.getElementById('signIn').innerHTML = ''}"
          className="fixed inset-0 bg-black opacity-50 z-10 drag-none"
        />
      </>
    }
There is a lot of stuff here
Lets concentrate on the button at the end of the file:

    <button
          hx-on="click: {history.replaceState(null, '', '/'); document.getElementById('signIn').innerHTML = ''}"
          className="fixed inset-0 bg-black opacity-50 z-10 drag-none"
        />

In order to create an overlay that closes the modal when clicked,
I created a button that listens to the click event and does the following.

  1. Replace the URL from SignIn back to the root

  2. Undo all the swaps we did for the signIn div.

And that’s pretty much it!

Wait! How did you render react component back to the client?

    import { renderToString } from "../util/renderToString";
    export async function GET() {
      return new Response(await renderToString(SignInModal()))
    }

Because the HTMX wants to work with strings as HTML then we need to return a string component and react-dom/server does it the best.
So I used a GET request from the NextJS App to render the object.

NextJS with HTMX?!

yup!
HTMX and NextJS aren’t completely different paradigms.
So I can use them together.
I had to cheat though because NextJS doesn’t like react-dom/server.

    // util/renderToString
    type renderToStringReact = typeof import("react-dom/server").renderToString
    let _renderToString: renderToStringReact;

    export const renderToString = async (element: Parameters<renderToStringReact>[0]) => {
      if (!_renderToString) {
        _renderToString = (await import('react-dom/server')).renderToString
      }
      return _renderToString(element)
    }

A dynamic import with a singleton did the trick.

What is the Conclusion?

I don’t know… Have fun with libraries and frameworks.

Top comments (2)

Collapse
 
schemetastic profile image
Schemetastic (Rodrigo)

I have heard of HTMX and so far seems fun and cool for small to medium size apps.

I personally like SvelteKit, has made my life so much easier.

Collapse
 
acecodept profile image
Ace-Code

I can respect that.