Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a resource on the client side only in Nuxt.js

I'm trying to build an app using Tone.js on top of Nuxt.js. Tone.js requires the browser's Web Audio API and as Nuxt renders stuff on the server side my build keeps failing.

Nuxt addresses this in the plugin documentation and I've followed that approach in my nuxt.config.js file writing:

module.exports = {
  plugins: [{src: '~node_modules/tone/build/Tone.js', ssr: false }],
}

however that results in this error: [nuxt] Error while initializing app TypeError: Cannot read property 'isUndef' of undefined. Looking at Tone's source I'm pretty sure this is because I'm getting it because the code is still being executed on the server side.

I've seen solutions putting the js file into the static folder and checking process.browser but both result in Tone being undefined.

My question seems to be the same as this one if it's helpful additional context

like image 267
isdn Avatar asked Dec 05 '25 03:12

isdn


1 Answers

Instead of import a plugin, in your page.vue you can init Tone.js in the mounted() method, because this function is run only from client-side.

Example of page/test.vue file:

<template>
  <div>
    Tone.js
  </div>
</template>

<script>
  export default {
    mounted() {
      var Tone = require("Tone");
      var synth = new Tone.Synth().toMaster();
      synth.triggerAttackRelease("C4", "8n");
    }
  }
</script>
like image 138
Nicolas Pennec Avatar answered Dec 07 '25 19:12

Nicolas Pennec