React Node.js Real Estate App Full Tutorial | MERN Stack App & Real-time Chat

4 min read 4 months ago
Published on Aug 31, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of building a full-stack real estate application using the MERN stack (MongoDB, Express.js, React, Node.js). You will also implement real-time chat functionality with Socket.io. This step-by-step guide covers everything from installation to advanced features like JWT authentication and data fetching.

Step 1: Installation

  1. Set up your development environment:

    • Make sure you have Node.js and npm installed on your machine.
    • Use the following command to create a new project directory:
      mkdir real-estate-app
      cd real-estate-app
      
  2. Initialize a new Node.js project:

    npm init -y
    
  3. Install necessary dependencies:

    npm install express mongoose dotenv cors cookie-parser jsonwebtoken
    
  4. Install additional tools for your React front-end:

    npx create-react-app client
    cd client
    npm install axios react-router-dom socket.io-client
    

Step 2: Setting Up the App Structure

  1. Organize your project directory:

    • Create folders for server and client code.
    • Your project should have the following structure:
      /real-estate-app
          /client
          /server
      
  2. Inside the server folder, create the following files:

    • server.js for your main server code.
    • config.js for configuration settings.
    • routes/ for defining your API routes.
    • models/ for your MongoDB models.

Step 3: Understanding Express.js Routes

  1. Set up your Express server in server.js:

    const express = require('express');
    const mongoose = require('mongoose');
    const cors = require('cors');
    const cookieParser = require('cookie-parser');
    
    const app = express();
    app.use(cors());
    app.use(express.json());
    app.use(cookieParser());
    
    mongoose.connect('your_mongodb_connection_string', { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => console.log("MongoDB connected"))
        .catch(err => console.log(err));
    
    const PORT = process.env.PORT || 5000;
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    
  2. Define your routes in routes folder:

    • Create files like auth.js, posts.js, etc., to handle different routes.

Step 4: Implementing JWT Authentication

  1. Create an authentication middleware:

    const jwt = require('jsonwebtoken');
    
    const authMiddleware = (req, res, next) => {
        const token = req.cookies.token;
        if (!token) return res.sendStatus(401);
        jwt.verify(token, 'your_jwt_secret', (err, user) => {
            if (err) return res.sendStatus(403);
            req.user = user;
            next();
        });
    };
    
  2. Protect your routes using the middleware:

    app.get('/protected', authMiddleware, (req, res) => {
        res.send('This is a protected route');
    });
    

Step 5: Setting Up Prisma with MongoDB

  1. Install Prisma and initialize it:

    npm install @prisma/client
    npx prisma init
    
  2. Configure your schema.prisma file to reflect your data models.

  3. Use Prisma to interact with your MongoDB database in your routes.

Step 6: Working with React for Front-end

  1. Set up routing in your React app using react-router-dom.

    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    
    function App() {
        return (
            <Router>
                <Switch>
                    <Route path="/" exact component={Home} />
                    <Route path="/login" component={Login} />
                    {/* Add more routes as needed */}
                </Switch>
            </Router>
        );
    }
    
  2. Create components for your application such as Home, Login, Post, etc.

Step 7: Implementing Real-Time Chat with Socket.io

  1. Set up Socket.io on the server:

    const http = require('http');
    const server = http.createServer(app);
    const io = require('socket.io')(server);
    
    io.on('connection', (socket) => {
        console.log('New user connected');
        socket.on('sendMessage', (message) => {
            io.emit('receiveMessage', message);
        });
    });
    
  2. Connect to Socket.io in your React app:

    import io from 'socket.io-client';
    const socket = io('http://localhost:5000');
    
    socket.on('receiveMessage', (message) => {
        // Handle received message
    });
    

Conclusion

In this tutorial, you have learned how to create a full-stack real estate application using the MERN stack. You set up a server with Express and MongoDB, implemented JWT authentication, and built a React front-end that communicates with your backend. You also added real-time chat functionality with Socket.io.

Next steps could include deploying your app or adding more features such as user profiles or advanced search capabilities. Make sure to explore the source code provided in the video for additional insights and enhancements.