Setting Up Frontend and Backend Folders: React Vite & Express Guid

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.

  1. Open your terminal in your desired project directory.

  2. Create the main project folder:

    mkdir fullstack-setup
    cd fullstack-setup
    

  1. Create frontend and backend folders:

    mkdir frontend backend
    

    Your 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.

  1. Navigate into the frontend folder:

    cd frontend
    

  1. Create a new React Vite project:

    npm create vite@latest . -- --template react-js
    

    Note: The . in the command specifies that you want to create the Vite

    project in the current directory (frontend folder).

  2. Install frontend dependencies:

    npm install
    

  1. Start the frontend development server:

    npm run dev
    

    Your 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.

  1. Navigate back to the main project folder and then into the backend folder:

    Open a new terminal or navigate back in your current terminal:

    cd ..
    cd backend
    

  1. Initialize a Node.js project:

    npm init -y
    

    This creates a package.json file with default settings.

  2. Install backend dependencies: We'll need express, mongoose

(for MongoDB interaction), and dotenv to manage environment variables.

```bash
npm install express mongoose dotenv
```

  1. Create server.js file: This will be the main file for our backend server.

    touch server.js
    

  2. Add basic Express server code to server.js: Open backend/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}`);
});
```

  1. Create a .env file in the backend folder: This file will store our

environment variables like the port and MongoDB connection string.

```bash
touch .env
```

  1. Add environment variables to .env: Open .env and 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=majority
    

    Important: For development, you can use a local MongoDB instance. For production, consider using MongoDB Atlas or another cloud MongoDB service.

    Never commit your .env file to your repository! Add it to your .gitignore file.

  2. 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 frontend folder.

  • Build your Node.js Express API in the backend folder.

  • 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!

Published: Feb 2025

← Back to Blog