Create a Real-Time Chat App with Bun and React

Introduction

Creating a real-time chat application is a fantastic project for both beginners and experienced developers alike. It serves as a practical way to learn about WebSockets, client-server communication, and the intricacies of building an interactive user interface. In this tutorial, we’ll walk through the process of creating a chat app using Bun and React. Bun, a modern JavaScript runtime, allows us to focus on performance and productivity, making it an excellent choice for our application.

This guide assumes you have a basic understanding of JavaScript and React. While we will cover a lot of ground, including both front-end and back-end development, my aim is to ensure that you gain not only the technical skills but also the confidence to tackle similar projects in the future.

So, let’s dive in and explore how you can build a functional chat app from scratch!

Setting Up Your Development Environment

Before we jump into coding, you need to set up your development environment. Ensure you have Bun installed on your computer. If you haven’t installed it yet, you can do so by running the following command:

curl -fsSL https://bun.sh/install | bash

Next, set up a new Bun project. Run the following command in your terminal:

bun create react chat-app

This command initializes a new Bun project and installs the necessary dependencies for a React application. After the setup is complete, navigate into your project directory:

cd chat-app

Now that you have your project set up, let’s run the development server to ensure everything is working correctly:

bun dev

You should see your React application running in the browser at http://localhost:3000. If you can see the default React welcome screen, you’re ready to move on!

Building the Chat Interface

The first step in building our chat application is to create the user interface where users can send and receive messages. Open the src/App.jsx file, where you’ll define the main structure of your chat app.

Let’s break our chat interface down into key components: a message display area and a message input area. We will create two functional components: MessageList for displaying message history and MessageInput for user input. Here’s how you can structure it:

import React, { useState } from 'react';

function MessageList({ messages }) {
  return (
    
{messages.map((msg, index) => (
{msg.sender}: {msg.content}
))}
); } function MessageInput({ onSend }) { const [message, setMessage] = useState(''); const sendMessage = () => { if (message.trim()) { onSend(message); setMessage(''); } }; return (
setMessage(e.target.value)} placeholder='Type your message...' />
); } function App() { const [messages, setMessages] = useState([]); const handleSendMessage = (messageContent) => { const newMessage = { sender: 'You', content: messageContent }; setMessages((prevMessages) => [...prevMessages, newMessage]); }; return (
); } export default App;

This code defines the app’s components and establishes a state to manage the messages. The MessageInput component allows users to type messages, and the MessageList component displays those messages. Now you can start building the real-time functionality!

Integrating WebSockets

For real-time messaging, we need to implement WebSockets. This technology allows the client and server to communicate instantly, making it ideal for chat applications. We will create a simple WebSocket server using Bun and connect it to our React app.

First, create a new file at the root of your project directory called server.js. Here, you will set up your WebSocket server:

import { serve } from 'bun';

const wss = serve({
  port: 4000,
}).on('connection', (ws) => {
  ws.on('message', (message) => {
    // Broadcast the received message to all connected clients
    wss.clients.forEach(client => {
      if (client.readyState === client.OPEN) {
        client.send(message);
      }
    });
  });
});

console.log('WebSocket server running on ws://localhost:4000');

In this code snippet, we create a WebSocket server that listens for incoming connections. When a message is received, it sends that message to all connected clients. Next, you need to integrate this server with your React application.

Modify the existing functionality in the App.jsx file to connect to your WebSocket server:

const WS_URL = 'ws://localhost:4000';
const ws = new WebSocket(WS_URL);

const App = () => {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    ws.onmessage = (event) => {
      const messageReceived = JSON.parse(event.data);
      setMessages((prevMessages) => [...prevMessages, messageReceived]);
    };
  }, []);

  const handleSendMessage = (messageContent) => {
    const newMessage = { sender: 'You', content: messageContent };
    ws.send(JSON.stringify(newMessage));
    setMessages((prevMessages) => [...prevMessages, newMessage]);
  };

  // rest of the component...
};

This code establishes a WebSocket connection and listens for incoming messages. When a user sends a message, it broadcasts it to all connected clients, making the chat app functional in real time.

Styling Your Chat App

With the functionality in place, it’s time to give your chat app some flair. Using CSS to style your components helps create a user-friendly interface. Create a styles.css file in your src directory and include it in your App.jsx file:

import './styles.css';

Here’s a simple styling setup you can start with:

.chat-app {
  max-width: 600px;
  margin: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 1em;
}

.message {
  margin: 5px 0;
}

input {
  width: calc(100% - 75px);
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

This CSS helps create a clean and modern look for your chat application. Feel free to customize the styles further based on your preferences.

Testing Your Application

Now that your chat app is fully functional, it’s essential to test it thoroughly. Open multiple browser windows and connect them to your chat app to simulate different users. Send messages between these windows to ensure that they are displayed in real time and that your application behaves as expected.

Additionally, consider testing under different network conditions. You can use tools like Chrome’s Developer Tools to simulate slow network speeds, which can help you identify potential performance issues in your application.

Should you encounter any bugs or unexpected behavior, carefully debug your code by utilizing console logs and React’s built-in error boundaries. Maintain a habit of writing clean, readable code with well-commented sections, especially when dealing with real-time applications, as they can get complicated quickly.

Deploying Your Chat App

Once you’re satisfied with your chat application, it’s time to deploy it so others can use it. You can deploy the front-end and back-end on platforms like Vercel, Netlify, or even with services like DigitalOcean for more advanced setups.

When deploying, make sure your WebSocket server is accessible from the public web. Properly configure your server to allow incoming connections from the client’s domain for seamless communication.

After deployment, go through the entire application to ensure everything functions as intended in the live environment. Test the chat feature from at least two different devices to confirm that real-time messaging is working as expected.

Conclusion

Congratulations! You’ve successfully built a real-time chat application using Bun and React. You’ve learned how to create an interactive interface, set up a WebSocket server for live messaging, and style your application to make it pleasant for users.

Always remember that building applications is an iterative process—don’t hesitate to come back and enhance the functionality of your chat app. You might explore adding features like user authentication, message timestamps, or even emoji support.

Thank you for joining me in this tutorial. I hope it has inspired you to tackle more ambitious projects with confidence. Happy coding!

Scroll to Top