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</>
}
1

2 Answers 2

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</>
}

Sign up to request clarification or add additional context in comments.

Comments

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</>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.