How to Use TURN Server with Node WebRTC Library
Tags: webrtc, node, webdev, javascript
Published: 2024-04-14 21:33:42

In this article we are going to learn how to use TURN server with Node.Js WebRTC library

Here is what we are going to learn in this article:

* Explanation of what are TURN servers and why they critical for overcoming NAT and firewall traversal issues in WebRTC.
    
* Choosing a TURN server, options and considerations
    
* Overview of [Metered.ca](http://Metered.ca) services and benefits scalability, reliability, easy integration.
    
* Setting Up TURN Server for Your Application
    
* Step-by-step guide on registering and setting up a TURN server with [Metered.ca](http://Metered.ca).
    
* Understanding the [Metered.ca](http://Metered.ca) dashboard and key configuration options.
    
* Detailed explanation of the Node-WebRTC library and its application.
    
* Code examples showing how to integrate [Metered.ca](http://Metered.ca)'s TURN server details into a Node.js application using the WebRTC library.
    
* Authenticating and establishing connections through the TURN server.
    
* Tools and methods to test TURN server functionality in your WebRTC app.
    
* Troubleshooting common issues and how to resolve them.
    

## Explanation of what are TURN servers and why they critical for overcoming NAT and firewall traversal issues in WebRTC.

TURN servers are an important part of the webrtc ecosystem. To understand why TURN servers are critical for WebRTC communications we need to delve in to the concepts of NAT, firewalls and basics of how WebRTC works

### Understanding NAT and Firewalls

NAT is a method using which NAT devices such as routers translates the private internal IP address of devices that are behind the router to public IP address and send the traffic to the internet

This enables multiples devices that are behind a NAT to use a single public IP for all the devices that are behind the NAT

The NAT creates a problem for p2p communication because the devices cannot know the real IP addresses of each other. So, that they can cannot to each other

Firewalls, on the other hand block unauthorized access to and from private networks. The firewalls rules thus prevent connections between devices such as those established by webrtc communications

### Role of TURN servers in WebRTC

TURN servers relay data between devices that are behind different NAT or cannot connect due to firewall restrictions.

1. **Connection Attempt:**WebRTC first tries to establish a direct connection using STUN. If the webrtc fails, due to NAT restrictions or firewall rules then it tries to establish connection using the TURN server
    
2. **Relaying traffic:** The TURN server receives the traffic from one client and relays it to the other client. Acting as an intemediary. All the traffic that passes through TURN server is fully and end to end encrypted.
    
3. **Overcoming NAT and Firewall:** By relaying traffic TURN servers ensure that communication can happen through NAT scenarios and strict firewall rules
    

## Choosing a TURN server, options and considerations

When choosing a TURN server service, you should keep in mind some criteria. Here are some of the relevant things that you should consider

* Compatibility and Standards Compliant: The TURN server should be compliant with the relevant RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928, ensuring broad compatibility with NAT traversal scenarios that is over the UDP, TCP, TLS and DTLS.
    
* Global coverage and Latency: To reduce latency and enable smooth working of TURN servers you should choose a provider that has auto geo targeting and servers all around the world
    
* Scalability and reliability: The TURN server must be scalable and reliable, so that it can expand with the needs of your corporation, and it is a important part of your critical infrastructure
    
* Cost Effectiveness: TURN servers must be cost effective as well and flexible with regards to costs as well. Things like pay as you go model and volume discounts are features that are required
    
* Security: TURN server data transfer must be end to end encrypted
    
* Ease of Administration: It is important that there is easy of administration when using TURN servers
    
    

## Overview of [Metered.ca](http://Metered.ca) services and benefits (scalability, reliability, easy integration).


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wh55xr9fukn31nlk94i0.png)

## [Metered TURN servers](https://www.metered.ca/stun-turn)

1. [**API:** TURN server](https://www.metered.ca/stun-turn) management with powerful API. You can do things like Add/ Remove credentials via the API, Retrieve Per User / Credentials and User metrics via the API, Enable/ Disable credentials via the API, Retrive Usage data by date via the API.
    
2. **Global Geo-Location targeting:** Automatically directs traffic to the nearest servers, for lowest possible latency and highest quality performance. less than 50 ms latency anywhere around the world
    
3. **Servers in 12 Regions of the world:** Toronto, Miami, San Francisco, Amsterdam, London, Frankfurt, Bangalore, Singapore,Sydney, Seoul
    
4. **Low Latency:** less than 50 ms latency, anywhere across the world.
    
5. **Cost-Effective:** pay-as-you-go pricing with bandwidth and volume discounts available.
    
6. **Easy Administration:** Get usage logs, emails when accounts reach threshold limits, billing records and email and phone support.
    
7. **Standards Compliant:** Conforms to RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928 over UDP, TCP, TLS, and DTLS.
    
8. **Multi‑Tenancy:** Create multiple credentials and separate the usage by customer, or different apps. Get Usage logs, billing records and threshold alerts.
    
9. **Enterprise Reliability:** 99.999% Uptime with SLA.
    
10. **Enterprise Scale:** With no limit on concurrent traffic or total traffic. Metered TURN Servers provide Enterprise Scalability
    
11. Runs on port 80 and 443
    
12. Support TURNS + SSL to allow connections through deep packet inspection firewalls.
    
14. Support STUN
    
15. Supports both TCP and UDP
    

## Step by Step Guide to adding Metered TURN servers in your Node-WebRTC project

### Step 1 : Setting up the project and installing dependencies

set up the project using the below code

```bash
npm init -y
```

then cd into the directory and install the dependency like so

```bash
npm install wrtc
```

### Step 2: Integrating Metered TURN servers with Node WebRTC

### Method A : Using ICE Server Array

Now configure the WebRTC to use the Metered TURN server

for this you will need the turn server urls, username and password. you can get the following creds

1. By going to metered.ca/stun-turn and creating an account
    
2. then logging in to the dashboard and creating a credential
    
3. click on the instructions button to get the ICE server Array
    


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46if0ipjluu84okooenv.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nehfgjzy1jnxu70n8txz.png)




you will need this array and credential to add to your webrtc library code

```bash
const { RTCPeerConnection } = require('wrtc');

// Replace these values with your Metered.ca TURN server details
const turnServerConfig = {
  urls: 'turn:your-turn-server.metered.ca:3478', // Example TURN server URL
  username: 'your-username', // Your TURN server username
  credential: 'your-password' // Your TURN server password
};

// Creating a new RTCPeerConnection with the TURN server configuration
const peerConnection = new RTCPeerConnection({
  iceServers: [turnServerConfig]
});

// Handling ICE candidate event
peerConnection.onicecandidate = event => {
  if (event.candidate) {
    console.log('New ICE candidate:', event.candidate);
  }
};

// Example: Sending a simple data channel message
const dataChannel = peerConnection.createDataChannel("sampleChannel");
dataChannel.onopen = () => dataChannel.send('Hello via WebRTC data channel!');

// Example: Setting up a simple offer-answer exchange
// This would typically be done via a signaling server
peerConnection.createOffer()
  .then(offer => peerConnection.setLocalDescription(offer))
  .then(() => {
    // Here, you would typically send the offer to the remote peer via your signaling mechanism
    console.log('Offer created and set as local description');
  })
  .catch(console.error);

// Note: Completing the connection establishment would require signaling to exchange offers/answers and ICE candidates between peers.
```

### Method B: Using Metered TURN Server APIs

Let us look into the second method of integrating the Metered TURN servers in your node webrtc application

first as before you need to install the node webrtc library into your application like so

```bash
npm install wrtc
```

next you will also need to install the node-fetch library to make HTTP requests to the metered api. You can also use the axios library to do this

```bash
npm install node-fetch
```

### step 2 Fetch TURN credentials from Metered.ca

Before using the TURN api credentials from metered, you have to replace the `<appname>` with your application name and `Your_secretKey` with your secret key that you get in your metered account

```javascript
const fetch = require('node-fetch');

async function fetchTurnCredentials() {
  const apiUrl = 'https://<appname>.metered.live/api/v1/turn/credential?secretKey=<YOUR_SECRET_KEY>';
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "expiryInSeconds": 3600, // Credential expiry time
        "label": "exampleLabel"  // Optional label for the credential
      }),
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch TURN credentials: ${response.statusText}`);
    }

    const data = await response.json();
    return {
      urls: `turn:<appname>.metered.live:3478`, // Use the appropriate TURN server URL
      username: data.username,
      credential: data.password
    };
  } catch (error) {
    console.error("Error fetching TURN credentials:", error);
    return null;
  }
}
```

### Step 3 : Establishing the WebRTC connection with the Fetched credentials

when you have the TURN server credentials the next thing that you have to do is to establish the webrtc connection, using the node-webrtc library

```javascript
const { RTCPeerConnection } = require('wrtc');

