TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'

Ricardo Machado picture Ricardo Machado · May 29, 2018 · Viewed 20.2k times · Source

I'm trying to load a .wasm file using the fetch api on Chrome , and serving a html file using express. But chrome does not let me load the file:

'Uncaught (in promise) TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.'

Here is my files:

/public/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script type="text/javascript">
          WebAssembly.instantiateStreaming(fetch('http://localhost:3000/simple.wasm'))
      .then(obj => {
       console.log(obj.instance.exports.add(1, 2));  // "3"
      });
    </script>
  </body>
</html>

Served by Express:

/index.js

const express = require('express')
express.static.mime.define({'application/wasm': ['wasm']})
var app = express();

app.use('/', express.static('public'));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Can i add a new mime type to express when serving a .wasm file? Or allow chrome to accept it? I dont have any idea for how to solve it ^^

See: http://kripken.github.io/emscripten-site/docs/compiling/WebAssembly.html

Web server setup
To serve wasm in the most efficient way over the network, make sure your web server has the proper MIME time for .wasm files, which is application/wasm. That will allow streaming compilation, where the browser can start to compile code as it downloads.

In Apache, you can do this with

AddType application/wasm .wasm
Also make sure that gzip is enabled:

AddOutputFilterByType DEFLATE application/wasm

Thank you everyone!

Answer

Lucio Paiva picture Lucio Paiva · Oct 10, 2018

One possible workaround is to use instantiate() instead of instantiateStreaming(), since the former doesn't care about MIME types (while the latter does). To use instantiate():

async function fetchAndInstantiate() {
    const response = await fetch("http://localhost:3000/simple.wasm");
    const buffer = await response.arrayBuffer();
    const obj = await WebAssembly.instantiate(buffer);
    console.log(obj.instance.exports.add(1, 2));  // "3"
}