top of page

Guide to Building a Full Stack React JS App

Writer's picture: CODING Z2MCODING Z2M

Updated: 3 days ago

Full Stack React JS

Full Stack React JS


Building a Full Stack React JS application with the MERN stack (MongoDB, Express, React, Node.js) is a great choice for full-stack development. Below are some key suggestions to help you get started:


Set Up Your Development Environment Node.js & NPM

  • Ensure you have the latest version of Node.js and npm (Node Package Manager) installed.

  • MongoDB: You can use MongoDB Atlas (cloud-based) or install MongoDB locally.

  • Code Editor: Use a code editor like VS Code for easy integration with the tools you'll need.


Key Principles of Modular Approach

  • Separation of Concerns:

    • Each layer (routes, controllers, models, middleware) handles a specific responsibility.

    • Avoid placing business logic in routes or server files.

  • Reusability:

    • Shared utilities (e.g., error handlers, token generation) are centralized in utility files.

  • Extensibility:

    • Add new features or modules without affecting existing ones.

  • Testability:

    • Modularized code allows unit testing of individual components.



Step 1: Set Up the Backend (Express, MongoDB, Node.js) Here's an example folder structure for a MERN stack app:

mern-app/

├── backend/ # Backend (Node.js + Express.js)

│ ├── config/ # Configuration files

│ │ └── db.js # MongoDB connection logic

│ ├── controllers/ # Business logic for routes

│ │ └── userController.js # Example: User-related logic

│ │ └── productController.js # Example: Product-related logic

│ ├── middleware/ # Custom middleware

│ │ └── authMiddleware.js # Example: Auth logic

│ ├── models/ # Mongoose models

│ │ └── userModel.js # Example: User schema

│ │ └── productModel.js # Example: Product schema

│ ├── routes/ # Express routes

│ │ └── userRoutes.js # Example: User-related routes

│ │ └── productRoutes.js # Example: Product-related routes

│ ├── utils/ # Helper functions

│ │ └── logger.js # Example: Custom logger

│ ├── .env # Environment variables

│ ├── server.js # Main entry point

├── frontend/ # Frontend (React.js)

│ ├── public/ # Static assets

│ ├── src/ # Source code

│ │ ├── components/ # Reusable React components

│ │ ├── pages/ # Page-level components

│ │ ├── services/ # API services (Axios or fetch)

│ │ ├── App.js # Main React component

│ │ ├── index.js # React entry point

│ └── package.json # Frontend dependencies

├── README.md # Project documentation


MERN Full Stack Web Development Training

1. Create a New Directory for Your Backend: Start by creating a separate folder for your backend inside your project directory:

>mkdir backend

>cd backend

2. Initialize a New Node.js Project: Initialize the Node.js app with the following command:

>npm init -y

This creates a package.json file.

3. Install Required Dependencies: Install the following packages for setting up the backend:

>npm install express mongoose cors dotenv

express: Web framework for Node.js.

mongoose: MongoDB object modeling tool.

cors: Middleware to handle Cross-Origin Resource Sharing (needed for React frontend to communicate with your backend).

dotenv: To handle environment variables.


4.Using MongoDB Atlas for Cloud Storage https://www.mongodb.com/atlas 

To get started, create an Organization. Within an Organization you can create

project.

Create a database by choosing your cloud provider, region, and specs.(Free Tier)

Go to "Database Access" then edit your password, if you want.

Go to "Network Access" then Edit IP address as 0.0.0.0/0 Go to "Database" then "connect" -> "Drivers" -> choose "Node.js" option as driver, copy the MongoDB URI, then add it in the .env file.


5. Create .env File: In the root of your backend folder, create a .env file to store sensitive information like the MongoDB URI:

MONGO_URI=mongodb://localhost:27017/yourdbname



Step 2: Set Up MongoDB Models

