Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
URL Shortener Service with NextJS
Next article icon

Social Networking Platform using Next.js

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Social Networking Platform built with NextJS is a web application that provides users the functionality to add a post, like a post, and be able to comment on it. The power of NextJS, a popular React framework for building server-side rendered (SSR) and statically generated web applications, this platform offers a seamless user experience with fast loading times and smooth navigation.

Output Preview: Let us have a look at how the final output will look like

Screenshot-2024-03-20-000330

Prerequisites:

  • NPM & NodeJS
  • NextJS
  • ReactJS
  • MongoDB

Approach to Create Social Networking Platform with NextJS:

  • Home Page: Displays recent posts fetched from the backend API.
  • Post Interaction: Users can like posts and add comments.
  • Create Post: Users can create new posts with a title, content, and optional image upload.
  • Backend API: Provides endpoints for fetching recent posts, creating posts, liking posts, and adding comments. Uses MongoDB as the database.

Steps to Create the NextJS App:

Step 1: Set up a NextJS project using the following command.

npx create-next-app next-mern-project
cd next-mern-project

Step 2: Install required dependencies.

npm install axios mongoose 

Project Structure:

Screenshot-2024-03-19-235202

The updated dependencies in package.json file will look like:

 "dependencies": {
"axios": "^1.6.8",
"mongodb": "^6.5.0",
"mongoose": "^8.2.2",
"multer": "^1.4.5-lts.1",
"next": "14.1.3",
"next-connect": "^1.0.0",
"react": "^18",
"react-dom": "^18",
"uuid": "^9.0.1"
}

Step 3: Creating a required files.

  • Create components folder with Post.js
  • Inside api create file posts.js
  • inside pages create file _app.js,index.js and create.js
  • create globals.css inside style folder

Example: Below is an example of creating a Social Networking Platform with NextJS.

