How to fix "unsafe-eval" error with Vue3 for the client-side version?

Viewed 3912

I'm using Express, cors, and helmet for my app. Vue3 is used on the client-side only and the library file is self-hosted in the public folder. I simply do

<script type="module" src="/public/lib/vue.esm-browser.js"></script>

to add the module to the client-side. The problem is that when I use it, it keeps giving me an Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'". This problem started yesterday suddenly, when I started using the helmet and cors modules, and even if I comment out these modules, it still shows the error. What should I fix?

1 Answers

Yes, vue.js uses a piece of code like that:

  // detect possible CSP restriction
  try {
    new Function('return 1');
  } catch (e) {
    if (e.toString().match(/unsafe-eval|CSP/)) {
      warn$$1(
        'It seems you are using the standalone build of Vue.js in an ' +
        'environment with Content Security Policy that prohibits unsafe-eval. ' +
        'The template compiler cannot work in this environment. Consider ' +
        'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
        'templates into render functions.'
      );
    }
  }

Here you have 2 options:

  1. usage of precompiled templates, see discussion at github.

  2. using a vue.runtime.js runtime version instead of vue.js full version.

VueJS has 2 different versions: the full version and the runtime version. 'unsafe-eval' is only needed for the full version of VueJS; the runtime version doesn't need it. See details here.

The runtime-only build is fully CSP-compliant. When using the runtime-only build with Webpack + vue-loader or Browserify + vueify, your templates will be precompiled into render functions which work perfectly in CSP environments. See details in Vue CSP environments.

Related