Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I integrate a TURN server with a React application
    TURN server React application WebRTC Coturn Metered TURN Server TURN credentials RTCPeerConnection WebRTC integration


How do I integrate a TURN server with a React application


To integrate a TURN server with a React application, you need to follow these steps:

1. Setup the TURN Server:
- Install TURN Server: You can use a TURN server like Coturn or Metered TURN Server. For example, you can install Coturn using the following command:

bash
     npm install coturn
     

- Configure TURN Server: Configure the TURN server by setting up the necessary files and directories. For example, you can create a configuration file (`turnserver.conf`) with the following content:
bash
     # turnserver.conf
     listening = 0.0.0.0:3478
     relay = 0.0.0.0:3478
     # other settings...
     

- Start the TURN Server: Start the TURN server using the following command:
bash
     turnserver -c turnserver.conf
     

2. Integrate TURN Server with React Application:
- Install Required Libraries: Install the necessary libraries for WebRTC and TURN server integration. For example, you can install the `wrtc` library for WebRTC and `node-fetch` for making HTTP requests to the TURN server:

bash
     npm install wrtc node-fetch
     

- Fetch TURN Credentials: Fetch the TURN server credentials from the TURN server API. For example, you can use the `node-fetch` library to make a POST request to the TURN server API:
javascript
     const fetch = require('node-fetch');
     const apiUrl = 'https://<appname>.metered.live/api/v1/turn/credential?secretKey=<YOUR_SECRET_KEY>';
     async function fetchTurnCredentials() {
       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;
       }
     }
     

3. Establish WebRTC Connection:
- Create Peer Connection: Create an instance of the `RTCPeerConnection` class and set the TURN server credentials:

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: [
           {
             urls: turnCredentials.urls,
             username: turnCredentials.username,
             credential: turnCredentials.credential,
           },
         ],
       });
       // Other WebRTC setup like creating data channels or handling media streams goes here
     }
     

4. Test the TURN Server Connection:
- Test TURN Server: You can test the TURN server by going to the TURN server test website and adding your credentials. This will help you verify that the TURN server is working correctly.

Here is a complete example of integrating a TURN server with a React application:

javascript
import React, { useState, useEffect } from 'react';
import { RTCPeerConnection } from 'wrtc';
import fetch from 'node-fetch';

const App = () => {
  const [turnCredentials, setTurnCredentials] = useState(null);
  const [peerConnection, setPeerConnection] = useState(null);

  useEffect(() => {
    async function fetchTurnCredentials() {
      try {
        const apiUrl = 'https://<appname>.metered.live/api/v1/turn/credential?secretKey=<YOUR_SECRET_KEY>';
        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();
        setTurnCredentials({
          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);
      }
    }

    async function setupWebRtcConnection() {
      if (!turnCredentials) {
        return;
      }
      const peerConnection = new RTCPeerConnection({
        iceServers: [
          {
            urls: turnCredentials.urls,
            username: turnCredentials.username,
            credential: turnCredentials.credential,
          },
        ],
      });
      setPeerConnection(peerConnection);
    }

    fetchTurnCredentials();
    setupWebRtcConnection();
  }, []);

  return (
    <div>
      {peerConnection && (
        <button onClick={() => {
          // Handle peer connection events
        }}>
          Start WebRTC Connection
        </button>
      )}
    </div>
  );
};

export default App;

This example demonstrates how to fetch TURN server credentials and set up a WebRTC connection using the `wrtc` library. You can customize this example to fit your specific requirements and integrate it with your React application.

Citations:
[1] https://dev.to/alakkadshaw/what-is-a-turn-server-3ome
[2] https://groups.google.com/g/turn-server-project-rfc5766-turn-server/c/G0kae3T2ZVw
[3] https://www.videosdk.live/developer-hub/stun-turn-server/webrtc-turn-server
[4] https://dev.to/alakkadshaw/how-to-use-turn-server-with-nodejs-webrtc-library-2b4g
[5] https://www.dhiwise.com/post/mastering-real-time-communication-how-to-integrate-react-webrtc