Building a Real-Time Chat Application with Node.js and MySQL
Written on
Chapter 1: Introduction to the Chat Application
In this guide, you will discover how to develop a real-time chat application utilizing Node.js along with MySQL for data management.
The chat application enables users to send messages via a form, storing these messages in a MySQL database. Additionally, it retrieves and displays messages in real-time.
Prerequisites
Before you start building the chat application, ensure that you have the following software packages installed on your machine:
- Node.js
- MySQL Server
To install these packages, execute the following commands in your terminal:
apt install nodejs npm
apt install mysql-server
After installing Node.js, npm, and MySQL Server, create a new directory for your project and navigate into it:
mkdir chat
cd chat
Next, run the command below to install the necessary dependencies:
npm install mysql express
This will create a new directory named node_modules, filled with the required modules.
Setting Up the MySQL Database
Now, let’s establish a MySQL database along with a table to hold user messages. Open a new terminal window and type mysql to log in.
Upon successful login, you should see the MySQL prompt. Enter the following commands:
CREATE DATABASE chatdb;
USE chatdb;
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(255),
message TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
This series of commands creates a database called "chatdb" and sets up a table named "messages".
Creating the Server File
Using the nano text editor, create a new file named server.js:
nano server.js
In this file, include the following code:
const express = require('express');
const mysql = require('mysql');
const path = require('path');
const app = express();
const port = 3000;
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'root', // Update with your MySQL username
password: '', // Update with your MySQL password
database: 'chatdb'
});
db.connect((err) => {
if (err) {
throw err;}
console.log('Connected to MySQL database');
});
app.use(express.json());
// Serve static files from the 'public' folder
app.use(express.static(path.join(__dirname, 'public')));
// Route to fetch messages from the database
app.get('/messages', (req, res) => {
db.query('SELECT * FROM messages', (err, results) => {
if (err) {
throw err;}
res.json(results);
});
});
// Route to post a new message to the database
app.post('/messages', (req, res) => {
const { user, message } = req.body;
const timestamp = new Date();
const newMessage = { user, message, timestamp };
db.query('INSERT INTO messages SET ?', newMessage, (err, result) => {
if (err) {
throw err;}
res.send('Message sent successfully');
});
});
// Route handler for the root path
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(Server running on port ${port});
});
This code initializes a basic chat application that enables sending and retrieving messages stored in the MySQL database.
Creating the Frontend
Inside your project directory (chat), create a folder called public. Then, use nano to create an index.html file within this folder:
nano public/index.html
Insert the following HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App</title>
</head>
<body>
<h1>Chat Application</h1>
<form id="messageForm">
<input type="text" id="user" placeholder="Your Name" required />
<input type="text" id="message" placeholder="Type a message..." required />
<button type="submit">Send</button>
</form>
<div id="messages"></div>
<script>
const messageForm = document.getElementById('messageForm');
const messagesDiv = document.getElementById('messages');
messageForm.addEventListener('submit', async (e) => {
e.preventDefault();
const user = document.getElementById('user').value;
const message = document.getElementById('message').value;
const response = await fetch('/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'},
body: JSON.stringify({ user, message })
});
if (response.ok) {
document.getElementById('message').value = '';}
});
async function fetchMessages() {
const response = await fetch('/messages');
const messages = await response.json();
messagesDiv.innerHTML = messages.map(msg => <p><strong>${msg.user}:</strong> ${msg.message}</p>).join('');
}
fetchMessages();
setInterval(fetchMessages, 3000); // Fetch messages every 3 seconds</script>
</body>
</html>
This code builds a simple web-based chat interface where users can input their names and send messages in real-time.
Running the Application
To start the chat application, execute the following command in your terminal:
node server.js
Now, open your web browser and navigate to http://localhost:3000. You will see the chat form, and you can test the application by entering random usernames and typing messages.
To verify that messages are being stored in the database, switch to the MySQL prompt and run:
USE chatdb;
SELECT * FROM messages;
The command USE chatdb; selects the database you created, and SELECT * FROM messages; retrieves all records from the "messages" table. You should see the usernames and messages displayed, confirming that the chat application is functioning correctly. If you wish to delete all messages without dropping the table, use:
DELETE FROM messages;
This command clears all entries from the "messages" table.
Conclusion
In this guide, you've learned to construct a real-time chat application using Node.js and MySQL. You can further enhance this application by incorporating user authentication and additional features.
If you found this tutorial helpful, consider leaving a clap and following for more content!
Chapter 2: Video Tutorials
To supplement your learning, check out these video tutorials:
The first video covers building a real-time chat app using ExpressJS and MySQL, providing a step-by-step walkthrough.
In the second video, you'll learn how to set up a React Native chat application with Node.js and MySQL, expanding your skills further.