async function setupWebRtcConnection() {
  const turnCredentials = await fetchTurnCredentials();
  if (!turnCredentials) {
    console.log("Could not obtain TURN credentials.");
    return;
  }

  const peerConnection = new RTCPeerConnection({
    iceServers: [turnCredentials]
  });

  // Handling ICE candidates
  peerConnection.onicecandidate = event => {
    if (event.candidate) {
      console.log('New ICE candidate:', event.candidate);
    }
  };

  // Other WebRTC setup like creating data channels or handling media streams goes here
  
  // Example: Creating a data channel
  const dataChannel = peerConnection.createDataChannel("sampleChannel");
  dataChannel.onopen = () => dataChannel.send('Hello via WebRTC data channel!');
  
  // Signaling code to exchange offer/answer and complete the connection setup would go here
}

setupWebRtcConnection().catch(console.error);
```

## Creating a complete video calling application with Metered TURN servers and Node WebRTC library

## Testing the TURN server connection

you can test the turn server is working or not by going to the turn server test website

[https://www.metered.ca/turn-server-testing](https://www.metered.ca/turn-server-testing)

there you can put in your credentials and press the "Add Server" button to add the server

you can add multiple servers from the ice servers including stun and turn servers. Then click on the "Launch Server Test" button to test the TURN servers


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mx24w3yadvm6bdp1l6tf.png)



## Conclusion

Now you have integrated the TURN server in your webrtc application using the Metered TURN servers and Node webrtc library