Building a fullstack Instagram clone with Next.js is a fantastic way to enhance your web development skills while creating a fully functional and visually appealing web application. In this tutorial, we will cover all the steps necessary to build a fullstack Instagram clone using Next.js, MongoDB, and Tailwind CSS.
Prerequisites:
Before starting this tutorial, make sure you have the following installed on your machine:
- Node.js
- MongoDB
- Git
- A text editor (such as Visual Studio Code)
- A basic understanding of JavaScript, React, and Next.js
Step 1: Setup a new Next.js project
To get started, create a new Next.js project by running the following commands in your terminal:
npx create-next-app instagram-clone
cd instagram-clone
Step 2: Install necessary dependencies
Next, install the required dependencies for our project. Run the following commands in your terminal:
npm install axios mongoose @tailwindcss/jit @headlessui/react
Step 3: Setup Tailwind CSS and Headless UI
Next, set up Tailwind CSS and Headless UI by creating a tailwind.config.js
file in the root of your project:
npx tailwindcss init -p
In your tailwind.config.js
file, add the following code to enable Just-In-Time mode:
module.exports = {
mode: 'jit',
purge: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
}
Step 4: Create a MongoDB database
Next, create a database for our project on MongoDB. You can use a cloud-based MongoDB service like MongoDB Atlas or run MongoDB locally on your machine.
Step 5: Set up the MongoDB connection
Create a .env.local
file in the root of your project and add your MongoDB connection URI:
MONGODB_URI=YOUR_MONGODB_CONNECTION_URI
Next, create a lib/db.js
file in your project and add the following code to establish a connection to your MongoDB database:
import mongoose from 'mongoose'
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('MongoDB Connected')
} catch (error) {
console.error(error)
process.exit(1)
}
}
export default connectDB
Step 6: Create the Post model
Create a models/Post.js
file in your project and define the Post model schema using Mongoose:
import mongoose from 'mongoose'
const PostSchema = new mongoose.Schema({
user: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
caption: {
type: String,
required: true,
},
likes: {
type: Number,
default: 0,
},
comments: [{
user: String,
text: String,
date: {
type: Date,
default: Date.now,
}
}]
})
const Post = mongoose.models.Post || mongoose.model('Post', PostSchema)
export default Post
Step 7: Create API routes
Next, create the necessary API routes to handle fetching and creating posts. Create a pages/api/posts/index.js
file in your project and add the following code:
import connectDB from '../../../lib/db'
import Post from '../../../models/Post'
connectDB()
export default async function handler(req, res) {
if (req.method === 'GET') {
const posts = await Post.find()
res.status(200).json(posts)
} else if (req.method === 'POST') {
const { user, image, caption } = req.body
const newPost = new Post({ user, image, caption })
await newPost.save()
res.status(201).json(newPost)
} else {
res.status(405).json({ error: 'Method Not Allowed' })
}
}
Step 8: Create the frontend components
Now that our backend is set up, it’s time to create the frontend components for our Instagram clone. Create a components/Post.js
file in your project and add the following code to create a Post component:
import { HeartIcon, ChatIcon } from '@heroicons/react/24'
const Post = ({ post }) => {
return (
<div className="bg-white shadow-md rounded-lg p-4 space-y-2">
<img src={post.image} alt="Post" className="w-full h-auto rounded-t-lg" />
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold">{post.user}</h3>
<p className="text-gray-500">{post.caption}</p>
</div>
<div className="space-x-2">
<HeartIcon className="h-6 w-6 text-red-500" />
<ChatIcon className="h-6 w-6 text-blue-500" />
</div>
</div>
</div>
)
}
export default Post
Step 9: Create the homepage
Create a pages/index.js
file in your project and add the following code to create the homepage:
import { useEffect, useState } from 'react'
import axios from 'axios'
import Post from '../components/Post'
const Home = () => {
const [posts, setPosts] = useState([])
useEffect(() => {
const getPosts = async () => {
const res = await axios.get('/api/posts')
setPosts(res.data)
}
getPosts()
}, [])
return (
<div className="max-w-2xl mx-auto mt-4">
{posts.map(post => (
<Post key={post._id} post={post} />
))}
</div>
)
}
export default Home
Step 10: Run your application
Finally, run your Next.js application by running the following command in your terminal:
npm run dev
Your fullstack Instagram clone should now be up and running. Feel free to customize and extend the functionality of your application further by adding features like user authentication, image uploads, comments, and likes.
Congratulations on building a fullstack Instagram clone with Next.js! You now have a solid understanding of how to create a modern web application using React, Next.js, MongoDB, and Tailwind CSS. Keep experimenting and improving your project to further enhance your web development skills. Happy coding!
Bro in which editor do you write all these code
I have seen your playlist of full stack web development
Thank you david!
Hi Dawid! I LOVE YOUR VIDEO.. but im STUCK on your BOOKING APP.. about the SAMESITE WARNING ON COOKIES.. When you manually changed the "localhost" to [axios.defaults.baseURL = "http:// 127. 0. 0. 1: 4000/]" This does not work.. your github update "import.meta.env.VITE_API_BASE_URL;" also not working
For 3 days I have been stuck at this level in the (routes)/create part. Here is what I receive as a message: An empty string ("") was passed to the src attribute.
,how to overcome this part?
What database do you use for this project? Thanks
Thank you, Dawid. I always follow your content to learn regularly whenever you've published new video😊
Next level content enjoying very much ❤❤❤
Please create afull stack e commerce in next 14 15 good to go
When are you planning to make micro frontend application?
excellent sir
Someone remind me in an hour.
turborepo ?
Which code editor ? also which theme ?
you are perfect
AWS has changed appreciate if you can do a video on CRUD with AWS lambda and dynmoDB
wow!! Amazing.
Do you have any react js course
will this project cover basic concepts of next js or i need know next js already ??
Looking forward to starting this one! 💪
Amazing and amazing 🎉🎉.. but no nested comments on specific post feature?😢
What amazing projects you build! ❤ I'm always thankful to you because I learn something new from each of your projects, brother. 🙏
Why code quality is low? There no transactions, a lot queries for one post,useEffect that watched file changes
???