CSS
/* globals.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
//pages/index.js import React, { useState, useEffect } from 'react'; import axios from 'axios';  function Home() {     const [posts, setPosts] = useState([]);     const [commentText, setCommentText] = useState('');      useEffect(() => {         axios             .get('/api/posts')             .then((response) => setPosts(response.data))             .catch((error) => console.error(                 'Error fetching posts:', error));     }, []);      const handleLike = async (id) => {         try {             const response = await axios.put('/api/posts', {                 id, action: 'like'             });             setPosts(posts.map(                 (post) => (post._id === id ? response.data : post)));         } catch (error) {             console.error('Error liking post:', error);         }     };      const handleComment = async (id, text) => {         try {             const response = await axios.put('/api/posts', {                 id, action: 'comment', text             });             setPosts(posts.map(                 (post) => (post._id === id ? response.data : post)));             setCommentText(''); // Reset comment text after posting         } catch (error) {             console.error('Error commenting on post:', error);         }     };      const convertImageToBase64 = async (file) => {         return new Promise((resolve, reject) => {             const reader = new FileReader();             reader.readAsDataURL(file);             reader.onload = () => resolve(reader.result);             reader.onerror = (error) => reject(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>                             <img src={post.file} alt="Post" />                         </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>                     <div>                         <input type="text" placeholder="Write a comment..."                             value={commentText}                             onChange={(e) => setCommentText(e.target.value)} />                         <button                             onClick={() => handleComment(post._id, commentText)}>                             Comment                         </button>                     </div>                 </div>             ))}         </div>     ); }  export default Home; 
JavaScript
// pages/_app.js  import '../styles/globals.css'; import React from 'react'; import { useRouter } from 'next/router';  function MyApp({ Component, pageProps }) {     const router = useRouter();      return (         <div className="app">             <nav>                 <ul>                     <li>                         <button onClick={() => router.push('/')}>                             Home                         </button>                     </li>                     <li>                         <button onClick={() => router.push('/create')}>                             Create Post                         </button>                     </li>                 </ul>             </nav>             <Component {...pageProps} />         </div>     ); }  export default MyApp; 
JavaScript
// pages/create.js  import React, { useState } from 'react'; import axios from 'axios';  function CreatePost() {     const [newPost, setNewPost] = useState({         title: '',         content: '',         file: null     });     const [error, setError] = useState('');      const handleInputChange = event => {         const { name, value } = event.target;         setNewPost({ ...newPost, [name]: value });     };      const handleFileChange = event => {         setNewPost({             ...newPost,             file: event.target.files[0]         });     };      const handlePostSubmit = async () => {         try {             const { title, content, file } = newPost;              if (!title || !content) {                 setError('Title and content are required fields.');                 return;             }              const postData = { title, content };              const response = await axios.post('/api/posts',                 postData);             console.log('Post created:', response.data);             setNewPost({ title: '', content: '', file: null });             setError('');         } catch (error) {             console.error('Error creating post:', error);             setError('Error creating post. Please try again.');         }     };       return (         <div className="create-post">             <h2>Create a Post</h2>             {error && <p style={{ color: 'red' }}>{error}</p>}             <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"                 accept="image/*" onChange={handleFileChange} />             <button onClick={handlePostSubmit}>                 Post             </button>         </div>     ); }  export default CreatePost; 
JavaScript
//pages/api/posts.js import mongoose from 'mongoose';  // MongoDB connection URI const MONGODB_URI = 'Your Mongo Database URL Here';  // Connect to MongoDB mongoose.connect(MONGODB_URI, {     useNewUrlParser: true,     useUnifiedTopology: true });  // Define post schema const postSchema = new mongoose.Schema({     title: String,     content: String,     file: String,     likes: { type: Number, default: 0 },     comments: [{ text: String }] });  // Define Post model const Post = mongoose.models.Post || mongoose.model('Post', postSchema);  // Export API handler export default async function handler(req, res) {     if (req.method === 'GET') {         try {             const posts = await Post.find();             res.status(200).json(posts);         } catch (error) {             res.status(500).json({                 error: 'Internal Server Error'             });         }     } else if (req.method === 'POST') {         try {             const { title, content, file } = req.body;              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'             });         }     } else if (req.method === 'PUT') {         try {             const { id, action } = req.body;              if (!id || !action) {                 return res.status(400).json({                     error: 'Post ID and action are required'                 });             }              let updatedPost;              if (action === 'like') {                 updatedPost = await Post.findByIdAndUpdate(id,                     { $inc: { likes: 1 } }, { new: true });             } else if (action === 'comment') {                 const { text } = req.body;                 if (!text) {                     return res.status(400).json({                         error: 'Comment text is required'                     });                 }                 updatedPost = await Post.findByIdAndUpdate(id,                     { $push: { comments: { text } } }, { new: true });             } else {                 return res.status(400).json({                     error: 'Invalid action'                 });             }              res.status(200).json(updatedPost);         } catch (error) {             console.error('Error updating post:', error);             res.status(500).json({                 error: 'Internal Server Error'             });         }     } else {         res.status(405).end(); // Method Not Allowed     } } 
JavaScript
// components/Post.js  import React, { useState } from 'react'; import axios from 'axios';  function Post({ post }) {     const [commentInput, setCommentInput] = useState('');      const handleLike = postId => {         axios.post(`/api/posts/like/${postId}`)             .then(response => {                 // Handle updated post data             })             .catch(                 error => console.error('Error liking post:', error));     };      const handleAddComment = (postId, commentText) => {         axios.post(`/api/posts/comment/${postId}`,             { text: commentText })             .then(response => {                 // Handle updated post data             })             .catch(                 error => console.error('Error adding comment:', error));     };      return (         <div className="post">             <h3>{post.title}</h3>             <p>{post.content}</p>             {post.file && (                 <div>                     <img src={`/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>     ); }  export default Post; 

Start your application using the following command.

npm run dev

Output:

aa

Database records:

Screenshot-2024-03-20-000736



Next Article
URL Shortener Service with NextJS

A

adityaan93uh
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Dev Scripter
  • Next.js
  • Web Development Projects
  • Dev Scripter 2024
  • Next.js - Projects

Similar Reads

  • Blogging Platform using Next JS
    In this project, we will explore the process of building The Blogging Platform with Next.js. Blogging Platform is a web application that allows users to create and publish blog posts. The platform provides a user-friendly interface for managing blog content and includes functionalities to create new
    5 min read
  • How to Create Todo App using Next.js ?
    In this article, we will create a to-do application and understand the basics of Next.js. This to-do list can add new tasks we can also delete the tasks by clicking on them. Next.js is a widely recognized React framework that e­nables server-side­ rendering and enhance­s the developme­nt of interact
    4 min read
  • Document Management System using NextJS
    The Document Management System is a web application developed using Next.js, that allows users to efficiently manage their documents. The system provides features for uploading, organizing, and retrieving documents. Users can upload documents through the web interface, which are then stored in local
    5 min read
  • Create a Quiz App with Next JS
    In this article, we’ll explore the process of building a Quiz App utilizing NextJS. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz. Outpu
    5 min read
  • E-commerce Dashboard with NextJS
    This project is an E-commerce Dashboard built with Next.js, providing features such as a dynamic sidebar, responsive navigation, order analytics, and most sold items of the week. It shows various features such as product analytics, order management, and user interaction. Output Preview: Prerequisite
    11 min read
  • Social Networking Platform using Next.js
    The Social Networking Platform built with NextJS is a web application that provides users the functionality to add a post, like a post, and be able to comment on it. The power of NextJS, a popular React framework for building server-side rendered (SSR) and statically generated web applications, this
    8 min read
  • URL Shortener Service with NextJS
    In this article, we will explore the process of building a URL shortener service using NextJS that takes a long URL and generates a shorter, more condensed version that redirects to the original URL when accessed. This shortened URL is typically much shorter and easier to share, especially in situat
    2 min read
  • Contact Us Form using Next.js
    Creating a Contact Us form in Next.js involves setting up a form component, handling form submissions, and potentially integrating with a backend service or API to send the form data. In this article, we will create a Contact Us Form with NextJS. Output Preview: Let’s have a look at what our final p
    6 min read
  • Blogging Platform using Next JS
    In this project, we will explore the process of building The Blogging Platform with Next.js. Blogging Platform is a web application that allows users to create and publish blog posts. The platform provides a user-friendly interface for managing blog content and includes functionalities to create new
    5 min read
  • Music Player App with Next.js and API
    In this tutorial, we'll create a Music Player App using NextJS, a React framework. Explore frontend development, API integration, and UI design to build a user-friendly app for seamless music enjoyment. Join us in harmonizing code and creativity to craft an engaging Music Player App with NextJS in t
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences