7 min read
Original source

A video chat with WebRTC and React

Let’s say two people want to video chat using our app. One solution would be for the first person to stream their camera feed to our server. Then, our…

Let’s say two people want to video chat using our app. One solution would be for the first person to stream their camera feed to our server. Then, our application would pass this data to the other caller. Unfortunately, our application acting as a middleman could introduce a significant lag, especially if our server is far from the call participants. Fortunately, we can use WebRTC to connect our users directly without sending all of the data through our server. This improves performance and helps us achieve a smooth experience. Even if the video and audio are not streamed through our application, we still need to build a server to allow the users to establish a connection with each other. In this article, we create a NestJS application to connect our users. Besides that, we also create a frontend app using React that manages and displays the video stream. For the code of our backend application, check out this repository. If you want to take a look at the frontend code, open this repository. Capturing the camera In this article, we gradually build both the frontend and backend applications. For the frontend part, we use Vite. If you want to know more about Vite, check out React with Vite and TypeScript and its common challenges Let’s start by capturing a stream from the local camera. To do that, we need to use the mediaDevices object. useLocalCameraStream.tsx import { useEffect, useState } from 'react'; export function useLocalCameraStream() { const [localStream, setLocalStream] = useState<MediaStream | null>(null); useEffect(() => { navigator.mediaDevices .getUserMedia({ video: true, audio: true }) .then((stream) => { setLocalStream(stream); }); }, []); return { localStream, }; }To display it, we need to use the

A video chat with WebRTC and React | NestJS.io