Search code examples
reactjsrustnext.jselectrontauri

Window is undefined in NextJS + Tauri


Error Screenshot

What I'm trying to do:

I was using the appWindow from Tauri to access the appWindow.minimize(), appWindow.toggleMaximize(), and appWindow.close() to create a custom title bar.

What the code looks like:

import { appWindow } from "@tauri-apps/api/window";

const CustomTitleBar = () => {
  const hasLoaded = hasLoadedCSR(); // custom hook for checking if component has mounted using useEffect

  if (typeof window === "undefined") return <></>; // 1st attempt to disable SSR for this component
  if (!hasLoaded) return <></>; // 2nd attempt to disable SSR for this component
  return (
    <>
      <div data-tauri-drag-region className="titlebar">
        <button
          className="titlebar-button"
          id="titlebar-minimize"
          onClick={() => {
            console.log("Clicked");
            appWindow.minimize();
          }}
        >
          <img
            src="https://api.iconify.design/mdi:window-minimize.svg"
            alt="minimize"
          />
        </button>
        <button
          className="titlebar-button"
          id="titlebar-maximize"
          onClick={() => appWindow.toggleMaximize()}
        >
          <img
            src="https://api.iconify.design/mdi:window-maximize.svg"
            alt="maximize"
          />
        </button>
        <button className="titlebar-button" id="titlebar-close">
          <img
            src="https://api.iconify.design/mdi:close.svg"
            alt="close"
            onClick={() => appWindow.close()}
          />
        </button>
      </div>
    </>
  );
};

export default CustomTitleBar;

I basically did 2 attempts to solve the problem because I definitely think this is caused by SSR as mentioned by FabianLars in a similar question.


Solution

  • To fix the problem, I basically created another component using the dynamic function to force CSR for CustomTitleBar.

    import dynamic from "next/dynamic";
    
    const DynamicCustomTitleBar = dynamic(() => import("./CustomTitleBar"), {
      ssr: false,
    });
    
    export default DynamicCustomTitleBar;