1. Create a Model for Your Data: Let’s create a simple model, say a User model. Create a 'models' folder and a file 'User.js' inside it: Then, define the schema for the user:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  }
});
module.exports = mongoose.model('User', userSchema);

2.Handle MongoDB connection logic: create a file db.js inside the folder 'config', encapsulating the logic (database connection) can be reused or modified independently.

const mongoose = require('mongoose');
const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log("Connected to MongoDB");
    } catch (err) {
        console.error("Failed to connect to MongoDB", err);
        process.exit(1); // Exit the process with failure
    }
};
module.exports = connectDB;

3. Create the Controller: In this case, we’ll create a userController.js inside 'controllers' folder that handles the business logic for user-related(users API) actions (e.g., registering a user, getting users from the database). Create controller functions that handle the logic for each route in the users API:

const User = require('../models/User');
// Controller to register a new user
const registerUser = async (req, res) => {
  try {
    const { name, email, password } = req.body;
    // Check if user already exists
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      return res.status(400).json({ message: 'User already exists' });
    }
    // Create and save new user
    const newUser = new User({ name, email, password });
    await newUser.save();
    res.status(201).json({ message: 'User registered successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};
// Controller to get all users
const getAllUsers = async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json(users);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};
// Export the controller functions
module.exports = {
  registerUser,
  getAllUsers
};

registerUser: Handles creating a new user, including validation (e.g., checking if the user already exists).

getAllUsers: Retrieves all users from the MongoDB database.


MERN Full Stack Web Development Training

4. Create API Routes to use the Controller: Create a 'routes' folder and a file for the user routes, users.js:

Create routers for the users API that handles requests for the users API:

const express = require('express');
const userController = require('../controllers/userController'); // Import the controller
const router = express.Router();

// POST route for registering a user
router.post('/register', userController.registerUser);

// GET route for fetching all users
router.get('/', userController.getAllUsers);

module.exports = router;

5. Create the Server (Express Setup): In the backend folder, create a new file server.js and add the following code to set up your Express server:

NOTE: Link Routes to Express: Import the routes and link them to your Express app:

const userRoutes = require('./routes/users');

app.use('/api/users', userRoutes); // Prefix all routes with /api/users

const express = require('express');
const mongoose = require('mongoose');
const userRoutes = require('./routes/users'); // Import Routes
const connectDB = require('./config/db');
const cors = require('cors');
require('dotenv').config();
const app = express();
// Middleware
app.use(cors()); // Enable cross-origin requests
app.use(express.json()); // Parse JSON bodies
// Connect to MongoDB
connectDB();
// Use Routes
app.use('/api/users', userRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

app.use('/api/users', userRoutes);: This ensures that any request made to /api/users will be routed to the userRoutes file, which in turn uses the controller logic to handle the request.



Step 3: Test the Backend

1. Start the Backend Server: Run the server to ensure everything is set up correctly:

>node server.js

2. Test the Endpoints: Use Postman to test your API endpoints:

POST /api/users/register: Test creating a new user (send a JSON body like { "name": "John", "email": "john@example.com", "password": "password123" }).

GET /api/users: Test fetching all users.

You should see the appropriate responses based on your controller logic.



Step 4: Connect Backend with Frontend (React)

On the React side, you will continue to make API calls using Axios (as shown in the earlier steps). Here's an example of how you can connect to the backend:

1. Create a Component to Register Users (Example):

import React, { useState } from 'react';
import axios from 'axios';
const Register = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('http://localhost:5000/api/users/register', {
        name,
        email,
        password
      });
      alert(response.data.message);
    } catch (error) {
      console.error(error);
      alert('Error registering user');
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} required />
      <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} required />
      <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} required />
      <button type="submit">Register</button>
    </form>
  );
};
export default Register;

2. Testing the Registration in React: When you fill out the registration form in your React app and submit it, the backend will handle the logic through the registerUser controller, saving the user to the MongoDB database.



12 views0 comments

Recent Posts

See All

Comments


bottom of page