Does not exist on type 'false | HTMLAudioElement'
NextJS uses Node to render anything in the server that allows you to build static and server side rendered apps. Therefore, any browser's APIs such as window
or in your case Audio
, do not exist in Node.
When Next tries to run the following code on node, and since Audio
does not exist. It will evaluate to false
since typeof Audio
is undefined
.
const audioRef = useRef(typeof Audio !== 'undefined' && new Audio(mp3Src));
To ensure the code is run only on browsers (not Node), you can use the useEffect
hook.
e.g.
const AudioPlayer: NextPage<Props> = ({ imgSrc, mp3Src }) => {
// const audioRef = useRef(new Audio(mp3Src));
const [audioElem, setAudioElem] = useState<HTMLAudioElement>();
useEffect(() => {
if (typeof Audio !== 'undefined' && mp3Src) {
const audio = new Audio(mp3Src);
setAudioElem(audio);
}
}, [mp3Src])
// const duration = audioRef.current.duration;
const { duration } = audioElem || {};
...
Some helpful links;
- https://dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97
- https://frontend-digest.com/why-is-window-not-defined-in-nextjs-44daf7b4604e