ReactJS Vite SSR ReferenceError: window is not defined - react-slick library

617 Views Asked by At

When I run npm build using React Vite SSR plugin, I get the following error after the build:

/<path>/node_modules/enquire.js/src/MediaQueryDispatch.js:14
if(!window.matchMedia) {
^
ReferenceError: window is not defined
    at new MediaQueryDispatch (/<path>/node_modules/enquire.js/src/MediaQueryDispatch.js:14:5)
    at Object.<anonymous> (/<path>/node_modules/enquire.js/src/index.js:2:18)

I am sure it is coming from react-slick library because when I comment it out it works. How to fix this?

1

There are 1 best solutions below

0
Jolly Good On

I learned that the issue is some libraries such as react-slick, at the time of this writing, does not support server-side rendering (SSR). The library expects the window object to be available but this object does not exist in a server-side rendered environment.

So the solution is to import the library only on the client-side (when the window object becomes available). Doing the below worked for me:

 const [Slider, setSlider] = useState(null);

  useEffect(() => {
    if (typeof window !== "undefined") {
      import("react-slick")
        .then((module) => {
          setSlider(() => module.default);
        })
        .catch((error) => {
          console.error("An error occurred when loading react-slick", error);
        });
    }
  }, []);

Then make sure to use it after it is available like this:

{Slider ?  (<Slider ...> <div>..</div> </Slider>) : ("Loading ...")}

Additionally, adding noExternal to vite.config file helps in resolving libraries having invalid code:

  import { defineConfig } from "vite";
  import ssr from "vite-plugin-ssr/plugin";

  export default defineConfig({
   ...other configurations..,
   ssr: {
    noExternal: ["react-slick"],
   },

})