3

Hi I am declaring an audio context like this and it says window in undefined. I tried declaring declare const window :any above window.Context but the error's still there. Anyone know how I can solve this?

window.AudioContext = window.AudioContext || (window as any).webkitAudioContext

export default function TestPage(){

   const audioContext = new AudioContext();

   return <>Hello</>
}
  • Does this answer your question? [Window is not defined in Next.js React app](https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app) – juliomalves Feb 02 '22 at 07:57

2 Answers2

1

next.js runs server side. window is only available on client side. So you will have to wait until component is mounted, like this:



export default function TestPage(){

   const audioContext = useState(null);
   useEffect(() => {
window.AudioContext = window.AudioContext || (window as any).webkitAudioContext;
audioContext.current = new AudioContext();

   },[]);


   return <>Hello</>
}

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
1

It's because of the server side rendering, so when nextjs is being rendered on the server the window doesn't exist yet, because window is only on the client.

What I usually do is to have some sort of function that is triggered in the client to initialize window:

(I assume that you're using reactjs because of the component format and fragment on the snippet)

export default function TestPage() {
   const [audioContext, setAudioContext] = useState<AudioContext | null>(null)
   useEffect(() => {
    if (typeof window !== 'undefined') {
      const val = window.AudioContext = window.AudioContext || window.webkitAudioContext;
      setAudioContext(val)
      // or you can put your logic here without setting the state
    }

   }, [])

   useCallback(() => {
     if (audioContext !== null) {  
       const audioContext = new audioContext();
       // your other logic for audio context
     }

   }, [audioContext ])

   return <>Hello</>
}
I am L
  • 4,288
  • 6
  • 32
  • 49