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