Shubham Goyal
MERN Blog App Tutorial
Likes: 0Views: 0
Date: 21st May 2025
Author: undefined undefined

๐Ÿ‘‹ Hey there!

Ever wondered how to build a full-stack blog app from scratch using MERN? You're in the right place! Grab a coffee, let's code together.

I'm super excited to walk you through one of my favorite projects โ€” a simple yet powerful blog app built using the MERN stack: MongoDB, Express.js, React, and Node.js. Whether you're just starting out or brushing up on full-stack dev skills, this one's for you.

๐Ÿ› ๏ธ Tech We'll Use

  • MongoDB โ€“ to store our blog posts
  • Express.js โ€“ to handle API routes
  • React โ€“ to build the UI
  • Node.js โ€“ to run our backend
  • Mongoose โ€“ for easier MongoDB queries
  • Axios โ€“ to connect frontend with backend

๐Ÿง  What We're Building

  • A blog app where users can:
  • ๐Ÿ“ View all blog posts
  • โž• Add a new blog post
  • ๐Ÿงน (Coming soon) Edit/Delete posts
  • You'll be amazed how much you can build with just a few tools. Let's dive in!

Lets Get Started

    ๐Ÿ”ง Step 1: Setting Up the Backend (Node.js + Express)

    ๐Ÿ“ Create a backend folder

      bash
      mkdir backend && cd backend
      npm init -y
      npm install express mongoose cors dotenv

      ๐Ÿ› ๏ธ Create a basic Express server

      Create a new file: index.js and add the following code:

        javascript
        const express = require('express');
        const mongoose = require('mongoose');
        const cors = require('cors');
        require('dotenv').config();
        
        const app = express();
        app.use(cors());
        app.use(express.json());
        
        mongoose.connect(process.env.MONGO_URI)
          .then(() => console.log("โœ… MongoDB connected"))
          .catch(err => console.error(err));
        
        app.get('/', (req, res) => res.send('API is working!'));
        
        app.listen(5000, () => console.log("๐Ÿš€ Server running on http://localhost:5000"));
        

        ๐Ÿ“Œ Don't forget your .env file

          bash
          MONGO_URI=mongodb://localhost:27017/blogapp
          PORT=5000

          ๐Ÿ“ฆ Step 2: Define the Blog Model

          Let's create a new file: models/Blog.js

            javascript
            const mongoose = require('mongoose');
            
            const BlogSchema = new mongoose.Schema({
              title: String,
              content: String,
              author: String,
              createdAt: {
                type: Date,
                default: Date.now
              }
            });
            
            module.exports = mongoose.model('Blog', BlogSchema);
            

            ๐Ÿงญ Step 3: Build the Blog Routes

            New file: routes/blogs.js

              javascript
              const express = require('express');
              const Blog = require('../models/Blog');
              const router = express.Router();
              
              router.get('/', async (req, res) => {
                const blogs = await Blog.find();
                res.json(blogs);
              });
              
              router.post('/', async (req, res) => {
                const newBlog = new Blog(req.body);
                const saved = await newBlog.save();
                res.json(saved);
              });
              
              module.exports = router;
              

              Import the route in index.js

                javascript
                const blogRoutes = require('./routes/blogs');
                app.use('/api/blogs', blogRoutes);

                ๐ŸŒˆ Step 4: Time for the Frontend (React)

                ๐Ÿ“ Create the frontend folder

                  javascript
                  npx create-react-app frontend
                  cd frontend
                  npm install axios

                  ๐Ÿ–ผ๏ธ Show all blog posts

                  Edit App.js

                    javascript
                    import { useEffect, useState } from 'react';
                    import axios from 'axios';
                    
                    function App() {
                      const [blogs, setBlogs] = useState([]);
                    
                      useEffect(() => {
                        axios.get('http://localhost:5000/api/blogs')
                          .then(res => setBlogs(res.data))
                          .catch(err => console.log(err));
                      }, []);
                    
                      return (
                        <div style={{ padding: '2rem' }}>
                          <h1>๐Ÿ“ My Blog</h1>
                          {blogs.map(blog => (
                            <div key={blog._id} style={{ margin: '1rem 0', padding: '1rem', border: '1px solid #ddd' }}>
                              <h2>{blog.title}</h2>
                              <p>{blog.content}</p>
                              <p><strong>~ {blog.author}</strong></p>
                            </div>
                          ))}
                        </div>
                      );
                    }
                    
                    export default App;
                    

                    โž• Step 5: Add a New Blog Post

                    Let's create a form! Add this inside your App.js or as a new component:

                      javascript
                      function AddBlog({ onAdd }) {
                        const [title, setTitle] = useState('');
                        const [content, setContent] = useState('');
                        const [author, setAuthor] = useState('');
                      
                        const submit = (e) => {
                          e.preventDefault();
                          axios.post('http://localhost:5000/api/blogs', { title, content, author })
                            .then(res => {
                              onAdd(res.data);
                              setTitle('');
                              setContent('');
                              setAuthor('');
                            });
                        };
                      
                        return (
                          <form onSubmit={submit} style={{ marginBottom: '2rem' }}>
                            <input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} /><br />
                            <input placeholder="Author" value={author} onChange={e => setAuthor(e.target.value)} /><br />
                            <textarea placeholder="Content" value={content} onChange={e => setContent(e.target.value)} /><br />
                            <button type="submit">Add Blog</button>
                          </form>
                        );
                      }
                      

                      Then in your App.js, include it like this:

                        javascript
                        <AddBlog onAdd={(blog) => setBlogs([blog, ...blogs])} />

                        ๐Ÿง  Key Things You Learned

                        • โœ… How to set up Express server
                        • โœ… Create & connect MongoDB with Mongoose
                        • โœ… Build REST APIs for blog posts
                        • โœ… Create a React frontend & connect it to backend
                        • โœ… Add a real blog post form
                        • โœ… Full MERN magic โœจ

                        Responses (0)

                        Write your response here
                        Shubham Goyal
                        Shubham Goyal.All Rights Reserved