Coming from a React environment, it was natural for me to write a page view tracker as below:
But this doesn’t work in Next.js. If you test it out, you would either get:
which is clear enough, or you might encounter:
This happens because you’re calling trackView
server action and the signal is aborted. It seems this issue arises due to Next.js hydration. Even though the component is set to be a client component, hydration renders it during the server pre-render.
Hydration in Next.js refers to the process where the server-rendered HTML is made interactive on the client side. Essentially, the HTML generated by Next.js during the server-side rendering (SSR) phase becomes a static page that is then "re-animated" or hydrated into a fully interactive app once the JavaScript loads and runs in the browser.
Hydration offers several advantages:
While hydration is beneficial, it comes with its own set of challenges:
window
object, leading to errors if your code tries to access it. This is because window
is a browser-specific global object that is unavailable in the Node.js environment where the server-side code runs.To address these hydration issues, you can make several adjustments. A fast solution you can adapt involves using Next.js hooks effectively:
Also, by removing document.referrer
from the dependencies array, I prevent unnecessary potential hydration issues. This ensures that useEffect
only triggers when the pathname changes, avoiding the issues caused by the initial hydration process. Next.js ensures that everything inside useEffect
will run on client-side only but it’s not the same case with hook dependancies so during hydration you might get an error saying that document
is not defined.
Hydration is a powerful feature of Next.js that bridges the gap between server-rendered and client-rendered applications. While it brings many benefits, it also requires careful handling of client-side code.
In summary, when working with Next.js:
window
and document
usage.Till next time!