Search code examples
node.jsazurepeerjs

PeerJS Server 404 on Azure


I'm trying to deploy a PeerJS server on Azure. On my kudu console, running

node peerjs --port 9000

returns

Started PeerServer on ::, port: 9000, path: / (v. 0.2.8)

However, when I try to connect to the server from my client code, I get a 404. Going directly to appname.azurewebsites.net/peerjs/id in my browser also returns a 404.

I see inside their package.json file, they run

bin/peerjs --port ${PORT:=9000}

instead of just passing in 9000 directly; I assume this is an environment variable. However, trying to run this on Azure gives

Error: Error: listen EACCES ${PORT:=9000}

which I assume means Azure doesn't recognize ${PORT:=9000} as a valid port.

I know for a fact there's nothing wrong with my client side code because a) I copied it directly from PeerJS's website, and b) everything works correctly when I deployed PeerJS to Heroku. It's only not running on Azure.

Other things I've tried: I edited peerjs in the bin folder to use process.env.PORT instead of what's passed in via the command line, but that didn't work, giving the same EACCES error. When I tried to console.log(process.env.PORT), I got undefined. None of my Google searches have turned up any solutions, although this person (Custom PeerJs Server giving ERR_CONNECTION_TIMED_OUT) seems to have a similar error, not on Azure.


Solution

    1. Azure App Service doesn't allow us to listen on a customer port. We need to use process.env.PORT instead. See Listen additional port Microsoft Azure Nodejs.

    2. Azure App Service (on Windows platform) runs on Microsoft IIS. So we need to put the app files to its virtual directory (D:\home\site\wwwroot) and no longer need to manually run the app via the Kudu console.

    In this case, you first need to install the library under app's root:

    npm install peer 
    

    And then create a file named index.js or app.js with following content and put it to /wwwroot folder:

    var PeerServer = require('peer').PeerServer;
    var server = PeerServer({port: process.env.PORT, path: '/'});
    

    As @Mikkel mentioned in a comment, PeerServer uses WebSocket protocol, so Web Sockets should be enabled in the Azure portal like this:

    enter image description here

    You also need to check out this post to add a web.config file for your app if it has not been created yet.