Instagram clone: photo feed, stories and explore
A photo-sharing app with profiles, follows, a home feed with infinite scroll, likes and comments, 24-hour stories, notifications and an explore page ranked by popularity.
Educational project inspired by Instagram. Skills101 is not affiliated with Instagram. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Feed design: fan-out on read vs on write
- ◆Cursor pagination and infinite scroll
- ◆Image processing and privacy (removing GPS data)
- ◆Ranking content by popularity and freshness
What you’ll build
- ✓Profiles with follow/unfollow and counts
- ✓Post up to 10 photos with captions and #hashtags
- ✓Home feed, likes (double-tap), comments
- ✓Stories that vanish after 24 hours, notifications, explore
Before you start
What you need
- •React/Next.js and SQL basics.
- •Node.js 20+, PostgreSQL; an S3-compatible bucket (AWS S3, Cloudflare R2, or MinIO locally in Docker).
- •Use your own photos or images with a free licence for demo accounts.
How it fits together
- 1Next.js pages and server actions; Prisma with PostgreSQL.
- 2Uploads are resized by sharp into a 1080px image and a thumbnail, then stored in object storage; the database stores only URLs.
- 3Home feed = posts from people you follow, newest first, read with a cursor (fan-out on read).
- 4Counts (likes, comments, followers) are stored on rows and updated in the same transaction as the change.
Project structure
pixgram/
├─ prisma/schema.prisma
├─ src/app/
│ ├─ page.tsx # home feed
│ ├─ [username]/page.tsx # profile grid
│ ├─ p/[id]/page.tsx # single post
│ ├─ create/page.tsx
│ ├─ stories/[username]/page.tsx
│ ├─ explore/page.tsx
│ └─ api/feed/route.ts # cursor pages
└─ src/lib/ (images, feed, likes, notify)Step-by-step guide
Step 1
Plan v1 and name your app
Goal: A clear feature list, your own brand and a list of screens.
v1: sign up with a username, edit profile, follow, create posts with 1–10 photos and a caption, home feed, like and comment, stories, notifications, explore. Later: reels, DMs, private accounts.
Screens: Feed, Profile (grid), Post, Create, Story viewer, Explore, Notifications. Mobile first: most users will open it on a phone.
Name it (“Pixgram”), use your own logo and colours. Add “Educational project inspired by Instagram. Not affiliated.” in the README.
✅ Check it works
You have phone-sized sketches of the 7 screens.
Step 2
Design the schema with counters
Goal: Users, follows, posts, likes, comments, stories and notifications, with fast counts.
Follow is a pair (followerId, followingId) with both as the primary key, so following twice is impossible. Like is (userId, postId), same idea.
Store
likeCount,commentCounton Post andfollowerCount,followingCounton User. Counting likes with COUNT(*) on every feed card is slow; a counter updated in the same transaction is instant and stays correct.Index
Post(authorId, createdAt)because the feed and profile grid both read “posts by these authors, newest first”.prisma/schema.prisma (core)model User { id String @id @default(cuid()) username String @unique name String bio String @default("") avatarUrl String? followerCount Int @default(0) followingCount Int @default(0) posts Post[] } model Follow { followerId String followingId String createdAt DateTime @default(now()) @@id([followerId, followingId]) @@index([followingId]) } model Post { id String @id @default(cuid()) authorId String author User @relation(fields: [authorId], references: [id]) caption String @default("") images PostImage[] likeCount Int @default(0) commentCount Int @default(0) createdAt DateTime @default(now()) @@index([authorId, createdAt]) @@index([createdAt]) } model Like { userId String postId String createdAt DateTime @default(now()) @@id([userId, postId]) } model Story { id String @id @default(cuid()) authorId String imageUrl String expiresAt DateTime createdAt DateTime @default(now()) @@index([authorId, expiresAt]) }✅ Check it works
Following the same user twice fails with a unique-constraint error (handle it as “already following”).
Step 3
Image upload pipeline with sharp
Goal: Uploaded photos are rotated correctly, resized, stripped of GPS data and stored in object storage.
Phone photos are huge (5–10 MB) and often stored sideways with an orientation flag.
sharp(buffer).rotate()applies that flag. Then make a 1080px-wide WebP for the post and a 320×320 cropped thumbnail for grids.Privacy: photos often contain the exact GPS location where they were taken. Sharp does not copy metadata to the output unless you ask it to, so the processed files are clean. Mention this in your README; it is a great interview point.
Upload results to the bucket with the AWS SDK (
PutObjectCommand) under random keys, and save the URLs. Limit uploads to 10 images of 15 MB each and check the file really is an image (sharp throws if it is not).src/lib/images.tsimport sharp from 'sharp' import { randomUUID } from 'node:crypto' import { PutObjectCommand } from '@aws-sdk/client-s3' import { s3, BUCKET, PUBLIC_URL } from './s3' export async function processUpload(input: Buffer) { const img = sharp(input, { limitInputPixels: 50_000_000 }).rotate() // fix orientation; metadata (GPS) is not copied const [full, thumb] = await Promise.all([ img.clone().resize({ width: 1080, withoutEnlargement: true }).webp({ quality: 80 }).toBuffer(), img.clone().resize(320, 320, { fit: 'cover' }).webp({ quality: 70 }).toBuffer(), ]) const key = randomUUID() await Promise.all([ s3.send(new PutObjectCommand({ Bucket: BUCKET, Key: key + '.webp', Body: full, ContentType: 'image/webp' })), s3.send(new PutObjectCommand({ Bucket: BUCKET, Key: key + '-t.webp', Body: thumb, ContentType: 'image/webp' })), ]) return { url: PUBLIC_URL + '/' + key + '.webp', thumbUrl: PUBLIC_URL + '/' + key + '-t.webp' } }✅ Check it works
Upload a phone photo taken in portrait: it appears upright, is under 300 KB, and an EXIF viewer finds no GPS data in the stored file.
Step 4
Profiles and following
Goal: Profile pages with a photo grid and counts, and a follow button that feels instant.
The profile page shows avatar, name, bio, posts/followers/following counts and a 3-column grid of thumbnails (cursor-paginated).
Follow and unfollow are server actions: in one transaction, create or delete the Follow row and increment or decrement both users' counters. Prevent following yourself.
Make the button optimistic: change it immediately with
useOptimistic, and roll back with a message if the server fails.✅ Check it works
Follow then unfollow quickly 5 times: counts end where they started.
Step 5
Build the home feed with cursor pagination
Goal: An infinite-scrolling feed of posts from people you follow, fast even with many posts.
Two ways to build feeds. Fan-out on write: when someone posts, insert it into every follower's feed table; reading is fast but a user with 1 million followers causes 1 million writes. Fan-out on read: when you open the app, query posts whose author you follow; writing is free, reading does more work. Big apps mix both. For this project, fan-out on read with a good index is right.
Use cursor pagination: “20 posts older than the last one I showed”. Sort by (createdAt, id) so ties are stable. Offset pagination (
skip: 200) gets slower and shows duplicates when new posts arrive.On the client, an IntersectionObserver on a sentinel near the bottom loads the next page.
src/lib/feed.tsexport async function feedPage(me: string, cursor?: string) { const following = await db.follow.findMany({ where: { followerId: me }, select: { followingId: true } }) const authors = [me, ...following.map((f) => f.followingId)] const posts = await db.post.findMany({ where: { authorId: { in: authors } }, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 21, // one extra tells us if there is a next page ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), include: { author: { select: { username: true, avatarUrl: true } }, images: true }, }) const liked = await db.like.findMany({ where: { userId: me, postId: { in: posts.map((p) => p.id) } }, select: { postId: true } }) const likedSet = new Set(liked.map((l) => l.postId)) return { posts: posts.slice(0, 20).map((p) => ({ ...p, likedByMe: likedSet.has(p.id) })), nextCursor: posts.length > 20 ? posts[19].id : null, } }✅ Check it works
Seed 500 posts: scrolling loads 20 at a time with no duplicates, and each page request takes under 100 ms locally.
Step 6
Likes and comments that stay consistent
Goal: Double-tap to like with a heart animation, and counts that never drift.
Toggle like in a transaction: try to delete the Like; if a row was deleted, decrement the counter; otherwise create it and increment. If two requests race and the create hits the unique constraint (Prisma error
P2002), treat it as already liked.Double-tap on the image likes (never unlikes) and plays a CSS heart animation; the heart button toggles.
Comments: max 500 characters, newest-first under the post with “View all 42 comments”. Increment
commentCountin the same transaction. Authors can delete comments on their posts.src/lib/likes.tsimport { Prisma } from '@prisma/client' export async function toggleLike(userId: string, postId: string) { try { return await db.$transaction(async (tx) => { const removed = await tx.like.deleteMany({ where: { userId, postId } }) if (removed.count) { await tx.post.update({ where: { id: postId }, data: { likeCount: { decrement: 1 } } }) return { liked: false } } await tx.like.create({ data: { userId, postId } }) await tx.post.update({ where: { id: postId }, data: { likeCount: { increment: 1 } } }) return { liked: true } }) } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return { liked: true } throw e } }✅ Check it works
Fire 10 like requests at once from a script: likeCount equals the number of Like rows afterwards.
Step 7
Stories that disappear after 24 hours
Goal: A row of story circles; tapping opens a full-screen viewer with progress bars.
A story has
expiresAt = createdAt + 24h. Every query filtersexpiresAt > now(), so expired stories vanish instantly without waiting for a cleanup job. A daily job deletes the old rows and their files.The story bar shows people you follow who have active stories; the ring is coloured if you have unseen stories (track views in a
StoryView(userId, storyId)table).The viewer: full screen, a progress bar per story, auto-advance every 5 seconds, tap right/left to skip, hold to pause. Preload the next image so it appears instantly.
✅ Check it works
Set a story's expiresAt to 1 minute from now: it disappears from the bar after a minute without any job running.
Step 8
Notifications
Goal: “Asha and 12 others liked your post” with an unread badge.
Create a notification row on like, comment and follow (skip actions on your own content). Store type, actor, target post and
readAt.Group on read: for the notifications page, group likes by post within the same day and show the latest actor plus “and N others”. This keeps writes simple and the page tidy.
The badge count is unread notifications; opening the page sets
readAt. Delete the like notification if the like is removed.✅ Check it works
3 friends like one post: you see one grouped notification, not three.
Step 9
Hashtags and an explore page
Goal: Clickable #tags and an explore grid of popular recent posts.
When saving a post, extract tags with a regex like
/#([\p{L}\p{N}_]{1,30})/gu(works for Hindi too), store them lowercased inTagandPostTag. Render tags in captions as links to/explore/tags/<tag>.Rank explore by popularity and freshness, the idea Hacker News uses: score = (likes + 2 × comments) ÷ (hours since posting + 2)^1.5. New posts with some engagement beat old posts with lots. Exclude accounts you already follow.
Compute it in SQL for posts from the last 7 days and cache the result for 5 minutes.
explore querySELECT p.id, (p."likeCount" + 2 * p."commentCount") / power(extract(epoch FROM now() - p."createdAt") / 3600 + 2, 1.5) AS score FROM "Post" p WHERE p."createdAt" > now() - interval '7 days' AND p."authorId" <> $1 AND p."authorId" NOT IN (SELECT "followingId" FROM "Follow" WHERE "followerId" = $1) ORDER BY score DESC LIMIT 30;✅ Check it works
A new post that gets 10 likes in an hour appears above a week-old post with 30 likes.
Step 10
Polish, safety and deployment
Goal: A fast, safe app live on the internet with demo accounts.
Performance:
next/imagewith sizes, blur placeholders from tiny thumbnails, and lazy loading below the fold. Check Lighthouse on mobile.Safety: block and report users (blocked users' posts and comments are hidden, and they cannot follow you), rate-limit posting and commenting, and limit caption length.
Deploy the app, the database and the bucket (with a CDN in front). Seed 5 demo users with your own photos. README: feed design trade-off, image pipeline and GPS privacy, ranking formula, and the not-affiliated note.
✅ Check it works
On a phone over mobile data, the feed shows the first posts in under 2 seconds.
🚀 Make it stand out
- +Private accounts with follow requests
- +Reels: short videos with HLS (see the Netflix guide)
- +Direct messages (see the WhatsApp guide)
- +Alt text for images, written by the user or suggested by an AI model