How to host a compressed Unity WebGL game on Netlify

Published on

Last Updated on

Estimated Reading Time: 2 min


When you deploy a WebGL build for a Unity game, you can define the compression format to Brotli(or gzip).

If you deploy this compressed unity game to Netlify and try to run it, you will see an error similar to

Unable to parse XYZ.br! This can happen if build compression was enabled but web server hosting the content was misconfigured to not serve the file with HTTP Response Header "Content-Encoding: br" present. Check browser Console and Devtools Network tab to debug.

Solution 1

One option is to enable the Decompression fallback option which embeds a Javascript decompressor into your build.

You can find this in the Project Settings -> Player -> Publishing Settings (for WebGL)

Although a perfectly valid option, it results in a larger loader size and is less efficient (according to the docs).

So, let's look at a better solution.

Solution 2

To ensure that the browser can run the game, you need to tell the browser to decompress the files with the .br extension using the Brotli algorithm.

If you look at the files generated by Unity in the Build folder, you will find the following files.

  • XYZ.data.br
  • XYZ.framework.js.br
  • XYZ.loader.js
  • XYZ.wasm.br

You need to set the Content-Encoding header for each file extension to br so that the browser knows how to decompress the files.

You can do this by creating a netlify.toml file at the root if you don't have one already and adding the following snippet to it.

[[headers]]
  for = ";/Build/*.data.br"
  [headers.values]
    Content-Encoding = ";br"
    Content-Type = ";application/octet-stream"

[[headers]]
  for = ";/Build/*.wasm.br"
  [headers.values]
    Content-Encoding = ";br"
    Content-Type = ";application/wasm"

[[headers]]
  for = ";/Build/*.js"
  [headers.values]
    Content-Encoding = ";js"
    Content-Type = ";application/javascript"

[[headers]]
  for = ";/Build/*.js.br"
  [headers.values]
    Content-Encoding = ";br"
    Content-Type = ";application/javascript"
  • for: The path where the headers will be added.
  • values: A map of values to add to the response headersa
    • Content-Encoding: The encoding that has been applied to the message paylaod.1
    • Content-Type: Indicates the original type of the resource.

This will set the correct content encoding for all the generated files.

Conclusion

By setting the appropriate headers in the netlify.toml file, we can serve a compressed Unity game on Netlify.

If you want to use gzip instead, you can follow the same steps by changing br to gz in the netlify.toml file.

References