Developing websockets locally with ngrok, Node and Relay

If you’re new to websockets, fret not — we’ll be starting with the basics. First off, why websockets? Most modern applications need a way to continuously update information back and forth between the client and user. While there are technologies that enable this on top of HTTP (like Ajax), websockets provides two way connection with an event bus that lets you send and receive events between a client and server with minimal latency.

We’ll use the Relay SDK to develop a simple app that reports the time, its name and location when you speak the phrase ‘status’ into a Relay device.

We’ll also use the Relay Samples repo & ngrok so go ahead and pull them into your dev environment (I’m using os x below, see instructions for node and ngrok on other platforms)

$ brew install node
$ git clone git@github.com:relaypro/relay-samples.git
$ cd relay-samples
$ npm install @relaypro/sdk
$ node index.js

Now, you should have a locally running websocket server running on port 8080 (under the covers, Relay uses the ws npm package):

Relay SDK WebSocket Server listening => 8080

Next, let’s get ngrok running and pointed to our websocket running on port 8080. Don’t worry about the http URIs, you can run websockets over them. In a separate terminal window, run:

$ ngrok http 8080https://3109c87c2297.ngrok.io -> http://localhost:8080

You should see a couple of URLs ending with ngrok.io. These are public addresses that you can use to connect your locally running node Relay websocket workflows with Relay servers. For now, let’s test it by running wscat in a separate terminal window:

$ npm install -g wscat
$ wscat -c wss://3109c87c2297.ngrok.io/deviceinfo
Connected (press CTRL+C to quit)

Nice! We’re using the deviceinfo sample code for this example. You should also see some corresponding events in your terminal window where your Relay workflow is running (go ahead and hit CTRL+C to terminate):

WebSocket request => /deviceinfo
creating event adapter
Workflow connection => deviceinfo-c0b1d92a185ffc9981fa0e9346094143

Ok great, we have one last step to register your Relay device with your newly created workflow. You’ll need to install the Relay CLI and grab the Relay device ID from the console.

$ npm install -g @relaypro/cli
$ relay login
$ relay workflow:create --type=phrase --phrase=status --uri=wss://3109c87c2297.ngrok.io/deviceinfo --name deviceinfo 99000756000XXXX

Next, grab your Relay device and try it out! Make sure you are on the Relay assistant channel (or press and hold the channel button on the side to access the assistant) and speak ‘status’ into your Relay:

Engineer & Entrepreneur connecting people with the power of voice at Relay (relaypro.com)