'Next.js loadeddata event on <audio> not firing

I'm trying to figure out why the loadeddata/loadedmetadata event is not firing in my application. Actually, sometimes it does fire but it's inconsistent. I suspect there is some kind of race condition going on here but after a lot of trial and error and quite a lot of frustration, I'm out of ideas.

So, the idea is simple. I have an <audio> element and I want to run some logic when it is loaded.

This seems to work when I try it in a non-Nextjs React application. Example here

However, when I run the same thing in my Next.js React application locally I observe the aforementioned behaviour, so I suspect that this could be nextjs specific?

This can be minimally reproduced by:

  1. Running npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn-starter/tree/master/learn-starter"

  2. Replacing the existing index.js with:

export default function Home() {

  const handleMetadata = () => {
    alert("hi")
  }

  return (
    <div className="container">
      <main>
        <audio
          id="audio"
          onLoadedData={handleMetadata}
          onLoadedMetadata={handleMetadata}
          src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"
        />
      </main>
    </div>
  )
}

  1. Repeatedly refreshing the browser window


Solution 1:[1]

you should load the compoent which use audio with no ssr.like this:

import dynamic from 'next/dynamic'
const AudioPlayer = dynamic(import('../components/Home'), {
    ssr: false
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YAN7