0% found this document useful (0 votes)
1 views

Build_Threads_Like_App

Uploaded by

beingari52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Build_Threads_Like_App

Uploaded by

beingari52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Build a Threads-like App with TypeScript, Next.js, Node.

js, MongoDB, and Clerk

1. Setup Your Development Environment

Install Prerequisites:

- Node.js: Install the latest version from nodejs.org.

- VS Code Extensions: ESLint, Prettier, TypeScript.

Initialize the Project:

$ npx create-next-app@latest threads-clone --typescript

$ cd threads-clone

$ npm install mongoose @clerk/nextjs @clerk/clerk-sdk-node

2. Configure Clerk for Authentication

Sign up for Clerk at clerk.dev and create a new application.

Set environment variables in `.env.local`:

NEXT_PUBLIC_CLERK_FRONTEND_API=<Your Clerk Frontend API>

CLERK_API_KEY=<Your Clerk API Key>

Wrap your app with Clerk in `pages/_app.tsx`:

import { ClerkProvider } from "@clerk/nextjs";

export default function MyApp({ Component, pageProps }: any) {

return <ClerkProvider><Component {...pageProps} /></ClerkProvider>;

Create a Sign-in Page in `pages/sign-in.tsx` and protect routes using `withAuth` middleware.
3. Connect to MongoDB

Install MongoDB:

$ npm install mongoose @types/mongoose

Set MongoDB URI in `.env.local`:

MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/threads?retryWri

tes=true&w=majority

Create a database utility file in `lib/mongodb.ts` to connect to MongoDB.

4. Define Models

Define the Post model in `models/Post.ts`:

import mongoose, { Schema, Document } from "mongoose";

export interface Post extends Document {

userId: string;

content: string;

createdAt: Date;

const PostSchema = new Schema<Post>({

userId: { type: String, required: true },

content: { type: String, required: true },

createdAt: { type: Date, default: Date.now },

});
export default mongoose.models.Post || mongoose.model<Post>("Post", PostSchema);

5. Create Backend API Routes

Add a Post API Route in `pages/api/posts.ts`:

import connectMongo from "../../lib/mongodb";

import Post from "../../models/Post";

import { withAuth } from "@clerk/nextjs/api";

export default withAuth(async (req, res) => {

const { userId } = req.auth;

if (!userId) return res.status(401).json({ message: "Unauthorized" });

await connectMongo();

if (req.method === "POST") {

const { content } = req.body;

const post = new Post({ userId, content });

await post.save();

return res.status(201).json(post);

res.status(405).json({ message: "Method Not Allowed" });

});

Fetch all posts:


if (req.method === "GET") {

const posts = await Post.find().sort({ createdAt: -1 });

return res.status(200).json(posts);

6. Build the Frontend

Post Feed in `pages/index.tsx`:

import { useState, useEffect } from "react";

export default function Home() {

const [posts, setPosts] = useState([]);

useEffect(() => {

async function fetchPosts() {

const res = await fetch("/api/posts");

const data = await res.json();

setPosts(data);

fetchPosts();

}, []);

return (

<div>

<h1>Threads Clone</h1>

{posts.map((post) => (

<div key={post._id}>
<p>{post.content}</p>

</div>

))}

</div>

);

Create a Post Component in `CreatePost.tsx`:

import { useState } from "react";

export default function CreatePost() {

const [content, setContent] = useState("");

const handleSubmit = async (e) => {

e.preventDefault();

await fetch("/api/posts", {

method: "POST",

headers: { "Content-Type": "application/json" },

body: JSON.stringify({ content }),

});

setContent("");

};

return (

<form onSubmit={handleSubmit}>

<textarea value={content} onChange={(e) => setContent(e.target.value)}

placeholder="What's on your mind?" />


<button type="submit">Post</button>

</form>

);

7. Enhance with Features

- Likes and Comments: Add `likes` and `comments` fields to the `Post` model and create related

APIs.

- Pagination: Use server-side rendering (SSR) or API pagination for large post feeds.

- User Profiles: Display posts by user and allow profile updates.

8. Deploy

Add `.env.local` values to Vercel or any hosting platform.

Deploy with Vercel:

$ vercel

You might also like