- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
- 122. API with NestJS #122. Many-to-many relationships with Kysely and PostgreSQL
- 123. API with NestJS #123. SQL transactions with Kysely
- 124. API with NestJS #124. Handling SQL constraints with Kysely
- 125. API with NestJS #125. Offset and keyset pagination with Kysely
- 126. API with NestJS #126. Improving the database performance with indexes and Kysely
- 127. API with NestJS #127. Arrays with PostgreSQL and Kysely
- 128. API with NestJS #128. Managing JSON data with PostgreSQL and Kysely
- 129. API with NestJS #129. Implementing soft deletes with SQL and Kysely
- 130. API with NestJS #130. Avoiding storing sensitive information in API logs
- 131. API with NestJS #131. Unit tests with PostgreSQL and Kysely
- 132. API with NestJS #132. Handling date and time in PostgreSQL with Kysely
- 133. API with NestJS #133. Introducing database normalization with PostgreSQL and Prisma
- 134. API with NestJS #134. Aggregating statistics with PostgreSQL and Prisma
- 135. API with NestJS #135. Referential actions and foreign keys in PostgreSQL with Prisma
- 136. API with NestJS #136. Raw SQL queries with Prisma and PostgreSQL range types
- 137. API with NestJS #137. Recursive relationships with Prisma and PostgreSQL
- 138. API with NestJS #138. Filtering records with Prisma
- 139. API with NestJS #139. Using UUID as primary keys with Prisma and PostgreSQL
- 140. API with NestJS #140. Using multiple PostgreSQL schemas with Prisma
- 141. API with NestJS #141. Getting distinct records with Prisma and PostgreSQL
- 142. API with NestJS #142. A video chat with WebRTC and React
- 143. API with NestJS #143. Optimizing queries with views using PostgreSQL and Kysely
- 144. API with NestJS #144. Creating CLI applications with the Nest Commander
- 145. API with NestJS #145. Securing applications with Helmet
- 146. API with NestJS #146. Polymorphic associations with PostgreSQL and Prisma
- 147. API with NestJS #147. The data types to store money with PostgreSQL and Prisma
- 148. API with NestJS #148. Understanding the injection scopes
- 149. API with NestJS #149. Introduction to the Drizzle ORM with PostgreSQL
- 150. API with NestJS #150. One-to-one relationships with the Drizzle ORM
- 151. API with NestJS #151. Implementing many-to-one relationships with Drizzle ORM
- 152. API with NestJS #152. SQL constraints with the Drizzle ORM
- 153. API with NestJS #153. SQL transactions with the Drizzle ORM
- 154. API with NestJS #154. Many-to-many relationships with Drizzle ORM and PostgreSQL
- 155. API with NestJS #155. Offset and keyset pagination with the Drizzle ORM
- 156. API with NestJS #156. Arrays with PostgreSQL and the Drizzle ORM
- 157. API with NestJS #157. Handling JSON data with PostgreSQL and the Drizzle ORM
- 158. API with NestJS #158. Soft deletes with the Drizzle ORM
- 159. API with NestJS #159. Date and time with PostgreSQL and the Drizzle ORM
- 160. API with NestJS #160. Using views with the Drizzle ORM and PostgreSQL
- 161. API with NestJS #161. Generated columns with the Drizzle ORM and PostgreSQL
- 162. API with NestJS #162. Identity columns with the Drizzle ORM and PostgreSQL
- 163. API with NestJS #163. Full-text search with the Drizzle ORM and PostgreSQL
- 164. API with NestJS #164. Improving the performance with indexes using Drizzle ORM
- 165. API with NestJS #165. Time intervals with the Drizzle ORM and PostgreSQL
- 166. API with NestJS #166. Logging with the Drizzle ORM
- 167. API with NestJS #167. Unit tests with the Drizzle ORM
- 168. API with NestJS #168. Integration tests with the Drizzle ORM
- 169. API with NestJS #169. Unique IDs with UUIDs using Drizzle ORM and PostgreSQL
- 170. API with NestJS #170. Polymorphic associations with PostgreSQL and Drizzle ORM
- 171. API with NestJS #171. Recursive relationships with Drizzle ORM and PostgreSQL
- 172. API with NestJS #172. Database normalization with Drizzle ORM and PostgreSQL
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 <video> element. Since we need to attach the media stream to its srcObject property, we must use a React reference.
VideoFeed.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { FunctionComponent } from 'react'; interface Props { mediaStream: MediaStream; isMuted?: boolean; } export const VideoFeed: FunctionComponent<Props> = ({ mediaStream, isMuted = false, }) => { return ( <video ref={(ref) => { if (ref) { ref.srcObject = mediaStream; } }} autoPlay={true} muted={isMuted} /> ); }; |
The last step is to combine our hook with the VideoFeed component.
App.tsx
1 2 3 4 5 6 7 8 9 10 11 12 |
import { useLocalCameraStream } from './useLocalCameraStream'; import { VideoFeed } from './VideoFeed'; export function App() { const { localStream } = useLocalCameraStream(); if (!localStream) { return null; } return <VideoFeed mediaStream={localStream} isMuted={true} />; } |
Creating video chat rooms
We want our users to be able to join a particular chat room and communicate in real time with the other person in the room. To do that, we need to use WebSockets.
If you want to know more about websockets, check out API with NestJS #26. Real-time chat with WebSockets
To use WebSockets in our NestJS application, we need to install a few additional libraries.
1 |
npm install @nestjs/websockets @nestjs/platform-socket.io |
In this article, we use Socket.IO, because it is the most popular implementation of WebSockets for NestJS.
Let’s start with allowing the users to join a chat room with a particular name. In this straightforward implementation, we only handle a maximum of two people at once in the room.
chat.gateway.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('join_room') async joinRoom( @MessageBody() roomName: string, @ConnectedSocket() socket: Socket, ) { const room = this.server.in(roomName); const roomSockets = await room.fetchSockets(); const numberOfPeopleInRoom = roomSockets.length; // a maximum of 2 people in a room if (numberOfPeopleInRoom > 1) { room.emit('too_many_people'); return; } socket.join(roomName); } } |
Thanks to the above code, the user joins a room with the provided name as soon as the frontend application emits the join_room message.
Dealing with Cross-Origin Resource Sharing
There is a solid chance that our frontend and backend applications are deployed to different origins. This can cause issues with Cross-Origin Resource Sharing when our frontend application tries to talk with the API.
If you want to know more about CORS, check out API with NestJS #117. CORS – Cross-Origin Resource Sharing
To deal with this, we need to define the URL of our frontend application on the backend side. A good way to do that is through environment variables.
.env
1 |
FRONTEND_URL=http://localhost:5173 |
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ChatModule } from './chat/chat.module'; import * as Joi from 'joi'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ChatModule, ConfigModule.forRoot({ validationSchema: Joi.object({ FRONTEND_URL: Joi.string().required(), }), }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} |
To be able to provide the frontend URL dynamically, we should extend the IoAdapter built into NestJS.
websocket-adapter.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { IoAdapter } from '@nestjs/platform-socket.io'; import { INestApplicationContext } from '@nestjs/common'; import { Server, ServerOptions } from 'socket.io'; import { CorsOptions } from 'cors'; export class WebsocketAdapter extends IoAdapter { constructor( appOrHttpServer: INestApplicationContext, private readonly corsOptions: CorsOptions, ) { super(appOrHttpServer); } create(port: number, options?: ServerOptions): Server { return super.create(port, { ...options, cors: this.corsOptions, }); } } |
We can now use it in our bootstrap function.
main.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ConfigService } from '@nestjs/config'; import { WebsocketAdapter } from './chat/websocket-adapter'; async function bootstrap() { const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); app.enableCors({ origin: configService.get('FRONTEND_URL'), }); app.useWebSocketAdapter( new WebsocketAdapter(app, { origin: configService.get('FRONTEND_URL'), }), ); await app.listen(3000); } bootstrap(); |
Joining a room
One way of letting the user join a particular room is through URL path parameters. For example, if the users enter the /video-chat-room/important-meeting URL, we assume that the room name is the important-meeting.
The React Router is the most straightforward way to achieve that with React.
1 |
npm install react-router-dom |
App.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { BrowserRouter, Route, Routes } from 'react-router-dom'; import { VideoChatRoom } from './VideoChatRoom'; import React from 'react'; import { useLocalCameraStream } from './useLocalCameraStream'; export const App = () => { const { localStream } = useLocalCameraStream(); return ( <BrowserRouter> <Routes> <Route path="video-chat-room/:roomName" element={localStream && <VideoChatRoom localStream={localStream} />} /> </Routes> </BrowserRouter> ); }; |
To connect to our API, we need its URL. The best way to store it is through environment variables.
.env
1 |
VITE_API_URL=http://localhost:3000 |
vite-env.d.ts
1 2 3 4 5 |
/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_API_URL: string; } |
We need to use the socket.io-client library to establish the WebSocket connection.
1 |
npm install socket.io-client |
socket.tsx
1 2 3 4 5 |
import { io } from 'socket.io-client'; export const socket = io(import.meta.env.VITE_API_URL, { autoConnect: false, }); |
We can now connect to our NestJS application and join a room.
useChatConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { useParams } from 'react-router-dom'; import { useCallback, useEffect } from 'react'; import { socket } from '../socket'; export function useChatConnection() { const { roomName } = useParams(); const handleConnection = useCallback(() => { socket.emit('join_room', roomName); }, [roomName]); useEffect(() => { socket.connect(); socket.on('connect', handleConnection); return () => { socket.off('connect', handleConnection); }; }, [roomName, handleConnection, roomName]); } |
Above, we emit the join_room event as soon as we connect to the WebSocket and provide the name of the chat based on the URL.
VideoChatRoom.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { VideoFeed } from './VideoFeed'; import { FunctionComponent } from 'react'; import { useChatConnection } from './useChatConnection'; interface Props { localStream: MediaStream; } export const VideoChatRoom: FunctionComponent<Props> = ({ localStream }) => { useChatConnection(); return <VideoFeed mediaStream={localStream} isMuted={true} />; }; |
Connecting the people in the room
Once we have precisely two people in our chat room, we want one of them to initiate a connection. To be able to do that, we need to let one of the people know that the other person is ready. To do that, we can emit the another_person_ready event.
chat.gateway.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('join_room') async joinRoom( @MessageBody() roomName: string, @ConnectedSocket() socket: Socket, ) { const room = this.server.in(roomName); const roomSockets = await room.fetchSockets(); const numberOfPeopleInRoom = roomSockets.length; // a maximum of 2 people in a room if (numberOfPeopleInRoom > 1) { room.emit('too_many_people'); return; } if (numberOfPeopleInRoom === 1) { room.emit('another_person_ready'); } socket.join(roomName); } } |
We need to start by creating an RTC Peer Connection. To do that, we need to provide the ICE server. In WebRTC, ICE is a framework used to facilitate the connection between the users. It helps us find the best path to connect two peers online. A part of the ICE framework is the STUN protocol used to discover the public address we need to establish the connection.
Fortunately, Google provides a public STUN server we can use.
usePeerConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { useMemo } from 'react'; export function usePeerConnection(localStream: MediaStream) { const peerConnection = useMemo(() => { const connection = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun2.1.google.com:19302' }], }); localStream.getTracks().forEach((track) => { connection.addTrack(track, localStream); }); return connection; }, []); return { peerConnection, }; } |
Above, we create an instance of the RTCPeerConnection and add video and audio tracks from the local stream created thanks to our webcam.
Let’s pass the peerConnection object to the useChatConnection hook we created before.
VideoChatRoom.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { VideoFeed } from './VideoFeed'; import { FunctionComponent } from 'react'; import { useChatConnection } from './useChatConnection'; import { usePeerConnection } from './usePeerConnection.tsx'; interface Props { localStream: MediaStream; } export const VideoChatRoom: FunctionComponent<Props> = ({ localStream }) => { const { peerConnection } = usePeerConnection(localStream); useChatConnection(peerConnection); return <VideoFeed mediaStream={localStream} isMuted={true} />; }; |
Sending the connection offer
The first step in establishing the WebRTC connection is sending the connection offer. To do that, we need to use the createOffer and setLocalDescription methods.
Once the offer is created, we send it to our NestJS server through the send_connection_offer event.
useOfferSending.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { useCallback } from 'react'; import { socket } from '../socket.tsx'; import { useParams } from 'react-router-dom'; export function useOfferSending(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const sendOffer = useCallback(async () => { const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); socket.emit('send_connection_offer', { roomName, offer, }); }, [roomName]); return { sendOffer }; } |
We should send the offer as soon as we receive the another_person_ready event indicating that the other person in the chat room is ready.
useChatConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { useParams } from 'react-router-dom'; import { useCallback, useEffect } from 'react'; import { socket } from '../socket'; import {useOfferSending} from "./useOfferSending.tsx"; export function useChatConnection(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const { sendOffer } = useOfferSending(peerConnection); const handleConnection = useCallback(() => { socket.emit('join_room', roomName); }, [roomName]); useEffect(() => { socket.connect(); socket.on('connect', handleConnection); socket.on('another_person_ready', sendOffer); return () => { socket.off('connect', handleConnection); socket.off('another_person_ready', sendOffer); }; }, [roomName, handleConnection, roomName]); } |
We now need to adjust our NestJS server to handle this event. Fortunately, it is very straightforward. As soon as our WebSocket server gets the send_connection_offer, it sends it to the other person in the room.
chat.gateway.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; // ... @SubscribeMessage('send_connection_offer') async sendConnectionOffer( @MessageBody() { offer, roomName, }: { offer: RTCSessionDescriptionInit; roomName: string; }, @ConnectedSocket() socket: Socket, ) { this.server.in(roomName).except(socket.id).emit('send_connection_offer', { offer, roomName, }); } } |
Sending the answer
The other person in the room must prepare the answer as soon as they receive the offer. First, we need to call the setRemoteDescription function to acknowledge the offer. Then, we must create the answer and send it to our NestJS server through the WebSocket.
useSendingAnswer.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { useCallback } from 'react'; import { socket } from '../socket.tsx'; import { useParams } from 'react-router-dom'; export function useOffersListening(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const handleConnectionOffer = useCallback( async ({ offer }: { offer: RTCSessionDescriptionInit }) => { await peerConnection.setRemoteDescription(offer); const answer = await peerConnection.createAnswer(); await peerConnection.setLocalDescription(answer); socket.emit('answer', { answer, roomName }); }, [roomName], ); return { handleConnectionOffer, }; } |
We should configure our frontend application to send the answer once it receives the offer.
useChatConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { useParams } from 'react-router-dom'; import { useCallback, useEffect } from 'react'; import { socket } from '../socket'; import { useOfferSending } from './useOfferSending.tsx'; import { useSendingAnswer } from './useSendingAnswer.tsx'; export function useChatConnection(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const { sendOffer } = useOfferSending(peerConnection); const { handleConnectionOffer } = useSendingAnswer(peerConnection); const handleConnection = useCallback(() => { socket.emit('join_room', roomName); }, [roomName]); useEffect(() => { socket.connect(); socket.on('connect', handleConnection); socket.on('another_person_ready', sendOffer); socket.on('send_connection_offer', handleConnectionOffer); return () => { socket.off('connect', handleConnection); socket.off('another_person_ready', sendOffer); socket.off('send_connection_offer', handleConnectionOffer); }; }, [roomName, handleConnection, roomName, handleConnectionOffer]); } |
We should configure our server to get the answer and pass it to the other person in the chat room.
chat.gateway.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; // ... @SubscribeMessage('answer') async answer( @MessageBody() { answer, roomName, }: { answer: RTCSessionDescriptionInit; roomName: string; }, @ConnectedSocket() socket: Socket, ) { this.server.in(roomName).except(socket.id).emit('answer', { answer, roomName, }); } } |
Processing the answer
Finally, we need to process the answer to the offer. We need to start by acknowledging the answer through the setRemoteDescription method.
useAnswerProcessing.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { useCallback } from 'react'; export function useAnswerProcessing(peerConnection: RTCPeerConnection) { const handleOfferAnswer = useCallback( ({ answer }: { answer: RTCSessionDescriptionInit }) => { peerConnection.setRemoteDescription(answer); }, [peerConnection], ); return { handleOfferAnswer, }; } |
We need to do that as soon as we receive the answer event.
useChatConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import { useParams } from 'react-router-dom'; import { useCallback, useEffect } from 'react'; import { socket } from '../socket'; import { useOfferSending } from './useOfferSending.tsx'; import { useSendingAnswer } from './useSendingAnswer.tsx'; import { useAnswerProcessing } from './useAnswerProcessing.tsx'; export function useChatConnection(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const { sendOffer } = useOfferSending(peerConnection); const { handleConnectionOffer } = useSendingAnswer(peerConnection); const { handleOfferAnswer } = useAnswerProcessing(peerConnection); const handleConnection = useCallback(() => { socket.emit('join_room', roomName); }, [roomName]); useEffect(() => { socket.connect(); socket.on('answer', handleOfferAnswer); socket.on('connect', handleConnection); socket.on('another_person_ready', sendOffer); socket.on('send_connection_offer', handleConnectionOffer); return () => { socket.off('connect', handleConnection); socket.off('another_person_ready', sendOffer); socket.off('send_connection_offer', handleConnectionOffer); socket.off('answer', handleOfferAnswer); }; }, [ roomName, handleConnection, roomName, handleConnectionOffer, handleOfferAnswer, sendOffer, ]); } |
When we receive the stream from the other person in the room, it causes the track event to be dispatched. Let’s listen to it and store it in the state so that we can display it later.
usePeerConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { useMemo, useState } from 'react'; import { socket } from '../socket.tsx'; import { useParams } from 'react-router-dom'; export function usePeerConnection(localStream: MediaStream) { const { roomName } = useParams(); const [guestStream, setGuestStream] = useState<MediaStream | null>(null); const peerConnection = useMemo(() => { const connection = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun2.1.google.com:19302' }], }); connection.addEventListener('track', ({ streams }) => { setGuestStream(streams[0]); }); localStream.getTracks().forEach((track) => { connection.addTrack(track, localStream); }); return connection; }, [localStream, roomName]); return { peerConnection, guestStream, }; } |
The icecandidate event
The icecandidate event in WebRTC is triggered when the local ICE agent discovers a new network candidate for establishing a peer-to-peer connection. This event provides the candidate’s information, which includes details like the IP address and port number. We must send this candidate to the peer we want to connect to. To do that, we need to send an event to our NestJS server.
usePeerConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { useMemo, useState } from 'react'; import { socket } from '../socket.tsx'; import { useParams } from 'react-router-dom'; export function usePeerConnection(localStream: MediaStream) { const { roomName } = useParams(); const [guestStream, setGuestStream] = useState<MediaStream | null>(null); const peerConnection = useMemo(() => { const connection = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun2.1.google.com:19302' }], }); connection.addEventListener('icecandidate', ({ candidate }) => { socket.emit('send_candidate', { candidate, roomName }); }); // ... return connection; }, [localStream, roomName]); return { peerConnection, guestStream, }; } |
Now, let’s handle the send_candidate event by passing the data to the other person in the chat room.
chat.gateway.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; // ... @SubscribeMessage('send_candidate') async sendCandidate( @MessageBody() { candidate, roomName, }: { candidate: unknown; roomName: string; }, @ConnectedSocket() socket: Socket, ) { this.server.in(roomName).except(socket.id).emit('send_candidate', { candidate, roomName, }); } } |
The last step is to handle receiving the candidate.
useChatConnection.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import { useParams } from 'react-router-dom'; import { useCallback, useEffect } from 'react'; import { socket } from '../socket'; import { useOfferSending } from './useOfferSending.tsx'; import { useSendingAnswer } from './useSendingAnswer.tsx'; import { useAnswerProcessing } from './useAnswerProcessing.tsx'; export function useChatConnection(peerConnection: RTCPeerConnection) { const { roomName } = useParams(); const { sendOffer } = useOfferSending(peerConnection); const { handleConnectionOffer } = useSendingAnswer(peerConnection); const { handleOfferAnswer } = useAnswerProcessing(peerConnection); const handleConnection = useCallback(() => { socket.emit('join_room', roomName); }, [roomName]); const handleReceiveCandidate = useCallback( ({ candidate }: { candidate: RTCIceCandidate }) => { peerConnection.addIceCandidate(candidate); }, [peerConnection], ); useEffect(() => { socket.connect(); socket.on('answer', handleOfferAnswer); socket.on('send_connection_offer', handleConnectionOffer); socket.on('another_person_ready', sendOffer); socket.on('connect', handleConnection); socket.on('send_candidate', handleReceiveCandidate); return () => { socket.off('answer', handleOfferAnswer); socket.off('send_connection_offer', handleConnectionOffer); socket.off('another_person_ready', sendOffer); socket.off('connect', handleConnection); socket.off('send_candidate', handleReceiveCandidate); }; }, [ roomName, handleConnection, roomName, handleConnectionOffer, handleOfferAnswer, sendOffer, handleReceiveCandidate ]); } |
Displaying both video streams
We now have access to the video stream of the other person in the room through the guestStream variable. Let’s use it to render both videos.
VideoChatRoom.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import { VideoFeed } from './VideoFeed'; import { FunctionComponent } from 'react'; import { useChatConnection } from './useChatConnection'; import { usePeerConnection } from './usePeerConnection.tsx'; interface Props { localStream: MediaStream; } export const VideoChatRoom: FunctionComponent<Props> = ({ localStream }) => { const { peerConnection, guestStream } = usePeerConnection(localStream); useChatConnection(peerConnection); return ( <div> <VideoFeed mediaStream={localStream} isMuted={true} /> {guestStream && ( <div> guest <VideoFeed mediaStream={guestStream} /> </div> )} </div> ); }; |
Summary
In this article, we’ve gone into detail about what Web Real-Time Communication (WebRTC) is and what problem it solves. We explained how it allows people to communicate in real-time directly through web browsers and keeps the role of the server to a minimum. We implemented a WebSocket server using NestJS and a frontend application with React to show how it works.
By implementing a real-life example, we got from the basics and progressed into more advanced aspects. Thanks to that, we established a solid understanding of WebRTC and used this knowledge in our code.