End of Life for Twilio Programmable Video - Upgrade to VideoSDKLearn More

How to Setup and Use ngrok with Websockets?

Learn how to set up and use ngrok with websockets for seamless real-time communication in your development environment.

Introduction to ngrok Websocket

In today's rapidly evolving tech landscape, seamless communication between servers and clients is crucial. One of the key technologies enabling real-time interaction is websockets. Websockets allow for two-way communication over a single, persistent connection, making them ideal for applications like chat systems, live notifications, and online gaming.
Enter ngrok—a tool that has revolutionized the way developers expose local servers to the internet. By creating secure tunnels, ngrok simplifies the development process, especially when dealing with webhook integrations and testing APIs. When combined with websockets, ngrok becomes an indispensable tool for developers looking to streamline their workflow and enhance real-time capabilities.
This article dives deep into using ngrok with websockets, offering a step-by-step guide to get you started, practical code snippets, and answers to frequently asked questions. Whether you are a seasoned developer or a newcomer, this guide aims to provide the knowledge you need to effectively leverage ngrok for websocket development.

Getting Started with ngrok and Websockets

Before diving into the specifics of configuring and running ngrok with websockets, let's cover the essential steps for getting started.

Prerequisites and Installation

To begin, ensure you have the following prerequisites:
  • A working local development environment
  • Administrator access to your machine (for installing software)
  • Basic understanding of command-line operations
Follow these steps to install ngrok:
  1. Download ngrok: Visit the

    ngrok website

    and download the appropriate version for your operating system.
  2. Install ngrok: Unzip the downloaded file and place the ngrok executable in a directory included in your system's PATH.

Initial Configuration of ngrok

After installing ngrok, you'll need to create an account on the ngrok website to get an authentication token. This token allows you to use ngrok without restrictions.
  1. Sign Up: Go to the

    ngrok sign-up page

    and create an account.
  2. Get Your Auth Token: Once logged in, navigate to the

    auth token page

    and copy your unique token.
  3. Authenticate ngrok: Open your terminal and run the following command to authenticate ngrok with your token:

sh

1   ngrok authtoken <YOUR_AUTH_TOKEN>

Verifying the Installation

To ensure that ngrok is correctly installed and authenticated, run the following command:

sh

1ngrok version
You should see the version number and confirmation of your authentication status.

Step-by-Step Implementation Guide

Step 1: Installing ngrok

To use ngrok with websockets, you need to install it as described above. Make sure that the ngrok command is accessible from your terminal.

Step 2: Configuring ngrok for Websockets

Configuration involves setting up ngrok to handle websocket traffic. Create a configuration file (ngrok.yml) with the following content:

YAML

1authtoken: <YOUR_AUTH_TOKEN>
2tunnels:
3  websocket:
4    proto: http
5    addr: 3000
6    bind_tls: true
This configuration specifies that ngrok should create a tunnel for HTTP traffic on port 3000, with TLS enabled.

Step 3: Running ngrok

Start ngrok using the configuration file:

sh

1ngrok start -config=ngrok.yml websocket
ngrok will start and provide you with a public URL that forwards to your local server on port 3000.

Step 4: Connecting Your Application

Integrate the provided ngrok URL into your application. For instance, if you are using a Node.js server, update the websocket server to listen on the ngrok URL.
Example Node.js code snippet:

JavaScript

1const WebSocket = require('ws');
2
3const ws = new WebSocket('wss://<YOUR_NGROK_SUBDOMAIN>.ngrok.io');
4
5ws.on('open', function open() {
6  console.log('connected');
7  ws.send(Date.now());
8});
9
10ws.on('close', function close() {
11  console.log('disconnected');
12});
13
14ws.on('message', function incoming(data) {
15  console.log(`Roundtrip time: ${Date.now() - data} ms`);
16  setTimeout(function timeout() {
17    ws.send(Date.now());
18  }, 500);
19});

Step 5: Testing the Connection

To verify the connectivity, run your local server and ensure it is listening on the specified port (e.g., 3000). Use the public URL provided by ngrok to establish a websocket connection. Check the logs to ensure data is being transmitted correctly.

Step 6: Advanced Configuration

For more advanced setups, you might want to use custom domains or subdomains with ngrok. This is useful for production environments or when you need a more professional appearance.

Custom Domains

Configure your DNS to point to ngrok’s servers and update your ngrok.yml file to include the custom domain:

YAML

1   tunnels:
2     websocket:
3       proto: http
4       addr: 3000
5       hostname: example.com
6       bind_tls: true

Security Considerations

Ensure that your application is secure by using HTTPS and implementing proper authentication and authorization mechanisms.

Get Free 10,000 Minutes Every Months

No credit card required to start.

Code Examples

Below are some practical examples of configuration and code snippets to help you get started with ngrok and websockets.

Configuration File (ngrok.yml)

YAML

1authtoken: <YOUR_AUTH_TOKEN>
2tunnels:
3  websocket:
4    proto: http
5    addr: 3000
6    bind_tls: true

Node.js WebSocket Client

JavaScript

1const WebSocket = require('ws');
2
3const ws = new WebSocket('wss://<YOUR_NGROK_SUBDOMAIN>.ngrok.io');
4
5ws.on('open', function open() {
6  console.log('connected');
7  ws.send(Date.now());
8});
9
10ws.on('close', function close() {
11  console.log('disconnected');
12});
13
14ws.on('message', function incoming(data) {
15  console.log(`Roundtrip time: ${Date.now() - data} ms`);
16  setTimeout(function timeout() {
17    ws.send(Date.now());
18  }, 500);
19});

Python WebSocket Client

Python

1import websocket
2import time
3
4def on_message(ws, message):
5    print(f"Received message: {message}")
6
7def on_error(ws, error):
8    print(f"Error: {error}")
9
10def on_close(ws):
11    print("Connection closed")
12
13def on_open(ws):
14    def run(*args):
15        for i in range(3):
16            time.sleep(1)
17            ws.send(f"Hello {i}")
18        time.sleep(1)
19        ws.close()
20    run()
21
22if __name__ == "__main__":
23    websocket.enableTrace(True)
24    ws = websocket.WebSocketApp("wss://<YOUR_NGROK_SUBDOMAIN>.ngrok.io",
25                                on_message=on_message,
26                                on_error=on_error,
27                                on_close=on_close)
28    ws.on_open = on_open
29    ws.run_forever()
These examples demonstrate how to set up a websocket client in both Node.js and Python, connecting to a server exposed through ngrok.

Conclusion

Using ngrok with websockets can significantly enhance your development workflow by providing a simple, secure, and effective way to expose your local servers to the internet. This combination is particularly useful for real-time applications requiring persistent and reliable connections. By following the steps outlined in this guide, you can set up and configure ngrok to work seamlessly with your websocket applications, enabling efficient testing and debugging processes. Explore the advanced features of ngrok to further optimize and secure your setups, ensuring a robust development environment.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