In this tutorial, we will provide a step-by-step guide on how to connect Express to MongoDB for a Real Time Chat App using the MERN stack (MongoDB, Express, React, Node.js). By the end of this tutorial, you will have a fully functional real-time chat application where users can communicate with each other in real-time.
Requirements:
- MongoDB Atlas account: Sign up for a free MongoDB Atlas account at https://www.mongodb.com/cloud/atlas.
- Node.js and NPM installed on your machine: Install Node.js and npm from https://nodejs.org/en/.
- Create-react-app: Install create-react-app by running
npx create-react-app your-app-name
in the terminal.
Step 1: Setting up the backend with Express
- Create a new folder for your project and navigate into it using the terminal.
- Run
npm init -y
to initialize a new npm project. - Install Express and nodemon to automatically restart the server when changes are made by running
npm install express nodemon
. - Create a new file called
server.js
and add the following code:
const express = require('express');
const app = express();
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
- Run the server by running
npm run start
and navigating tohttp://localhost:5000
in your browser. You should seeHello World!
displayed.
Step 2: Connecting Express to MongoDB
- Install the
mongoose
package by runningnpm install mongoose
. - Create a new file called
db.js
and add the following code:
const mongoose = require('mongoose');
mongoose.connect('your-mongodb-atlas-connection-string', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch((err) => console.log(err));
- Replace
'your-mongodb-atlas-connection-string'
with the connection string from your MongoDB Atlas dashboard. - Import and call the
db.js
file in theserver.js
file:
require('./db');
Step 3: Setting up the frontend with React
- Navigate to the project directory and run
npx create-react-app client
to create a new React project. - Delete the contents of the
src
directory and create a new file calledindex.js
with the following code:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
- Create a new file called
App.js
and add the following code:
import React from 'react';
const App = () => {
return (
<div>
<h1>Real Time Chat App</h1>
</div>
);
};
export default App;
- Start the React server by navigating to the
client
directory and runningnpm start
.
Step 4: Adding real-time chat functionality
- Install the
socket.io
package in the server directory by runningnpm install socket.io
. - Add the following code in the
server.js
file after the Express app has been initialized:
const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
http.listen(5000, () => {
console.log('Socket.io server running on port 5000');
});
- Add the following code in the
App.js
file to establish a socket connection with the server:
import React, { useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:5000');
const App = () => {
useEffect(() => {
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
}, []);
return (
<div>
<h1>Real Time Chat App</h1>
</div>
);
};
export default App;
- Test the real-time chat functionality by opening multiple tabs of the application in the browser and sending messages between them.
Congratulations! You have successfully connected Express to MongoDB for a Real Time Chat App using the MERN stack. Happy coding!
awesome tutorial sir. thank you
please complete this course as quickly as possible 🙏
post daily 2 videos please