How Can I Send Messages via WebSockets with React on the Frontend and tRPC on the Backend?
Image by Lottie - hkhazo.biz.id

How Can I Send Messages via WebSockets with React on the Frontend and tRPC on the Backend?

Posted on

Are you tired of using traditional HTTP requests to send messages between your React frontend and tRPC backend? Do you want to create a real-time communication system that’s fast, efficient, and scalable? Look no further! In this article, we’ll show you how to send messages via WebSockets with React on the frontend and tRPC on the backend.

What are WebSockets?

WebSockets are a bi-directional communication protocol that allows for real-time communication between a client (usually a web browser) and a server. Unlike traditional HTTP requests, WebSockets establish a persistent connection between the client and server, allowing for efficient and low-latency communication.

Why Use WebSockets with React and tRPC?

Using WebSockets with React and tRPC offers several benefits, including:

  • Real-time communication: WebSockets enable real-time communication between the client and server, making it perfect for applications that require instant updates, such as live updates, gaming, and chat applications.
  • Efficient: WebSockets reduce the overhead of traditional HTTP requests, making it a more efficient way to communicate between the client and server.
  • Scalable: WebSockets can handle a large number of concurrent connections, making it a scalable solution for high-traffic applications.

Setting Up the Project

Before we dive into the implementation, let’s set up a new React project with tRPC. Run the following command to create a new React project:

npx create-react-app websocket-chat

Next, install tRPC by running the following command:

yarn add @trpc/server

Creating the tRPC Server

Create a new file called `server.ts` and add the following code:

import { createTRPC } from '@trpc/server';
import { WebSocket } from 'ws';

const app = createTRPC();

app.ws('/websocket', {
  onConnection: (ws: WebSocket) => {
    console.log('Client connected');

    ws.on('message', (message: string) => {
      console.log(`Received message: ${message}`);
      ws.send(`Server received message: ${message}`);
    });

    ws.on('close', () => {
      console.log('Client disconnected');
    });
  },
});

app.listen(4000, () => {
  console.log('Server listening on port 4000');
});

This code sets up a tRPC server that listens for WebSocket connections on port 4000. When a client connects, it logs a message to the console and sets up event listeners for messages and close events.

Connecting to the tRPC Server from React

Create a new file called `App.tsx` and add the following code:

import React, { useState, useEffect } from 'react';
import { WebSocket } from 'ws';

function App() {
  const [message, setMessage] = useState('');
  const [ws, setWs] = useState(null);

  useEffect(() => {
    const ws = new WebSocket('ws://localhost:4000/websocket');

    ws.onmessage = (event) => {
      console.log(`Received message from server: ${event.data}`);
    };

    ws.onopen = () => {
      console.log('Connected to server');
    };

    ws.onclose = () => {
      console.log('Disconnected from server');
    };

    ws.onerror = (event) => {
      console.log(`Error: ${event}`);
    };

    setWs(ws);
  }, []);

  const sendMessage = () => {
    if (ws) {
      ws.send(message);
    }
  };

  return (
    
setMessage(event.target.value)} placeholder="Type a message..." />
); } export default App;

This code sets up a WebSocket connection to the tRPC server and sets up event listeners for messages, open, close, and error events. It also sets up a input field and a send button to send messages to the server.

Sending Messages via WebSockets

Now that we have set up the tRPC server and connected to it from React, let’s send a message from the React frontend to the tRPC backend.

In the `App.tsx` file, add the following code to the `sendMessage` function:

const sendMessage = () => {
  if (ws) {
    ws.send(message);
    setMessage('');
  }
};

This code sends the message to the server when the send button is clicked and clears the input field.

In the `server.ts` file, add the following code to the `onmessage` event listener:

ws.on('message', (message: string) => {
  console.log(`Received message: ${message}`);
  ws.send(`Server received message: ${message}`);
  // Broadcast the message to all connected clients
  app.ws.clients.forEach((client) => {
    client.send(message);
  });
});

This code logs the received message to the console, sends a response back to the client, and broadcasts the message to all connected clients.

Conclusion

In this article, we have shown you how to send messages via WebSockets with React on the frontend and tRPC on the backend. We have set up a tRPC server that listens for WebSocket connections, connected to the server from React, and sent messages between the client and server.

WebSockets offer a powerful way to enable real-time communication between the client and server, making it perfect for applications that require instant updates, such as live updates, gaming, and chat applications.

Further Reading

If you want to learn more about WebSockets and tRPC, check out the following resources:

Technology Resource
WebSockets WebSockets API on MDN
tRPC tRPC Documentation
React React Documentation

We hope this article has helped you understand how to send messages via WebSockets with React on the frontend and tRPC on the backend. Happy coding!

Here is the FAQ about sending messages via WebSockets with React on the frontend and tRPC on the backend:

Frequently Asked Question

Got questions about sending messages via WebSockets with React on the frontend and tRPC on the backend? We’ve got answers!

What is the best way to establish a WebSocket connection with tRPC on the backend?

You can establish a WebSocket connection with tRPC on the backend by creating a WebSocket API route in your tRPC backend and connecting to it from your React frontend using the `ws` or `wss` protocol. Make sure to handle the connection, disconnection, and message events on both the frontend and backend!

How do I send messages from the frontend to the backend via WebSockets?

To send messages from the frontend to the backend via WebSockets, you can use the `send()` method of the WebSocket object in your React frontend. For example, `socket.send(JSON.stringify({ type: ‘message’, data: ‘Hello, backend!’ }))`. On the backend, you can listen for incoming messages using the `onMessage()` event handler!

Can I use tRPC’s built-in subscription feature with WebSockets?

Yes, you can use tRPC’s built-in subscription feature with WebSockets! tRPC provides a `onSubscribe()` method that allows you to handle subscription requests from clients. By combining this with WebSockets, you can establish real-time communication between the frontend and backend and broadcast messages to subscribed clients!

How do I handle errors and disconnections when using WebSockets with tRPC?

To handle errors and disconnections when using WebSockets with tRPC, you can use the `onError()` and `onClose()` event handlers on both the frontend and backend. These events allow you to catch and handle errors, as well as detect when the connection is lost or closed. Don’t forget to implement reconnect logic to ensure a seamless user experience!

Are there any security considerations when using WebSockets with tRPC?

Yes, there are security considerations when using WebSockets with tRPC! Make sure to implement proper authentication and authorization mechanisms to ensure that only authorized clients can establish WebSocket connections. Additionally, be mindful of potential vulnerabilities such as cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks!