Part 4 --- Building the Full-Stack MERN Structure Connecting the… — Full Stack Camp — TG.ME

Part 4 --- Building the Full-Stack MERN Structure

Connecting the frontend and backend into a cohesive MERN application requires careful coordination of ports, CORS policies, and environment variables. The React development server typically runs on port 5173, while the Express server runs on port 5000, necessitating a proxy configuration or explicit CORS middleware to allow cross-origin requests. To make API endpoints maintainable, developers define a centralized API client that points to the base URL of the backend, ensuring that if your server IP changes, you only update one file. This full-stack structure brings a new level of organization, often separating concerns into frontend components, frontend state stores, backend routes, backend controllers, and database models. With this architecture, your application becomes highly modular, easily extensible, and ready for deployment to platforms like Render or Vercel.

Typical Project Folder Structure

my-mern-app/
├── client/                    # React Frontend (Vite)
│   ├── src/
│   │   ├── components/        # Reusable UI pieces
│   │   ├── pages/             # Route-level screens
│   │   ├── context/           # AuthContext, ThemeContext
│   │   ├── services/          # API service files (authService, productService)
│   │   ├── utils/             # axiosInstance.js, helpers
│   │   └── App.jsx
│   └── package.json

└── server/                    # Express Backend
    ├── models/                # Mongoose models (User, Product)
    ├── routes/                # Express route handlers
    ├── controllers/           # Business logic
    ├── middleware/            # auth.js (verifyToken), errorHandler.js
    ├── config/                # Database connection
    └── server.js

Connecting Client to Server with CORS

On the backend, ensure CORS is enabled to accept requests from your React origin.

// server/server.js
const cors = require("cors");
app.use(cors({ origin: "http://localhost:5173", credentials: true }));

Environment Variables (.env)

Never hardcode secrets! Use environment variables for the API URL and JWT secret.

# client/.env
VITE_API_URL=http://localhost:5000/api

# server/.env
PORT=5000
MONGODB_URI=mongodb://localhost:27017/myapp
JWT_SECRET=your_super_secret_key_here

---
August 9, 2026 74