DEV Community

Dougie Hawes
Dougie Hawes

Posted on

Build a MERN stack app (without over complicating it)

Setting Up a Basic MERN Stack Project

This guide aligns with an upcoming video on my YouTube channel, where I'll walk through setting up a basic MERN stack project from scratch. Let's get started!

1. Initialize the Project

Start by creating a project directory and navigating into it:

mkdir mern-app && cd mern-app
Enter fullscreen mode Exit fullscreen mode

2. Set Up the Backend (Express + Node.js)

Create a backend folder and initialize a Node.js project:

mkdir backend && cd backend
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install necessary dependencies:

npm install express cors dotenv
Enter fullscreen mode Exit fullscreen mode

Create an index.js file in the backend directory and add:

const express = require("express");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());

app.get("/api", (req, res) => {
  res.json({ message: "Hello World!" });
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

3. Set Up the Frontend (React)

Go back to the root directory and create a React app:

cd ..
npx create-react-app frontend
Enter fullscreen mode Exit fullscreen mode

Navigate into the frontend directory and install Axios to handle API requests:

cd frontend
npm install axios
Enter fullscreen mode Exit fullscreen mode

Replace the contents of src/App.js with:

import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    axios.get("http://localhost:5000/api").then((res) => {
      setMessage(res.data.message);
    });
  }, []);

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

export default App;
Enter fullscreen mode Exit fullscreen mode

4. Run Both Frontend and Backend Simultaneously

Install concurrently in the root directory:

cd ..
npm install concurrently --save-dev
Enter fullscreen mode Exit fullscreen mode

Modify package.json in the root directory to include a start script:

"scripts": {
  "start": "concurrently \"cd backend && node index.js\" \"cd frontend && npm start\""
}
Enter fullscreen mode Exit fullscreen mode

Now, run the entire project with:

npm start
Enter fullscreen mode Exit fullscreen mode

Your backend will serve "Hello World!" to the frontend, which will display it in an <h1> tag. Stay tuned for the video where I demonstrate this process in action! 🚀

mern #react #node #express #webdevelopment #javascript #fullstack #tutorial #coding #programming

Top comments (0)