How to Create Your First MERN Stack App

 The MERN stack—MongoDB, Express.js, React.js, and Node.js—is one of the most popular JavaScript-based tech stacks for building full-stack web applications. It allows developers to use a single language (JavaScript) across both frontend and backend, making development fast and efficient. In this blog, we'll walk through how to create your first MERN stack app step by step.

Set Up the Backend (Node.js + Express)

Initialize a Node project:

bash

Copy

Edit

mkdir mern-app

cd mern-app

npm init -y

Install dependencies:

bash

Copy

Edit

npm install express mongoose cors dotenv

Create the basic server (server.js):

javascript

Copy

Edit

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

const app = express();

require('dotenv').config();

app.use(cors());

app.use(express.json());

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

Create a simple API:

Define a route like /api/message that returns a welcome message.

Set Up MongoDB

Use MongoDB Atlas or your local MongoDB server. Create a new database and collection. Connect the URI in your .env file like this:

bash

Copy

Edit

MONGO_URI=mongodb+srv://yourusername:yourpassword@cluster.mongodb.net/mernapp

Step 3: Set Up the Frontend (React.js)

Create the React app:

bash

Copy

Edit

npx create-react-app client

cd client

Install Axios for API calls:

bash

Copy

Edit

npm install axios

Make a request to the backend:

In App.js, fetch data using Axios:

javascript

Copy

Edit

import React, { useEffect, useState } from 'react';

import axios from 'axios';

function App() {

  const [message, setMessage] = useState('');

  useEffect(() => {

    axios.get('http://localhost:5000/api/message')

      .then(res => setMessage(res.data))

      .catch(err => console.log(err));

  }, []);

  return <h1>{message}</h1>;

}

export default App;

Step 4: Run the App

Start the backend:

bash

Copy

Edit

node server.js

Start the frontend:

cd client

npm start

Conclusion

Congratulations! You’ve just created your first MERN stack app with a backend API and a React frontend. As you grow, you can add features like user authentication, form handling, and data validation to make your app production-ready.

Learn MERN Stack Training Course

Read More:

Top 10 Projects to Build Using the MERN Stack

How MongoDB Powers Scalable Web Applications

Exploring the Basics of Express.js for Beginners

Visit Quality Thought Training Institute

Get Direction

Comments

Popular posts from this blog

Regression Analysis in Python

Top 10 Projects to Build Using the MERN Stack