A WebSocket Example Built With Node And ReactJS
Creating a WebSocket project with a Node.js backend and a React.js frontend is a great way to build real-time applications. Below is a step-by-step guide to help you set up these two sub-projects.
Project Structure
Your project structure will look something like this:
websocket-project/
├── server/
│ ├── package.json
│ ├── server.js
├── ui/
│ ├── package.json
│ ├── public/
│ ├── src/
│ │ ├── App.js
│ │ ├── index.js
├── README.md
Step 1: Set Up the Backend (Node.js)
-
Create the Backend Directory
mkdir server cd server
-
Initialize the Node.js Project
npm init -y
-
Install Required Dependencies
npm install ws express
-
Create
server.js
- This file will create an Express server and a WebSocket server using the
ws
library.
// backend/server.js const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); // Serve static files from the frontend app.use(express.static('../ui/build')); // WebSocket connection wss.on('connection', (ws) => { console.log('New client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); ws.send(`Echo: ${message}`); }); ws.on('close', () => { console.log('Client disconnected'); }); }); // Start the server server.listen(8080, () => { console.log('Server is running on http://localhost:8080'); });
- This file will create an Express server and a WebSocket server using the
-
Run the Backend Server
node server.js
Step 2: Set Up the Frontend (React.js)
-
Create the Frontend Directory
npx create-react-app frontend cd frontend
-
Modify
App.js
- Connect to the WebSocket server and display the messages.
// frontend/src/App.js import React, { useEffect, useState } from 'react'; function App() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [ws, setWs] = useState(null); useEffect(() => { const socket = new WebSocket('ws://localhost:8080'); socket.onopen = () => { console.log('Connected to WebSocket server'); }; socket.onmessage = (event) => { setMessages((prevMessages) => [...prevMessages, event.data]); }; socket.onclose = () => { console.log('Disconnected from WebSocket server'); }; setWs(socket); return () => { socket.close(); }; }, []); const sendMessage = () => { if (ws && input.trim()) { ws.send(input); setInput(''); } }; return ( <div style={{ padding: '20px' }}> <h1>WebSocket Chat</h1> <div> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} style={{ marginRight: '10px' }} /> <button onClick={sendMessage}>Send</button> </div> <div style={{ marginTop: '20px' }}> <h2>Messages:</h2> {messages.map((msg, index) => ( <p key={index}>{msg}</p> ))} </div> </div> ); } export default App;
-
Run the Frontend
npm start
- The React app will run at
http://localhost:3000
by default.
- The React app will run at
Step 3: Connect the Frontend and Backend
- When you start both the backend and frontend, they will connect via WebSocket.
- Open the frontend in your browser (
http://localhost:3000
) and open the console to see WebSocket logs. - You can type messages in the input box, and they will be sent to the WebSocket server, which will echo them back.
Step 4: Build for Production (Optional)
-
Build the React App
cd frontend npm run build
-
Serve the Built Files in Express
- The Express server in the backend will serve the static files from the React build folder.
- Modify the backend
server.js
to serve the React app:
// Serve React build files app.use(express.static('../frontend/build')); // Fallback to index.html for React Router app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '../frontend', 'build', 'index.html')); });
-
Run the Backend Again
node server.js
- Now, when you visit
http://localhost:8080
, you’ll see your React app served by the Express server, and WebSocket communication will work as expected.
Code
Please check the code in GitHub.