Deploy a Unity Webgl Build to a Local Server

Created on: 05 Apr 22 23:54 +0700 by Son Nguyen Hoang in English

Several methods to test your webgl build on your local server

Thumbnail 1

Some colleagues of mine, who, despite of their degrees, don’t know how to deploy a WebGL build to a local server. Thus, I suggested he use a small add-on on Google Chrome. However, as a programmer myself, I quite dislike this solution (it is not nerdy, requires no programming and sometimes the add-on is lagged or broken). Furthermore, it turns out that there is not so many topics and tutorial about this on the internet. Hence, I made this post to list all solutions I knew that work for me to deploy WebGL Game to the local server. Hopefully, this will help some game developers in the future.

To illustrate the procedure, this blog post comes with a link to my Git Repository that contains a simple Unity build. You can run the script to deploy that game to your local server if you will. Next, it is well noted that to run the WebGL Build on the local server, the compression mode in the publishing setting is set to “uncompressed”. This is suggested to work best for testing but not recommended in actual production. If you want to deploy a WebGL with a compression method, such as “Brotli”, the problem is that it will cause an error and force you to make the connection to be “HTTPS”, not “HTTP”. Using “HTTPS” on local ends is another topic that I will not cover in this post.

Game demo

O. Let Unity did it

Yes, laugh at my face as you wish but it appears that Unity only launch this test server onced! This means that you cannot rerun the game on local after you shutdown the computer! Furthermore, I don’t find any method to manually restart the server from Unity. So, this method is never enough!

A. The simplest solution: Web Server for Chrome

At the time of writing, this addon proves to be very efficient and because it is a Chrome extension, no code and very minimum setup are required. What you need is … well, Chrome. Go to the marketplace and search for the addon named “Web Server for Chrome”.

Run the app from Chrome. A new window will pop up and allow you to choose the folder where the Build folder is. Choose the folder, select the port then toggle the switch to start the server. That’s it. Visit the localhost (127.0.0.1) with your port number that the Unity game is ready for you. Addon

Now, you can wonder why the heck I did not attach any actual image of the addon to this section. The answer is that this addon DOES NOT work in my current browser (BRAVE). Is this a bug in my devices or this also happens to other Brave’ users? I can never know! But in the past, I tried this method and it was success on Chrome Browser so 99% it will work for you too!

B. Python-based solution

To do this you must have python (python3 or python2.7) installed on your devices first.

1. Using built-in “http.server” from the command line

This is deadly simple, go to the directory where the build file is located then run the command line.

python -m http.server // no specified directory
python -m http.server -d simple-webgl-build

This command also allows you to customize the path to your Build directory.

2. But … wait a minute, using built-in module is not nerdy enough!

You can always do it the hard way though. Modify the path to the build directory then run the program.

import http.server
import socketserver

PORT = 3000
DIRECTORY = "../simple-webgl-build"

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)


with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever(poll_interval=2)

Then run the script using Python

python main.py

C. Node-based solution

Like the Python-based counterpart, to do this way you must have NodeJS preinstalled on your local first. From this point, I can give you another three solutions:

1. The quickest method: Run Serve Module from Global

This is again, deadly simple. First, install serve module as a global package using npm.

npm install -g serve

Then run serve from the WebGL build directory

serve

This should be enough now, however, if you are on Windows, you may encounter the bug related to permissions as the system prevents the script from being executed

serve : File C:\Users\sonng\AppData\Roaming\npm\serve.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ serve
+ ~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

This is again, outside of the scope of this post so I will not go further more. However, you can always solve the problem by installing and running the package locally!

2. But … install something global is SUCK. Then make it local instead!

To do this you should create a new folder that will contain the script. This also implies that all setup prerequisites had been done (e.g npm initialization is made and needed packages were installed by npm install). In addition, an index.js file should be created to run the script through Node.

First step: Install the “serve” module locally:

npm i serve

Then save the below code to the index.js file. Note that you may want to modify the path to the WebGL build folder.

//index.js

const handler = require('serve-handler');
const http = require('http');

const server = http.createServer((request, response) => {
  let param = {
    public : "../simple-webgl-build/"
  }
  return handler(request, response, param);
})

server.listen(3001, () => {
  console.log('Running at http://localhost:3001');
});

Then run NodeJS on the index.js file. Tadaa, your game has been deployed!

node index.js
3. Use expressjs to serve the server ?

Similar to the #2 solution but use expressjs instead. You follow almost the same procedure as #2 but the index.js file must be changed to fit with the express framework’s api. Also, don’t forget to install expressjs into your node_modules as usual.

//index.js
const express = require('express')
const app = express()
const port = 3000

app.use(express.static('../simple-webgl-build'))
app.get('/', (req, res) => {
  res.sendFile('../simple-webgl-build/index.html')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Then again, run node

node index.js

That’s it for the post. All of the code has been published and open for public on my Github. Visit the below link to check the code.

https://github.com/sonnguyen9800/unity-webgl-deploy-sample

Reference The image used in the thumnail belongs to Unsplash (https://unsplash.com/)

Back To Top