MERN Stack is basically Mongos, Express React.js and Node.js. Which means, in a MERN Stack application we create backend using Node.js and Express and Front End with React.js and for the Database we use NoSQL kind of Database which is MongoDB. In this post we are going to explain how to start a new MERN stack application.
Required Softwares
To create a MERN stack application you need to install following softwares into your machine.
- VS Code IDE
- Node.js
- MongoDB
- PostMan
Initialize Backend (Node.js and Express):
Select a folder location where you want to create your first MERN stack application and open a command prompt inside that folder. For example, if we choose MERN-PROJECTS as a folder location and we open this folder in explorer. We can type the cmd
in top address bar and it will open a new command window with the respective folder location. Now all you need to do is to create a directory with the name of your project. For example, if we want to create an application which name is mytodo, simply enter these commands
>> mkdir mytodo
>> cd mytodo
Now that you are inside this directory of mytodo all you need to do is create another folder called backend so you can use the same mkdir
command to create the backend directory. Once your backend directory is created you are ready to create your Node.js based project for backend. Here’s how you do it
- Navigate to the project directory and run
npm init
to initialize a new Node.js project. - Install required packages:
npm install express mongoose cors
.
Create Backend Files:
Now you need to create few files which will setup your backend ready. Here are the steps you need to follow.
Create a file inside your backend folder and name this file as index.js
. In this file you need to set up the basic Express server and configure middleware (body parser, CORS). Also you need to provide your mongoDB urls to connect to it.
// index.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json()); // Parse incoming JSON data
// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB');
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
})
.catch(err => console.error('Error connecting to MongoDB:', err));
Code language: JavaScript (javascript)
don’t forget to replace the string 'mongodb://localhost/mydatabase'
with the appropriate MongoDB connection string for your setup.
Explanation:
- We import the necessary packages:
express
,mongoose
, andcors
. - We create an instance of the Express app.
- We set the port for the server to listen on (either from an environment variable or default to 5000).
- We use the
cors()
middleware to handle Cross-Origin Resource Sharing. - We use the
express.json()
middleware to parse JSON data in incoming requests. - We connect to MongoDB using the
mongoose.connect()
method. Adjust the connection URL as needed. - If the connection is successful, we start the server to listen on the specified port.
Initialize Frontend (React):
In the MERN Stack Application the front end is made with React.js rather then the Angular.js which is used in MEAN Stack application. Now we need to come out from the backend directory and need to create a new folder name the frontend. Inside this frontend
folder we need to start a new react application which we can do with this simple command from command prompt or windows power shell (which ever you prefer).
npx create-react-app client
This command will create a new directory name client inside your working directory, so if you do not want to wrap the code in frontend directory you can neglect that step and directory can use above command inside your mytodo folder and it will create the client folder inside the mytodo
folder. After the project is ready all you have to do is to navigate to this client directory by simply cd client
and once you are in, you need to install the npm packages. with npm install
command. Inside your front end you may need to create the appropriate components required for your project.
Connect React.js Front end to Node.js Backend
To interact with Node.js backend from the React.js front end you need to use axios
package to make backend requests or you may use the built in fetch
to call the api ends. If you’re running your frontend and backend on different ports during development, you can configure the proxy in the client/package.json
to avoid CORS issues.
Here is a simple node.js example code
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.get('/api/message', (req, res) => {
const message = 'Hello from the backend!';
res.json({ message });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Code language: PHP (php)
and once you are inside your react.js code you can call this “/api/message” route with this example code.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
// Using Fetch API
fetch('/api/message')
.then(response => response.json())
.then(data => setMessage(data.message))
.catch(error => console.error('Fetch Error:', error));
// Using Axios
axios.get('/api/message')
.then(response => setMessage(response.data.message))
.catch(error => console.error('Axios Error:', error));
}, []);
return (
<div className="App">
<h1>React and Node.js Integration</h1>
<p>Message from the backend: {message}</p>
</div>
);
}
export default App;
Code language: JavaScript (javascript)
How to run a MERN Stack Application
Now that you setup your MERN Stack application, here is how to run the application.
First of all go to your server code and run it with simply this command node index.js
. Once the server is running at http://localhost:5000
you can go to your front-end client folder and run the react application with simply this command npm start
this will start the react js application which would be accessible on the http://localhost:3000
url.