:rocket: Day 49: Setting Up the MERN Stack – The Right Way with Vite!

The MERN stack (MongoDB, Express, React, Node.js) is one of the most powerful full-stack combinations. But setting it up right is key! And let’s face it—Create React App is dead :rotating_light:. The best way to set up React now is with Vite :zap:.

Here’s a step-by-step guide to setting up a full MERN stack project from scratch.


:wrench: Step 1: Installing Node.js & npm

First, install Node.js from :point_right: nodejs.org (choose the latest LTS version).

Once installed, check if it’s working by running:
node -v
npm -v

If both return version numbers, you’re good to go :white_check_mark:.


:open_file_folder: Step 2: Setting Up the Backend (Express.js)

Now, let’s set up Node.js & Express.

:one: Create a new project folder:
mkdir mern-app && cd mern-app

:two: Initialize a Node.js project:
npm init -y

:three: Install Express:
npm install express

:four: Create a new file called index.js and add this:

javascript

CopyEdit

const express = require('express');  
const app = express();  

app.get('/', (req, res) => {  
    res.send('MERN Backend is running!');  
});  

app.listen(5000, () => {  
    console.log('Server is running on port 5000');  
});  

:five: Start the server:
node index.js

If you see “Server is running on port 5000”, your backend is working! :tada:


:oil_drum: Step 3: Connecting MongoDB

Now, let’s connect MongoDB. You can use MongoDB Compass (local) or MongoDB Atlas (cloud-based).

:one: Install Mongoose:
npm install mongoose

:two: In index.js, connect MongoDB:

javascript

CopyEdit

const mongoose = require('mongoose');  

mongoose.connect('mongodb://localhost:27017/mernapp', {  
    useNewUrlParser: true,  
    useUnifiedTopology: true  
})  
.then(() => console.log('MongoDB Connected'))  
.catch(err => console.error(err));  

If it logs “MongoDB Connected”, your database is now linked! :white_check_mark:


:atom_symbol: Step 4: Setting Up React with Vite

Forget Create React App—Vite is faster and better.

:one: Inside mern-app, create a React app with Vite:
npm create vite@latest client -- --template react

:two: Navigate into the client folder:
cd client

:three: Install dependencies:
npm install

:four: Start the React app:
npm run dev

Your frontend should now be running at localhost:5173! :rocket:


:link: Step 5: Connecting Frontend & Backend

To allow React to communicate with Express, you need to set up a proxy.

:one: Open client/vite.config.js and add this:

php

CopyEdit

export default defineConfig({  
  server: {  
    proxy: {  
      '/api': 'http://localhost:5000'  
    }  
  }  
});  

Now, React can make API calls to Express without CORS issues!

100daysofcode lebanon-mug