In this article we'll set up the server for our phone app. The server file will look like a regular Express server file with one difference, the Peer server.
- First of all, create a file called
server.js
in the same location as the HTML and CSS files you created previously. This is the entry point of our app, as defined in ourpackage.json
file. - You'll need to start your code by requiring the peer server at the top of the
server.js
file, to ensure that we have access to the peer server:js
const { ExpressPeerServer } = require("peer");
- You then need to actually create the peer server. Add the following code below your previous line:
js
const peerServer = ExpressPeerServer(server, { proxied: true, debug: true, path: "/myapp", ssl: {}, });
ExpressPeerServer
object to create the peer server, passing it some options in the process. The peer server will handle the signalling required for WebRTC for us, so we don't have to worry about STUN/TURN servers or other protocols. - Finally, you'll need to tell your app to use the
peerServer
by callingapp.use(peerServer)
. Your finishedserver.js
should include the other necessary dependencies you'd include in a server file, as well as serving theindex.html
file to the root path. Updateserver.js
so that it looks like this:js
const express = require("express"); const http = require("http"); const path = require("path"); const app = express(); const server = http.createServer(app); const { ExpressPeerServer } = require("peer"); const port = process.env.PORT || "8000"; const peerServer = ExpressPeerServer(server, { proxied: true, debug: true, path: "/myapp", ssl: {}, }); app.use(peerServer); app.use(express.static(path.join(__dirname))); app.get("/", (request, response) => { response.sendFile(`${__dirname}/index.html`); }); server.listen(port); console.log(`Listening on: ${port}`);
- You should be able to connect to your app via
localhost
(in ourserver.js
we're using port 8000 (defined on line 7) but you may be using another port number). Runyarn start
(wherestart
refers to the script you declared inpackage.json
on the previous page) in your terminal. Visitlocalhost:8000
in your browser and you should see a page that looks like this:
If you want to learn more about Peer.js, check out the Peer.js Server repo on GitHub.