Social Media Platform using MERN Stack
Last Updated :
23 Jul, 2025
In web development, creating a "Social Media Website" will showcase and utilising the power of MERN stack – MongoDB, Express, React, and Node. This application will provide users the functionality to add a post, like the post and able to comment on it.
Preview Image: Let us have a look at how the final output will look like.

Prerequisites:
Approach to create Social Media Platform:
- The social media website was developed with a dual focus on backend using Express.js and frontend using React.
- Express handled API routes for CRUD operations, including likes and comments, and Multer facilitated file uploads for multimedia content.
- React was chosen for the frontend, providing an interactive user interface with components for posts, likes, and comments.
- Axios played a pivotal role in connecting the frontend to the backend API endpoints, ensuring smooth communication.
- The integration phase involved configuring CORS, connecting frontend to backend API URLs, and thorough end-to-end testing for a seamless user experience.
Steps to Create the Project:
Step 1: Create a directory for the backend by running the following command.
npm init social_backend
cd social_backend
Step 2: Initialize the Express project and install the following dependencies.
npm init -y
npm install express mongoose cors body-parser multer uuid
Folder Structure(Backend):

The updated dependencies in package.json file of backend will look like:
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^8.0.3",
"multer": "^1.4.5-lts.1",
"uuid": "^9.0.1"
}
Example: Create the required files and add the following code:
JavaScript
// models/Post.js
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: String,
content: String,
likes: { type: Number, default: 0 },
comments: [{ text: String }],
});
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
JavaScript
// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
mongoose.connect('Your MongoDB connection string', { useNewUrlParser: true, useUnifiedTopology: true });
const postSchema = new mongoose.Schema({
title: String,
content: String,
file: String,
likes: { type: Number, default: 0 },
comments: [{ text: String }],
});
const Post = mongoose.model('Post', postSchema);
app.use(bodyParser.json());
app.get('/api/posts', async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/posts', upload.single('file'), async (req, res) => {
try {
const { title, content } = req.body;
const file = req.file ? req.file.filename : undefined;
if (!title || !content) {
return res.status(400).json({ error: 'Title and content are required fields' });
}
const post = new Post({ title, content, file });
await post.save();
res.status(201).json(post);
} catch (error) {
console.error('Error creating post:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/posts/like/:postId', async (req, res) => {
try {
const postId = req.params.postId;
const post = await Post.findById(postId);
if (!post) {
return res.status(404).json({ error: 'Post not found' });
}
post.likes += 1;
await post.save();
res.json(post);
} catch (error) {
console.error('Error liking post:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/posts/comment/:postId', async (req, res) => {
try {
const postId = req.params.postId;
const { text } = req.body;
const post = await Post.findById(postId);
if (!post) {
return res.status(404).json({ error: 'Post not found' });
}
post.comments.push({ text });
await post.save();
res.json(post);
} catch (error) {
console.error('Error adding comment:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 3: To start the backend run the following command.
node server.js
Step 4: Set up React frontend using the command.
npx create-react-app social_frontend
cd social_frontend
Step 5 : Installing the required packages:
npm i axios react-router-dom
Folder Structure(Frontend):

The updated dependencies in package.json file of frontend will look lik:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: Create the required files and the following code.
CSS
/* App.css */
.home {
max-width: 800px;
margin: 0 auto;
}
.post {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 20px;
}
.post h3 {
color: #333;
}
.post p {
color: #555;
}
/* App.css */
.create-post {
max-width: 600px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ddd;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.create-post h2 {
color: #333;
}
.create-post input,
.create-post textarea {
width: 100%;
margin: 10px 0;
padding: 10px;
}
.create-post button {
background-color: #4caf50;
color: #fff;
padding: 10px 15px;
border: none;
cursor: pointer;
}
.comment-input {
margin-top: 10px;
padding: 8px;
width: 70%;
}
.comment-button {
background-color: #4caf50;
color: #fff;
padding: 8px 16px;
border: none;
cursor: pointer;
}
.post img,
.post video {
max-width: 100%;
height: auto;
margin-top: 10px;
}
.post button {
background-color: #4caf50;
color: #fff;
padding: 8px 16px;
border: none;
cursor: pointer;
margin-right: 10px;
}
.post ul {
list-style: none;
padding: 0;
}
.post li {
margin-bottom: 5px;
}
.comment-input {
margin-top: 10px;
padding: 8px;
width: 70%;
}
.comment-button {
background-color: #4caf50;
color: #fff;
padding: 8px 16px;
border: none;
cursor: pointer;
}
/* App.css */
.app {
max-width: 800px;
margin: 0 auto;
}
nav {
background-color: #333;
padding: 10px;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
}
nav li {
display: inline-block;
margin-right: 20px;
}
nav a {
text-decoration: none;
color: #fff;
font-weight: bold;
font-size: 16px;
}
nav a:hover {
color: #4caf50;
}
.create-post,
.home {
border: 1px solid #ddd;
padding: 20px;
margin-bottom: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.home h2,
.create-post h2 {
color: #333;
}
.home .post,
.create-post {
margin-bottom: 30px;
}
.home .post button,
.create-post button {
background-color: #4caf50;
color: #fff;
padding: 10px 15px;
border: none;
cursor: pointer;
}
.home .post button:hover,
.create-post button:hover {
background-color: #45a049;
}
JavaScript
// App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import CreatePost from './CreatePost';
import './App.css';
function App() {
return (
<Router>
<div className="app">
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/create">Create Post</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/create" element={<CreatePost />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</Router>
);
}
export default App;
JavaScript
// Home.js
import React, { useState, useEffect } from "react";
import axios from "axios";
function Home() {
const [commentInput, setCommentInput] = useState("");
const [posts, setPosts] = useState([]);
useEffect(() => {
axios
.get("http://localhost:5000/api/posts")
.then((response) => setPosts(response.data))
.catch((error) => console.error("Error fetching posts:", error));
}, []);
const handleLike = (postId) => {
axios
.post(`http://localhost:5000/api/posts/like/${postId}`)
.then((response) => {
const updatedPosts = posts.map((post) =>
post._id === postId ? response.data : post
);
setPosts(updatedPosts);
})
.catch((error) => console.error("Error liking post:", error));
};
const handleAddComment = (postId, commentText) => {
axios
.post(`http://localhost:5000/api/posts/comment/${postId}`, {
text: commentText,
})
.then((response) => {
const updatedPosts = posts.map((post) =>
post._id === postId ? response.data : post
);
setPosts(updatedPosts);
})
.catch((error) => console.error("Error adding comment:", error));
};
return (
<div className="home">
<h2>Recent Posts</h2>
{posts.map((post) => (
<div key={post._id} className="post">
<h3>{post.title}</h3>
<p>{post.content}</p>
{post.file && (
<div>
{post.file.includes(".mp4") ? (
<video width="320" height="240" controls>
<source
src={
`http://localhost:5000/uploads/${post.file}`
}
type="video/mp4"
/>
Your browser does not support the video tag.
</video>
) : (
<img
src={
`http://localhost:5000/uploads/${post.file}`
}
alt="Post Media"
/>
)}
</div>
)}
<p>Likes: {post.likes}</p>
<button onClick={() => handleLike(post._id)}>Like</button>
<p>Comments: {post.comments.length}</p>
<ul>
{post.comments.map((comment, index) => (
<li key={index}>{comment.text}</li>
))}
</ul>
<input
type="text"
placeholder="Add a comment"
className="comment-input"
onChange={(e) => setCommentInput(e.target.value)}
/>
<button
onClick={() => handleAddComment(post._id, commentInput)}
className="comment-button"
>
Add Comment
</button>
</div>
))}
</div>
);
}
export default Home;
JavaScript
// CreatePost.js
import React, { useState } from "react";
import axios from "axios";
function CreatePost() {
const [newPost, setNewPost] = useState({
title: "",
content: "",
file: null,
});
const handleInputChange = (event) => {
const { name, value } = event.target;
setNewPost({ ...newPost, [name]: value });
};
const handleFileChange = (event) => {
setNewPost({ ...newPost, file: event.target.files[0] });
};
const handlePostSubmit = () => {
const formData = new FormData();
formData.append("title", newPost.title);
formData.append("content", newPost.content);
formData.append("file", newPost.file);
axios
.post("http://localhost:5000/api/posts", formData)
.then((response) => {
setNewPost({ title: "", content: "", file: null });
})
.catch((error) => console.error("Error creating post:", error));
};
return (
<div className="create-post">
<h2>Create a Post</h2>
<input
type="text"
name="title"
placeholder="Title"
value={newPost.title}
onChange={handleInputChange}
/>
<textarea
name="content"
placeholder="Content"
value={newPost.content}
onChange={handleInputChange}
></textarea>
<input type="file" name="file" onChange={handleFileChange} />
<button onClick={handlePostSubmit}>Post</button>
</div>
);
}
export default CreatePost;
Step 6: Start the application by running the following command.
npm start
Output:
Similar Reads
MERN Stack The MERN stack is a widely adopted full-stack development framework that simplifies the creation of modern web applications. Using JavaScript for both the frontend and backend enables developers to efficiently build robust, scalable, and dynamic applications.What is MERN Stack?MERN Stack is a JavaSc
9 min read
MERN Full Form MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications. The full form of MERN includes four powerful technologies:MongoDBExpress.jsReact.jsNode.jsThese technologies together provide a full-stack JavaScript framework for developing modern, dynami
2 min read
How to Become a MERN Stack Developer? Do you also get amazed at those beautiful websites that appear in front of you? Those are designed by none other than Full-Stack Developers Or MERN stack developers. They are software developers who specialize in building web applications using the MERN stack, which is a popular set of technologies
6 min read
Difference between MEAN Stack and MERN Stack Web development is a procedure or process for developing a website. A website basically contains three ends: the client side, the server side, and the database. These three are different sides of an application that combine together to deliver an application; all ends are implemented separately with
3 min read
Best Hosting Platforms for MERN Projects Hosting your website grants you the thrilling opportunity to showcase it to the world. Whether you choose free or paid hosting, the process of deploying your website fills you with a mix of excitement, pride, and nervousness. You eagerly await user feedback, enthusiastically embracing the chance to
5 min read
Getting Started with React & Frontend
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Props - Set 1The react props refer to properties in react that are passed down from parent component to child to render the dynamic content.Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component.What are Prop
5 min read
ReactJS StateIn React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
Create ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list allows users to add new tasks and delete them by clicking the corresponding
3 min read
Redux Setup and basics
Introduction to Redux (Action, Reducers and Store)Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.Uses: It makes easier to manage state and data. As the complexity of our application in
4 min read
Redux and The Flux ArchitectureFlux Architecture: Flux is AN architecture that Facebook uses internally when operating with React. It is not a framework or a library. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow. Redux is a predictable state container for JavaS
5 min read
React Redux Hooks: useSelector and useDispatch.State management is a major aspect of building React applications, allowing users to maintain and update application state predictably. With the introduction of React Hooks, managing state has become even more streamlined and efficient. Among the most commonly used hooks for state management in Reac
4 min read
What are Action's creators in React Redux?In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects.Action C
4 min read
What is Redux Thunk?Redux Thunk is like a co-worker for Redux, giving it the power to handle asynchronous actions. It's that extra tool that allows your Redux store to deal with things like fetching data from a server or performing tasks that take some time. With Redux Thunk, your app can smoothly manage both synchrono
3 min read
Creating custom middlewares in React ReduxIn React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
5 min read
Common middleware libraries used in ReduxMiddleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
5 min read
Express and Mongo Setup
Mongo with Express TutorialMongoDB and ExpressJS are a powerful pair for web development. MongoDB provides flexible data storage, while ExpressJS simplifies server-side logic. Together, they make it easy to create modern web applications efficiently. MongoDB's document-based approach and ExpressJS's streamlined backend develo
5 min read
How to Install MongoDB on Windows?Looking to install MongoDB on your Windows machine? This detailed guide will help you install MongoDB on Windows (Windows Server 2022, 2019, and Windows 11) quickly and efficiently. Whether you are a developer or a beginner, follow this guide for seamless MongoDB installation, including setting up e
6 min read
How to Install Express in a Node Project?ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services.Be
2 min read
Mongoose Module IntroductionMongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and structured way to interact with MongoDB, allowing you to define schemas for your collections, apply constraints, and validate data before storing it in the database. In this guide, we'
5 min read
Mongoose ConnectionsA Mongoose connection is a Node.js module that establishes and manages connections between a Node.js application and a MongoDB database. It optimizes resource utilization, handles connection pooling, and manages errors, facilitating efficient data operations.What is Mongoose Connection?A Mongoose co
6 min read
How to Connect MongoDB with a Node.js Application using MongooseJSMongoose is a powerful MongoDB object modeling library for Node.js enabling you to easily interact between your Node.js app and MongoDB. In this article we are going to explore how you can connect your Node.js app to MongoDB using MongooseJS. You will learn how to create a connection, specify schema
4 min read
Node.js CRUD Operations Using Mongoose and MongoDB AtlasCRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
8 min read
Signup Form Using Node.js and MongoDBInstallations First, we need to include a few packages for our Nodejs application. npm install express --save Express allows us to set up middlewares to respond to HTTP Requests. npm install body-parser --save If you want to read HTTP POST data , you have to use the "body-parser" node module. npm in
3 min read
API Routing and Authentication
Postman- Backend Testing
Introduction to Postman for API DevelopmentPostman: Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development eas
7 min read
Basics of API Testing Using PostmanAPIs(Application Programming Interfaces) are very commonly used in development. Postman is a tool that can be used for API Testing. In this article, we will learn how to do simple API Testing using Postman. Go to your workspace in Postman.Click on the + symbol to open a new tab.Enter the API Endpoin
2 min read
How to use postman for testing express applicationTesting an Express app is very important to ensure its capability and reliability in different use cases. There are many options available like Thunder client, PAW, etc but we will use Postman here for the testing of the Express application. It provides a great user interface and numerous tools whic
3 min read
How to send different types of requests (GET, POST, PUT, DELETE) in Postman.In this article, we are going to learn how can we send different types of requests like GET, POST, PUT, and DELETE in the Postman. Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge betwe
5 min read
How to test GET Method of express with Postman ?The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can't change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In thi
2 min read
How to test POST Method of Express with Postman?The POST method is a crucial aspect of web development, allowing clients to send data to the server for processing. In the context of Express, a popular web framework for Node, using the POST method involves setting up routes to handle incoming data. In this article, we'll explore how to test the PO
2 min read
How to test DELETE Method of Express with Postman ?The DELETE method is an essential part of RESTful web services used to remove specific resources from a server. Whether you are building a simple API or a complex web application, knowing how to use this method effectively is key. Here, we will explore how to Implement the DELETE method in Express.j
3 min read
How to create and write tests for API requests in Postman?Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
3 min read