
Setting Up Frontend and Backend Folders: React Vite & Express Guid
Setting Up Frontend and Backend Folders: React Vite & Express Guide
Structuring your full-stack projects into separate frontend and backend folders is a best practice for maintainability and organization. This guide will walk you through setting up a project with a React Vite frontend and an Express Node.js backend, using JavaScript and MongoDB.
Why Separate Frontend and Backend?
- Clear Separation of Concerns: Frontend and backend are distinct parts of your application, handling different responsibilities. Separating them makes your codebase cleaner and easier to manage.
- Independent Development: Teams can work on the frontend and backend concurrently without stepping on each other's toes.
- Scalability: You can scale frontend and backend resources independently based on demand.
- Technology Flexibility: You can choose the best technologies for each layer.
Step 1: Create the Project Folders 📂
First, let's create the main project folder and then the frontend and
backend folders inside it.
-
Open your terminal in your desired project directory.
-
Create the main project folder:
mkdir fullstack-setup cd fullstack-setup
-
Create
frontendandbackendfolders:mkdir frontend backendYour project structure should now look like this:
fullstack-setup/ ├── backend/ └── frontend/
Step 2: Set up the React Vite Frontend ⚛️
Now, let's set up the frontend using Vite for a fast and modern React development experience.
-
Navigate into the
frontendfolder:cd frontend
-
Create a new React Vite project:
npm create vite@latest . -- --template react-jsNote: The
.in the command specifies that you want to create the Viteproject in the current directory (
frontendfolder). -
Install frontend dependencies:
npm install
-
Start the frontend development server:
npm run devYour React frontend should now be running at
http://localhost:5173/.// You can open this in your browser to see the default Vite + React app.
Step 3: Set up the Express Node.js Backend
Next, let's set up the backend using Express with Node.js and connect to MongoDB.
-
Navigate back to the main project folder and then into the
backendfolder:Open a new terminal or navigate back in your current terminal:
cd .. cd backend
-
Initialize a Node.js project:
npm init -yThis creates a
package.jsonfile with default settings. -
Install backend dependencies: We'll need
express,mongoose
(for MongoDB interaction), and dotenv to manage environment variables.
```bash
npm install express mongoose dotenv
```
-
Create
server.jsfile: This will be the main file for our backend server.touch server.js -
Add basic Express server code to
server.js: Openbackend/server.js
in your code editor and add the following code:
```
require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 5000; // Use PORT from .env or default to 5000
app.get('/', (req, res) => {
res.send('Backend server is running!');
});
// MongoDB Connection (replace with your connection string)
const mongoURI = process.env.MONGO_URI || 'mongodb://localhost:27017/your-database-name';
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
```
- Create a
.envfile in thebackendfolder: This file will store our
environment variables like the port and MongoDB connection string.
```bash
touch .env
```
-
Add environment variables to
.env: Open.envand add your port and MongoDB URI. Remember to replace placeholders with your actual MongoDB connection details!PORT=5000 MONGO_URI=mongodb+srv://<your_username>:<your_password>@<your_cluster_url>/<your_database_name>?retryWrites=true&w=majorityImportant: For development, you can use a local MongoDB instance. For production, consider using MongoDB Atlas or another cloud MongoDB service.
Never commit your
.envfile to your repository! Add it to your.gitignorefile. -
Start the backend server:
node server.js
Your Express backend should now be running on http://localhost:5000/. Visiting this in your browser should display "Backend server is running!". Check your terminal for "MongoDB connected" if your MongoDB setup is correct.
Step 4: Connect Frontend to Backend (Example)
While this guide focuses on folder setup, let's quickly see how you might connect your frontend to the backend. In your React frontend
(e.g., in frontend/src/App.jsx), you could fetch data from your backend:
import React, { useEffect, useState } from 'react';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/hello') // Assuming you create a /api/hello endpoint in your backend
.then(response => response.text())
.then(data => setMessage(data))
.catch(error => console.error("Error fetching data:", error));
}, []);
return (
<div>
<h1>React Frontend connected to Backend!</h1>
<p>{message}</p>
</div>
);
}
export default App;
You would then need to create an /api/hello endpoint in your backend/server.js to send data to the frontend.
Conclusion
You've successfully set up a project with separate frontend and backend folders, using React Vite for the frontend and Express Node.js for the backend.
This structure provides a solid foundation for building scalable and maintainable full-stack applications.
From here, you can:
-
Develop your React frontend in the
frontendfolder. -
Build your Node.js Express API in the
backendfolder. -
Establish communication between the frontend and backend for a complete full-stack application.
This organized structure will make your development process smoother and your codebase much easier to navigate as your project grows!