morganney / tts-react

Convert text to speech using React.
https://morganney.github.io/tts-react/
MIT License
46 stars 7 forks source link

ReferenceError when using with SSR #83

Open szamanr opened 1 month ago

szamanr commented 1 month ago

problem

when using with SSR, e.g. with a framework like Next.js, the code is rendered twice: first on the server, then on the client. you can use the "use client"; directive to mark a file as client-only, but it will still be rendered on the server for DOM comparison (as far as i understand, could be wrong on this point).

when the hook is called, it internally makes a reference to window, which is not available on the server, and therefore throws a server error: ReferenceError: window is not defined.

a solution would be to check if typeof window === "undefined" before making the window calls, and in such case, abort the call.

reproduction

"use client";

const Component = () => {
  const { play } = useTts({
    children: <p>Hello, world!</p>,
  });

  return (
    <p>a sample client component</p>
  );
}
morganney commented 1 month ago

@szamanr thanks for reporting this and opening a PR. Let me look into this a bit after work and see if I can reproduce it myself for a better understanding, or if you already had a minimal reproducible example that would be great.