How to Build a Full-Stack App with MERN: A Step-by-Step Tutorial
The MERN stack (MongoDB, Express.js, React, Node.js) is a powerful, JavaScript-only set of technologies for building modern web applications. This tutorial walks you through creating a simple CRUD app, from backend API to frontend UI. By the end, you’ll have a functional full-stack application running locally.
1. Set Up the Backend with Node.js and Express
Start by initializing a new Node project. Create a folder named server and run npm init -y. Install the core dependencies:
- express – for routing and middleware
- mongoose – to connect and interact with MongoDB
- cors – to allow cross-origin requests from React
- dotenv – to manage environment variables
Create an index.js file, import Express, and set up a basic server listening on port 5000. Use mongoose.connect() to link to your local MongoDB instance, then define a simple schema (e.g., for a Task model with title and completed fields).
2. Build RESTful API Endpoints
With Express and Mongoose in place, create routes inside a routes folder. Use a router to define:
- GET /api/tasks – fetch all tasks
- POST /api/tasks – add a new task
- PUT /api/tasks/:id – update a task
- DELETE /api/tasks/:id – delete a task
Implement each route using Mongoose methods (e.g., Task.find(), Task.create()). Test your API with Postman or cURL before moving to the frontend.
3. Scaffold the React Frontend
Create a React app using create-react-app (or Vite) in a separate client folder. Install axios for HTTP requests. Build components:
- App.js – main wrapper with state and useEffect to fetch tasks
- TaskList.js – renders tasks from state
- TaskForm.js – input form to add new tasks
Use axios.get('http://localhost:5000/api/tasks') to load data on component mount, and similar calls for POST, PUT, DELETE.
4. Connect Frontend to Backend
Ensure CORS is enabled in your Express app (app.use(cors())). In React, proxy API requests to avoid CORS issues in development by adding "proxy":"http://localhost:5000" to your client’s package.json. Now your React app can call endpoints without full URLs.
Run both servers (backend on port 5000, frontend on port 3000) using separate terminals. The frontend will now display data from MongoDB, and you can create, update, and delete tasks in real time.
Conclusion
You’ve built a complete MERN stack app with a RESTful API and a reactive UI. This pattern can be extended with authentication, more complex schemas, or additional features. The key takeaway is how seamlessly JavaScript works across the full stack.