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 . The best way to set up React now is with Vite
.
Here’s a step-by-step guide to setting up a full MERN stack project from scratch.
Step 1: Installing Node.js & npm
First, install Node.js from 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 .
Step 2: Setting Up the Backend (Express.js)
Now, let’s set up Node.js & Express.
Create a new project folder:
mkdir mern-app && cd mern-app
Initialize a Node.js project:
npm init -y
Install Express:
npm install express
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');
});
Start the server:
node index.js
If you see “Server is running on port 5000”, your backend is working!
Step 3: Connecting MongoDB
Now, let’s connect MongoDB. You can use MongoDB Compass (local) or MongoDB Atlas (cloud-based).
Install Mongoose:
npm install mongoose
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!
Step 4: Setting Up React with Vite
Forget Create React App—Vite is faster and better.
Inside
mern-app
, create a React app with Vite:
npm create vite@latest client -- --template react
Navigate into the client folder:
cd client
Install dependencies:
npm install
Start the React app:
npm run dev
Your frontend should now be running at localhost:5173!
Step 5: Connecting Frontend & Backend
To allow React to communicate with Express, you need to set up a proxy.
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!