SpeechSynthesisUtterance is not defined Error in NextJS

I'm trying to get the 'SpeechSynthesis to speak 'Hello world' but it gives me an error. SpeechSynthesisUtterance is not defined. When I first try it it works but when I restart the server with 'npm run dev' it gives the error.

Is there a way I can fix this?

Here's the code:

export default function Main() {
  let text = new SpeechSynthesisUtterance("Hello world!");

  return <button onClick={SpeechSynthesis.speak(text)}>Click me</button>;
}

Thanks in advance:)

Upvotes: 0

Views: 940

Answers (1)

Paracide
Paracide

Reputation: 21

The window and SpeechSynthesisUtterance can not be accessed in server side, so move them to client-side rendering, like this:

<button
  onClick={() => {
    window.speechSynthesis.speak(new SpeechSynthesisUtterance("Hello world!"))
  }}
>
  Click me
</button>

Upvotes: 0

Related Questions