Skip to content

Instantly share code, notes, and snippets.

@adrianhajdin
Last active July 16, 2024 14:58
Show Gist options
  • Save adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e to your computer and use it in GitHub Desktop.
Save adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e to your computer and use it in GitHub Desktop.
Build and Deploy a Full Stack MERN Next.js 13 Threads App | React, Next JS, TypeScript, MongoDB
/* eslint-disable camelcase */
// Resource: https://clerk.com/docs/users/sync-data-to-your-backend
// Above article shows why we need webhooks i.e., to sync data to our backend
// Resource: https://docs.svix.com/receiving/verifying-payloads/why
// It's a good practice to verify webhooks. Above article shows why we should do it
import { Webhook, WebhookRequiredHeaders } from "svix";
import { headers } from "next/headers";
import { IncomingHttpHeaders } from "http";
import { NextResponse } from "next/server";
import {
addMemberToCommunity,
createCommunity,
deleteCommunity,
removeUserFromCommunity,
updateCommunityInfo,
} from "@/lib/actions/community.actions";
// Resource: https://clerk.com/docs/integration/webhooks#supported-events
// Above document lists the supported events
type EventType =
| "organization.created"
| "organizationInvitation.created"
| "organizationMembership.created"
| "organizationMembership.deleted"
| "organization.updated"
| "organization.deleted";
type Event = {
data: Record<string, string | number | Record<string, string>[]>;
object: "event";
type: EventType;
};
export const POST = async (request: Request) => {
const payload = await request.json();
const header = headers();
const heads = {
"svix-id": header.get("svix-id"),
"svix-timestamp": header.get("svix-timestamp"),
"svix-signature": header.get("svix-signature"),
};
// Activitate Webhook in the Clerk Dashboard.
// After adding the endpoint, you'll see the secret on the right side.
const wh = new Webhook(process.env.NEXT_CLERK_WEBHOOK_SECRET || "");
let evnt: Event | null = null;
try {
evnt = wh.verify(
JSON.stringify(payload),
heads as IncomingHttpHeaders & WebhookRequiredHeaders
) as Event;
} catch (err) {
return NextResponse.json({ message: err }, { status: 400 });
}
const eventType: EventType = evnt?.type!;
// Listen organization creation event
if (eventType === "organization.created") {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/CreateOrganization
// Show what evnt?.data sends from above resource
const { id, name, slug, logo_url, image_url, created_by } =
evnt?.data ?? {};
try {
// @ts-ignore
await createCommunity(
// @ts-ignore
id,
name,
slug,
logo_url || image_url,
"org bio",
created_by
);
return NextResponse.json({ message: "User created" }, { status: 201 });
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
// Listen organization invitation creation event.
// Just to show. You can avoid this or tell people that we can create a new mongoose action and
// add pending invites in the database.
if (eventType === "organizationInvitation.created") {
try {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation
console.log("Invitation created", evnt?.data);
return NextResponse.json(
{ message: "Invitation created" },
{ status: 201 }
);
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
// Listen organization membership (member invite & accepted) creation
if (eventType === "organizationMembership.created") {
try {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership
// Show what evnt?.data sends from above resource
const { organization, public_user_data } = evnt?.data;
console.log("created", evnt?.data);
// @ts-ignore
await addMemberToCommunity(organization.id, public_user_data.user_id);
return NextResponse.json(
{ message: "Invitation accepted" },
{ status: 201 }
);
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
// Listen member deletion event
if (eventType === "organizationMembership.deleted") {
try {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/DeleteOrganizationMembership
// Show what evnt?.data sends from above resource
const { organization, public_user_data } = evnt?.data;
console.log("removed", evnt?.data);
// @ts-ignore
await removeUserFromCommunity(public_user_data.user_id, organization.id);
return NextResponse.json({ message: "Member removed" }, { status: 201 });
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
// Listen organization updation event
if (eventType === "organization.updated") {
try {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/UpdateOrganization
// Show what evnt?.data sends from above resource
const { id, logo_url, name, slug } = evnt?.data;
console.log("updated", evnt?.data);
// @ts-ignore
await updateCommunityInfo(id, name, slug, logo_url);
return NextResponse.json({ message: "Member removed" }, { status: 201 });
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
// Listen organization deletion event
if (eventType === "organization.deleted") {
try {
// Resource: https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/DeleteOrganization
// Show what evnt?.data sends from above resource
const { id } = evnt?.data;
console.log("deleted", evnt?.data);
// @ts-ignore
await deleteCommunity(id);
return NextResponse.json(
{ message: "Organization deleted" },
{ status: 201 }
);
} catch (err) {
console.log(err);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
};
"use server";
import { FilterQuery, SortOrder } from "mongoose";
import Community from "../models/community.model";
import Thread from "../models/thread.model";
import User from "../models/user.model";
import { connectToDB } from "../mongoose";
export async function createCommunity(
id: string,
name: string,
username: string,
image: string,
bio: string,
createdById: string // Change the parameter name to reflect it's an id
) {
try {
connectToDB();
// Find the user with the provided unique id
const user = await User.findOne({ id: createdById });
if (!user) {
throw new Error("User not found"); // Handle the case if the user with the id is not found
}
const newCommunity = new Community({
id,
name,
username,
image,
bio,
createdBy: user._id, // Use the mongoose ID of the user
});
const createdCommunity = await newCommunity.save();
// Update User model
user.communities.push(createdCommunity._id);
await user.save();
return createdCommunity;
} catch (error) {
// Handle any errors
console.error("Error creating community:", error);
throw error;
}
}
export async function fetchCommunityDetails(id: string) {
try {
connectToDB();
const communityDetails = await Community.findOne({ id }).populate([
"createdBy",
{
path: "members",
model: User,
select: "name username image _id id",
},
]);
return communityDetails;
} catch (error) {
// Handle any errors
console.error("Error fetching community details:", error);
throw error;
}
}
export async function fetchCommunityPosts(id: string) {
try {
connectToDB();
const communityPosts = await Community.findById(id).populate({
path: "threads",
model: Thread,
populate: [
{
path: "author",
model: User,
select: "name image id", // Select the "name" and "_id" fields from the "User" model
},
{
path: "children",
model: Thread,
populate: {
path: "author",
model: User,
select: "image _id", // Select the "name" and "_id" fields from the "User" model
},
},
],
});
return communityPosts;
} catch (error) {
// Handle any errors
console.error("Error fetching community posts:", error);
throw error;
}
}
export async function fetchCommunities({
searchString = "",
pageNumber = 1,
pageSize = 20,
sortBy = "desc",
}: {
searchString?: string;
pageNumber?: number;
pageSize?: number;
sortBy?: SortOrder;
}) {
try {
connectToDB();
// Calculate the number of communities to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;
// Create a case-insensitive regular expression for the provided search string.
const regex = new RegExp(searchString, "i");
// Create an initial query object to filter communities.
const query: FilterQuery<typeof Community> = {};
// If the search string is not empty, add the $or operator to match either username or name fields.
if (searchString.trim() !== "") {
query.$or = [
{ username: { $regex: regex } },
{ name: { $regex: regex } },
];
}
// Define the sort options for the fetched communities based on createdAt field and provided sort order.
const sortOptions = { createdAt: sortBy };
// Create a query to fetch the communities based on the search and sort criteria.
const communitiesQuery = Community.find(query)
.sort(sortOptions)
.skip(skipAmount)
.limit(pageSize)
.populate("members");
// Count the total number of communities that match the search criteria (without pagination).
const totalCommunitiesCount = await Community.countDocuments(query);
const communities = await communitiesQuery.exec();
// Check if there are more communities beyond the current page.
const isNext = totalCommunitiesCount > skipAmount + communities.length;
return { communities, isNext };
} catch (error) {
console.error("Error fetching communities:", error);
throw error;
}
}
export async function addMemberToCommunity(
communityId: string,
memberId: string
) {
try {
connectToDB();
// Find the community by its unique id
const community = await Community.findOne({ id: communityId });
if (!community) {
throw new Error("Community not found");
}
// Find the user by their unique id
const user = await User.findOne({ id: memberId });
if (!user) {
throw new Error("User not found");
}
// Check if the user is already a member of the community
if (community.members.includes(user._id)) {
throw new Error("User is already a member of the community");
}
// Add the user's _id to the members array in the community
community.members.push(user._id);
await community.save();
// Add the community's _id to the communities array in the user
user.communities.push(community._id);
await user.save();
return community;
} catch (error) {
// Handle any errors
console.error("Error adding member to community:", error);
throw error;
}
}
export async function removeUserFromCommunity(
userId: string,
communityId: string
) {
try {
connectToDB();
const userIdObject = await User.findOne({ id: userId }, { _id: 1 });
const communityIdObject = await Community.findOne(
{ id: communityId },
{ _id: 1 }
);
if (!userIdObject) {
throw new Error("User not found");
}
if (!communityIdObject) {
throw new Error("Community not found");
}
// Remove the user's _id from the members array in the community
await Community.updateOne(
{ _id: communityIdObject._id },
{ $pull: { members: userIdObject._id } }
);
// Remove the community's _id from the communities array in the user
await User.updateOne(
{ _id: userIdObject._id },
{ $pull: { communities: communityIdObject._id } }
);
return { success: true };
} catch (error) {
// Handle any errors
console.error("Error removing user from community:", error);
throw error;
}
}
export async function updateCommunityInfo(
communityId: string,
name: string,
username: string,
image: string
) {
try {
connectToDB();
// Find the community by its _id and update the information
const updatedCommunity = await Community.findOneAndUpdate(
{ id: communityId },
{ name, username, image }
);
if (!updatedCommunity) {
throw new Error("Community not found");
}
return updatedCommunity;
} catch (error) {
// Handle any errors
console.error("Error updating community information:", error);
throw error;
}
}
export async function deleteCommunity(communityId: string) {
try {
connectToDB();
// Find the community by its ID and delete it
const deletedCommunity = await Community.findOneAndDelete({
id: communityId,
});
if (!deletedCommunity) {
throw new Error("Community not found");
}
// Delete all threads associated with the community
await Thread.deleteMany({ community: communityId });
// Find all users who are part of the community
const communityUsers = await User.find({ communities: communityId });
// Remove the community from the 'communities' array for each user
const updateUserPromises = communityUsers.map((user) => {
user.communities.pull(communityId);
return user.save();
});
await Promise.all(updateUserPromises);
return deletedCommunity;
} catch (error) {
console.error("Error deleting community: ", error);
throw error;
}
}
import Image from "next/image";
import Link from "next/link";
import { Button } from "../ui/button";
interface Props {
id: string;
name: string;
username: string;
imgUrl: string;
bio: string;
members: {
image: string;
}[];
}
function CommunityCard({ id, name, username, imgUrl, bio, members }: Props) {
return (
<article className='community-card'>
<div className='flex flex-wrap items-center gap-3'>
<Link href={`/communities/${id}`} className='relative h-12 w-12'>
<Image
src={imgUrl}
alt='community_logo'
fill
className='rounded-full object-cover'
/>
</Link>
<div>
<Link href={`/communities/${id}`}>
<h4 className='text-base-semibold text-light-1'>{name}</h4>
</Link>
<p className='text-small-medium text-gray-1'>@{username}</p>
</div>
</div>
<p className='mt-4 text-subtle-medium text-gray-1'>{bio}</p>
<div className='mt-5 flex flex-wrap items-center justify-between gap-3'>
<Link href={`/communities/${id}`}>
<Button size='sm' className='community-card_btn'>
View
</Button>
</Link>
{members.length > 0 && (
<div className='flex items-center'>
{members.map((member, index) => (
<Image
key={index}
src={member.image}
alt={`user_${index}`}
width={28}
height={28}
className={`${
index !== 0 && "-ml-2"
} rounded-full object-cover`}
/>
))}
{members.length > 3 && (
<p className='ml-1 text-subtle-medium text-gray-1'>
{members.length}+ Users
</p>
)}
</div>
)}
</div>
</article>
);
}
export default CommunityCard;
export const sidebarLinks = [
{
imgURL: "/assets/home.svg",
route: "/",
label: "Home",
},
{
imgURL: "/assets/search.svg",
route: "/search",
label: "Search",
},
{
imgURL: "/assets/heart.svg",
route: "/activity",
label: "Activity",
},
{
imgURL: "/assets/create.svg",
route: "/create-thread",
label: "Create Thread",
},
{
imgURL: "/assets/community.svg",
route: "/communities",
label: "Communities",
},
{
imgURL: "/assets/user.svg",
route: "/profile",
label: "Profile",
},
];
export const profileTabs = [
{ value: "threads", label: "Threads", icon: "/assets/reply.svg" },
{ value: "replies", label: "Replies", icon: "/assets/members.svg" },
{ value: "tagged", label: "Tagged", icon: "/assets/tag.svg" },
];
export const communityTabs = [
{ value: "threads", label: "Threads", icon: "/assets/reply.svg" },
{ value: "members", label: "Members", icon: "/assets/members.svg" },
{ value: "requests", label: "Requests", icon: "/assets/request.svg" },
];
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
/* main */
.main-container {
@apply flex min-h-screen flex-1 flex-col items-center bg-dark-1 px-6 pb-10 pt-28 max-md:pb-32 sm:px-10;
}
/* Head Text */
.head-text {
@apply text-heading2-bold text-light-1;
}
/* Activity */
.activity-card {
@apply flex items-center gap-2 rounded-md bg-dark-2 px-7 py-4;
}
/* No Result */
.no-result {
@apply text-center !text-base-regular text-light-3;
}
/* Community Card */
.community-card {
@apply w-full rounded-lg bg-dark-3 px-4 py-5 sm:w-96;
}
.community-card_btn {
@apply rounded-lg bg-primary-500 px-5 py-1.5 text-small-regular !text-light-1 !important;
}
/* thread card */
.thread-card_bar {
@apply relative mt-2 w-0.5 grow rounded-full bg-neutral-800;
}
/* User card */
.user-card {
@apply flex flex-col justify-between gap-4 max-xs:rounded-xl max-xs:bg-dark-3 max-xs:p-4 xs:flex-row xs:items-center;
}
.user-card_avatar {
@apply flex flex-1 items-start justify-start gap-3 xs:items-center;
}
.user-card_btn {
@apply h-auto min-w-[74px] rounded-lg bg-primary-500 text-[12px] text-light-1 !important;
}
.searchbar {
@apply flex gap-1 rounded-lg bg-dark-3 px-4 py-2;
}
.searchbar_input {
@apply border-none bg-dark-3 text-base-regular text-light-4 outline-none !important;
}
.topbar {
@apply fixed top-0 z-30 flex w-full items-center justify-between bg-dark-2 px-6 py-3;
}
.bottombar {
@apply fixed bottom-0 z-10 w-full rounded-t-3xl bg-glassmorphism p-4 backdrop-blur-lg xs:px-7 md:hidden;
}
.bottombar_container {
@apply flex items-center justify-between gap-3 xs:gap-5;
}
.bottombar_link {
@apply relative flex flex-col items-center gap-2 rounded-lg p-2 sm:flex-1 sm:px-2 sm:py-2.5;
}
.leftsidebar {
@apply sticky left-0 top-0 z-20 flex h-screen w-fit flex-col justify-between overflow-auto border-r border-r-dark-4 bg-dark-2 pb-5 pt-28 max-md:hidden;
}
.leftsidebar_link {
@apply relative flex justify-start gap-4 rounded-lg p-4;
}
.pagination {
@apply mt-10 flex w-full items-center justify-center gap-5;
}
.rightsidebar {
@apply sticky right-0 top-0 z-20 flex h-screen w-fit flex-col justify-between gap-12 overflow-auto border-l border-l-dark-4 bg-dark-2 px-10 pb-6 pt-28 max-xl:hidden;
}
}
@layer utilities {
.css-invert {
@apply invert-[50%] brightness-200;
}
.custom-scrollbar::-webkit-scrollbar {
width: 3px;
height: 3px;
border-radius: 2px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: #09090a;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #5c5c7b;
border-radius: 50px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #7878a3;
}
}
/* Clerk Responsive fix */
.cl-organizationSwitcherTrigger .cl-userPreview .cl-userPreviewTextContainer {
@apply max-sm:hidden;
}
.cl-organizationSwitcherTrigger
.cl-organizationPreview
.cl-organizationPreviewTextContainer {
@apply max-sm:hidden;
}
/* Shadcn Component Styles */
/* Tab */
.tab {
@apply flex min-h-[50px] flex-1 items-center gap-3 bg-dark-2 text-light-2 data-[state=active]:bg-[#0e0e12] data-[state=active]:text-light-2 !important;
}
.no-focus {
@apply focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 !important;
}
/* Account Profile */
.account-form_image-label {
@apply flex h-24 w-24 items-center justify-center rounded-full bg-dark-4 !important;
}
.account-form_image-input {
@apply cursor-pointer border-none bg-transparent outline-none file:text-blue !important;
}
.account-form_input {
@apply border border-dark-4 bg-dark-3 text-light-1 !important;
}
/* Comment Form */
.comment-form {
@apply mt-10 flex items-center gap-4 border-y border-y-dark-4 py-5 max-xs:flex-col !important;
}
.comment-form_btn {
@apply rounded-3xl bg-primary-500 px-8 py-2 !text-small-regular text-light-1 max-xs:w-full !important;
}
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true,
serverComponentsExternalPackages: ["mongoose"],
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "img.clerk.com",
},
{
protocol: "https",
hostname: "images.clerk.dev",
},
{
protocol: "https",
hostname: "uploadthing.com",
},
{
protocol: "https",
hostname: "placehold.co",
},
],
typescript: {
ignoreBuildErrors: true,
},
},
};
module.exports = nextConfig;
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
"./pages/**/*.{ts,tsx}",
"./components/**/*.{ts,tsx}",
"./app/**/*.{ts,tsx}",
"./src/**/*.{ts,tsx}",
],
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
fontSize: {
"heading1-bold": [
"36px",
{
lineHeight: "140%",
fontWeight: "700",
},
],
"heading1-semibold": [
"36px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"heading2-bold": [
"30px",
{
lineHeight: "140%",
fontWeight: "700",
},
],
"heading2-semibold": [
"30px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"heading3-bold": [
"24px",
{
lineHeight: "140%",
fontWeight: "700",
},
],
"heading4-medium": [
"20px",
{
lineHeight: "140%",
fontWeight: "500",
},
],
"body-bold": [
"18px",
{
lineHeight: "140%",
fontWeight: "700",
},
],
"body-semibold": [
"18px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"body-medium": [
"18px",
{
lineHeight: "140%",
fontWeight: "500",
},
],
"body-normal": [
"18px",
{
lineHeight: "140%",
fontWeight: "400",
},
],
"body1-bold": [
"18px",
{
lineHeight: "140%",
fontWeight: "700",
},
],
"base-regular": [
"16px",
{
lineHeight: "140%",
fontWeight: "400",
},
],
"base-medium": [
"16px",
{
lineHeight: "140%",
fontWeight: "500",
},
],
"base-semibold": [
"16px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"base1-semibold": [
"16px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"small-regular": [
"14px",
{
lineHeight: "140%",
fontWeight: "400",
},
],
"small-medium": [
"14px",
{
lineHeight: "140%",
fontWeight: "500",
},
],
"small-semibold": [
"14px",
{
lineHeight: "140%",
fontWeight: "600",
},
],
"subtle-medium": [
"12px",
{
lineHeight: "16px",
fontWeight: "500",
},
],
"subtle-semibold": [
"12px",
{
lineHeight: "16px",
fontWeight: "600",
},
],
"tiny-medium": [
"10px",
{
lineHeight: "140%",
fontWeight: "500",
},
],
"x-small-semibold": [
"7px",
{
lineHeight: "9.318px",
fontWeight: "600",
},
],
},
extend: {
colors: {
"primary-500": "#877EFF",
"secondary-500": "#FFB620",
blue: "#0095F6",
"logout-btn": "#FF5A5A",
"navbar-menu": "rgba(16, 16, 18, 0.6)",
"dark-1": "#000000",
"dark-2": "#121417",
"dark-3": "#101012",
"dark-4": "#1F1F22",
"light-1": "#FFFFFF",
"light-2": "#EFEFEF",
"light-3": "#7878A3",
"light-4": "#5C5C7B",
"gray-1": "#697C89",
glassmorphism: "rgba(16, 16, 18, 0.60)",
},
boxShadow: {
"count-badge": "0px 0px 6px 2px rgba(219, 188, 159, 0.30)",
"groups-sidebar": "-30px 0px 60px 0px rgba(28, 28, 31, 0.50)",
},
screens: {
xs: "400px",
},
keyframes: {
"accordion-down": {
from: { height: 0 },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: 0 },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
};
"use server";
import { revalidatePath } from "next/cache";
import { connectToDB } from "../mongoose";
import User from "../models/user.model";
import Thread from "../models/thread.model";
import Community from "../models/community.model";
export async function fetchPosts(pageNumber = 1, pageSize = 20) {
connectToDB();
// Calculate the number of posts to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;
// Create a query to fetch the posts that have no parent (top-level threads) (a thread that is not a comment/reply).
const postsQuery = Thread.find({ parentId: { $in: [null, undefined] } })
.sort({ createdAt: "desc" })
.skip(skipAmount)
.limit(pageSize)
.populate({
path: "author",
model: User,
})
.populate({
path: "community",
model: Community,
})
.populate({
path: "children", // Populate the children field
populate: {
path: "author", // Populate the author field within children
model: User,
select: "_id name parentId image", // Select only _id and username fields of the author
},
});
// Count the total number of top-level posts (threads) i.e., threads that are not comments.
const totalPostsCount = await Thread.countDocuments({
parentId: { $in: [null, undefined] },
}); // Get the total count of posts
const posts = await postsQuery.exec();
const isNext = totalPostsCount > skipAmount + posts.length;
return { posts, isNext };
}
interface Params {
text: string,
author: string,
communityId: string | null,
path: string,
}
export async function createThread({ text, author, communityId, path }: Params
) {
try {
connectToDB();
const communityIdObject = await Community.findOne(
{ id: communityId },
{ _id: 1 }
);
const createdThread = await Thread.create({
text,
author,
community: communityIdObject, // Assign communityId if provided, or leave it null for personal account
});
// Update User model
await User.findByIdAndUpdate(author, {
$push: { threads: createdThread._id },
});
if (communityIdObject) {
// Update Community model
await Community.findByIdAndUpdate(communityIdObject, {
$push: { threads: createdThread._id },
});
}
revalidatePath(path);
} catch (error: any) {
throw new Error(`Failed to create thread: ${error.message}`);
}
}
async function fetchAllChildThreads(threadId: string): Promise<any[]> {
const childThreads = await Thread.find({ parentId: threadId });
const descendantThreads = [];
for (const childThread of childThreads) {
const descendants = await fetchAllChildThreads(childThread._id);
descendantThreads.push(childThread, ...descendants);
}
return descendantThreads;
}
export async function deleteThread(id: string, path: string): Promise<void> {
try {
connectToDB();
// Find the thread to be deleted (the main thread)
const mainThread = await Thread.findById(id).populate("author community");
if (!mainThread) {
throw new Error("Thread not found");
}
// Fetch all child threads and their descendants recursively
const descendantThreads = await fetchAllChildThreads(id);
// Get all descendant thread IDs including the main thread ID and child thread IDs
const descendantThreadIds = [
id,
...descendantThreads.map((thread) => thread._id),
];
// Extract the authorIds and communityIds to update User and Community models respectively
const uniqueAuthorIds = new Set(
[
...descendantThreads.map((thread) => thread.author?._id?.toString()), // Use optional chaining to handle possible undefined values
mainThread.author?._id?.toString(),
].filter((id) => id !== undefined)
);
const uniqueCommunityIds = new Set(
[
...descendantThreads.map((thread) => thread.community?._id?.toString()), // Use optional chaining to handle possible undefined values
mainThread.community?._id?.toString(),
].filter((id) => id !== undefined)
);
// Recursively delete child threads and their descendants
await Thread.deleteMany({ _id: { $in: descendantThreadIds } });
// Update User model
await User.updateMany(
{ _id: { $in: Array.from(uniqueAuthorIds) } },
{ $pull: { threads: { $in: descendantThreadIds } } }
);
// Update Community model
await Community.updateMany(
{ _id: { $in: Array.from(uniqueCommunityIds) } },
{ $pull: { threads: { $in: descendantThreadIds } } }
);
revalidatePath(path);
} catch (error: any) {
throw new Error(`Failed to delete thread: ${error.message}`);
}
}
export async function fetchThreadById(threadId: string) {
connectToDB();
try {
const thread = await Thread.findById(threadId)
.populate({
path: "author",
model: User,
select: "_id id name image",
}) // Populate the author field with _id and username
.populate({
path: "community",
model: Community,
select: "_id id name image",
}) // Populate the community field with _id and name
.populate({
path: "children", // Populate the children field
populate: [
{
path: "author", // Populate the author field within children
model: User,
select: "_id id name parentId image", // Select only _id and username fields of the author
},
{
path: "children", // Populate the children field within children
model: Thread, // The model of the nested children (assuming it's the same "Thread" model)
populate: {
path: "author", // Populate the author field within nested children
model: User,
select: "_id id name parentId image", // Select only _id and username fields of the author
},
},
],
})
.exec();
return thread;
} catch (err) {
console.error("Error while fetching thread:", err);
throw new Error("Unable to fetch thread");
}
}
export async function addCommentToThread(
threadId: string,
commentText: string,
userId: string,
path: string
) {
connectToDB();
try {
// Find the original thread by its ID
const originalThread = await Thread.findById(threadId);
if (!originalThread) {
throw new Error("Thread not found");
}
// Create the new comment thread
const commentThread = new Thread({
text: commentText,
author: userId,
parentId: threadId, // Set the parentId to the original thread's ID
});
// Save the comment thread to the database
const savedCommentThread = await commentThread.save();
// Add the comment thread's ID to the original thread's children array
originalThread.children.push(savedCommentThread._id);
// Save the updated original thread to the database
await originalThread.save();
revalidatePath(path);
} catch (err) {
console.error("Error while adding comment:", err);
throw new Error("Unable to add comment");
}
}
// Resource: https://docs.uploadthing.com/api-reference/react#generatereacthelpers
// Copy paste (be careful with imports)
import { generateReactHelpers } from "@uploadthing/react/hooks";
import type { OurFileRouter } from "@/app/api/uploadthing/core";
export const { useUploadThing, uploadFiles } = generateReactHelpers<OurFileRouter>();
"use server";
import { FilterQuery, SortOrder } from "mongoose";
import { revalidatePath } from "next/cache";
import Community from "../models/community.model";
import Thread from "../models/thread.model";
import User from "../models/user.model";
import { connectToDB } from "../mongoose";
export async function fetchUser(userId: string) {
try {
connectToDB();
return await User.findOne({ id: userId }).populate({
path: "communities",
model: Community,
});
} catch (error: any) {
throw new Error(`Failed to fetch user: ${error.message}`);
}
}
interface Params {
userId: string;
username: string;
name: string;
bio: string;
image: string;
path: string;
}
export async function updateUser({
userId,
bio,
name,
path,
username,
image,
}: Params): Promise<void> {
try {
connectToDB();
await User.findOneAndUpdate(
{ id: userId },
{
username: username.toLowerCase(),
name,
bio,
image,
onboarded: true,
},
{ upsert: true }
);
if (path === "/profile/edit") {
revalidatePath(path);
}
} catch (error: any) {
throw new Error(`Failed to create/update user: ${error.message}`);
}
}
export async function fetchUserPosts(userId: string) {
try {
connectToDB();
// Find all threads authored by the user with the given userId
const threads = await User.findOne({ id: userId }).populate({
path: "threads",
model: Thread,
populate: [
{
path: "community",
model: Community,
select: "name id image _id", // Select the "name" and "_id" fields from the "Community" model
},
{
path: "children",
model: Thread,
populate: {
path: "author",
model: User,
select: "name image id", // Select the "name" and "_id" fields from the "User" model
},
},
],
});
return threads;
} catch (error) {
console.error("Error fetching user threads:", error);
throw error;
}
}
// Almost similar to Thead (search + pagination) and Community (search + pagination)
export async function fetchUsers({
userId,
searchString = "",
pageNumber = 1,
pageSize = 20,
sortBy = "desc",
}: {
userId: string;
searchString?: string;
pageNumber?: number;
pageSize?: number;
sortBy?: SortOrder;
}) {
try {
connectToDB();
// Calculate the number of users to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;
// Create a case-insensitive regular expression for the provided search string.
const regex = new RegExp(searchString, "i");
// Create an initial query object to filter users.
const query: FilterQuery<typeof User> = {
id: { $ne: userId }, // Exclude the current user from the results.
};
// If the search string is not empty, add the $or operator to match either username or name fields.
if (searchString.trim() !== "") {
query.$or = [
{ username: { $regex: regex } },
{ name: { $regex: regex } },
];
}
// Define the sort options for the fetched users based on createdAt field and provided sort order.
const sortOptions = { createdAt: sortBy };
const usersQuery = User.find(query)
.sort(sortOptions)
.skip(skipAmount)
.limit(pageSize);
// Count the total number of users that match the search criteria (without pagination).
const totalUsersCount = await User.countDocuments(query);
const users = await usersQuery.exec();
// Check if there are more users beyond the current page.
const isNext = totalUsersCount > skipAmount + users.length;
return { users, isNext };
} catch (error) {
console.error("Error fetching users:", error);
throw error;
}
}
export async function getActivity(userId: string) {
try {
connectToDB();
// Find all threads created by the user
const userThreads = await Thread.find({ author: userId });
// Collect all the child thread ids (replies) from the 'children' field of each user thread
const childThreadIds = userThreads.reduce((acc, userThread) => {
return acc.concat(userThread.children);
}, []);
// Find and return the child threads (replies) excluding the ones created by the same user
const replies = await Thread.find({
_id: { $in: childThreadIds },
author: { $ne: userId }, // Exclude threads authored by the same user
}).populate({
path: "author",
model: User,
select: "name image _id",
});
return replies;
} catch (error) {
console.error("Error fetching replies: ", error);
throw error;
}
}
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
// generated by shadcn
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// created by chatgpt
export function isBase64Image(imageData: string) {
const base64Regex = /^data:image\/(png|jpe?g|gif|webp);base64,/;
return base64Regex.test(imageData);
}
// created by chatgpt
export function formatDateString(dateString: string) {
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "short",
day: "numeric",
};
const date = new Date(dateString);
const formattedDate = date.toLocaleDateString(undefined, options);
const time = date.toLocaleTimeString([], {
hour: "numeric",
minute: "2-digit",
});
return `${time} - ${formattedDate}`;
}
// created by chatgpt
export function formatThreadCount(count: number): string {
if (count === 0) {
return "No Threads";
} else {
const threadCount = count.toString().padStart(2, "0");
const threadWord = count === 1 ? "Thread" : "Threads";
return `${threadCount} ${threadWord}`;
}
}
@Jaywalker300
Copy link

Error: ClerkInstanceContext not found, apply the following Fix: Wrap your app with ClerkProvider in both /auth/layout.tsx and root/layout.tsx files.

@mesainirohit
Copy link

Screenshot from 2023-08-14 15-50-51 I get this error after signing in and being redirected to the index page

Wrap your app with ClerkProvider in both layout.tsx files, i.e., app/(auth)/layout.tsx and app/(root)/layout.tsx

@dark40
Copy link

dark40 commented Aug 17, 2023

Hi fellows, I have encountered issue in webhook (at least I believe so). The coummnity wasn't able to be added in to database, and the vercel returns 504 after logged in. I can't even reach the home page as video showed. Not sure which step(s) were wrong.
image

@alvienzo720
Copy link

So what you have to do is go to the root page.tsx and import import {ClerkProvider} from "@clerk/nextjs";
Then wrap your ClerkProvider with all your code like blow
export default function Home() {
return (
<ClerkProvider>
<div>
<UserButton afterSignOutUrl="/"/>
</div>
</ClerkProvider>
)
}

@orlando-guy
Copy link

scrnli_17_08_2023 15-23-56
I have set up clerk as in the video but i still get this error. Can anyone help !

@tokyoabc
Copy link

tokyoabc commented Aug 17, 2023

image
I have this error can someone help me

@codecret
Copy link

for

didn't work

@sridhar-kpr
Copy link

Hi
someone please help me out
i get this error
Screenshot 2023-08-19 155013

"use server";

import { revalidatePath } from 'next/cache';
// import mongoose from 'mongoose'; // Import mongoose here
import Thread from '../models/thread.modal';
import User from '../models/user.model';
import { connectToDatabase } from '../mongoose';

interface Params {
text: string;
author: string;
communityId: string | null;
path: string;
}

export async function createThread({ text, author, communityId, path }: Params) {
try {
connectToDatabase();
console.log('iiii');

// if (!mongoose.Types.ObjectId.isValid(author)) {
//   throw new Error('Invalid author ObjectId format');
// }

const createdThread = await Thread.create({ text, author, commuinity: null });

// Update user model
await User.findByIdAndUpdate(author, { $push: { threads: createdThread._id } });

// Revalidate community
revalidatePath(path);

} catch (error: any) {
throw new Error(Error in threads.action.ts ${error.message});
}
}
also this is
error
connected to database
iiii
connected to database

  • error lib\actions\thread.action.ts (33:10) @ createThread
  • error Error: Error in threads.action.ts Thread validation failed: author: Cast to ObjectId failed for value "user_2U6rLehxs7YVD1YueJ9bTXDNNea" (type string) at path "author" because of "BSONError"
    at createThread (./lib/actions/thread.action.ts:39:15)
    31 | revalidatePath(path);
    32 | } catch (error: any) {

33 | throw new Error(Error in threads.action.ts ${error.message});
| ^
34 | }
35 | }
36 |

this is posthread.tsx
"use client";

import { useForm } from "react-hook-form";
import * as z from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { zodResolver } from "@hookform/resolvers/zod";
import { Textarea } from "../ui/textarea";
import { usePathname, useRouter } from "next/navigation";

// import Image from "next/image";
// import { ChangeEvent, useState } from "react";
// import { isBase64Image } from "@/lib/utils";
// import { useUploadThing } from "@/lib/validations/uploadthing";

// import { updateUser } from "@/lib/actions/user.action";
import { ThreadValidation } from "@/lib/validations/thread";
import { createThread } from "@/lib/actions/thread.action";
interface Props {
user: {
id: string;
objectId: string;
username: string;
name: string;
bio: string;
image: string;
};
btntittle: string;
}

function PostThread({ userId }: { userId: string }) {
const router = useRouter();
const pathname = usePathname();

const form = useForm({
resolver: zodResolver(ThreadValidation),
defaultValues: {
thread: "",
accountId: userId,
},
});
const onSubmit = async (values: z.infer) => {
await createThread({
text: values.thread,
author: userId,
communityId: null,
path: pathname,
});
router.push("/");
};
return (
<Form {...form}>

    <FormField
      control={form.control}
      name="thread"
      render={({ field }) => (
        <FormItem className="mt-10 flex-col flex gap-4 w-full">
          <FormLabel className="text-base-semibold text-light-2">
            Content
          </FormLabel>
          <FormControl className="no-focus border border-dark-4 bg-dark-4 text-light-1">
            <Textarea rows={15} {...field} />
          </FormControl>
          <FormMessage />
        </FormItem>
      )}
    />
    <Button type="submit" className="bg-primary-500">Post</Button>

  </form>
</Form>

);
}
export default PostThread;

@sridhar-kpr
Copy link

Error in threads.action.ts Thread validation failed: author: Cast to ObjectId failed for value "user_2U6rLehxs7YVD1YueJ9bTXDNNea" (type string) at path "author" because of "BSONError"
this si when I consoled error

@ykrambe
Copy link

ykrambe commented Aug 19, 2023

image

can someone help me please, i've been stuck for 2 days, i dont know why some classname not executed in my code, i do the tutorial clearly step by step , when i put classname that not in global css, it's not executed, exampe, this navbar background suppose to be black, and the image in next of threads text. please help me guys

@Ousbaiy
Copy link

Ousbaiy commented Aug 19, 2023

just add "use server" in thread.action.ts

@Ahmedbenslama
Copy link

image it keeps giving me this error, can anybody help me out
your facing connection issue thats why the function is buffering
use your db url :mongodb+srv://username:yourpass@cluster0.hzfnjwm.mongodb.net/......
hope it will fix the problem

I already did and nothing seems to work

@BhattacharjiHRB
Copy link

My thread form button is not submitting the onSubmit function might be in a loop or something idk and userId is defined in the props but still getting this error i'm stuck here also profile/[id] is not working
can anyone solve the problem or faced it ?
Screenshot 2023-08-20 152053
Screenshot 2023-08-20 152133

@Tuong-Duy-Anh
Copy link

Hi guys, I'm having this error in the process of implementing updateUser()
image
really need your help, cause I have checked the typo and found no differents

@AnuragHerenj
Copy link

error

How to solve this error?

@g-sanskar
Copy link

When I am deploying on vercel for first time before setting endpoint thing,
I am getting error that Module not found: Can't resolve 'mongoose'
I have search the internet and not getting a clue why this is happening, can someone help me please.....
Screenshot 2023-08-21 064236

@naivedeveloper95
Copy link

naivedeveloper95 commented Aug 21, 2023

Getting the below error.

Failed to compile

./app/globals.css
Syntax error: D:\Code\threads\app\globals.css The bg-dark-2 class does not exist. If bg-dark-2 is a custom class, make sure it is defined within a @layer directive. (134:3)

132 | /* Tab */
133 | .tab {

134 | @apply flex min-h-[50px] flex-1 items-center gap-3 bg-dark-2 text-light-2 data-[state=active]:bg-[#0e0e12] data-[state=active]:text-light-2 !important;
| ^
135 | }
136 |
-- inner error --
Syntax error: D:\Code\threads\app\globals.css The bg-dark-2 class does not exist. If bg-dark-2 is a custom class, make sure it is defined within a @layer directive. (134:3)

132 | /* Tab */
133 | .tab {

134 | @apply flex min-h-[50px] flex-1 items-center gap-3 bg-dark-2 text-light-2 data-[state=active]:bg-[#0e0e12] data-[state=active]:text-light-2 !important;
| ^
135 | }
136 |
Generated code for D:\Code\threads\node_modules\next\dist\build\webpack\loaders\css-loader\src\index.js??ruleSet[1].rules[5].oneOf[12].use[2]!D:\Code\threads\node_modules\next\dist\build\webpack\loaders\postcss-loader\src\index.js??ruleSet[1].rules[5].oneOf[12].use[3]!D:\Code\threads\app\globals.css

Import trace for requested module:
./app/globals.css

image

How do I resolve it?

@Jaywalker300
Copy link

check if you have a tailwindConfig.ts(not js) file on your root folder. if that's the case then you may have to delete it, copy the global.css file again and paste it where you previously had it, save your work and restart your code editor.

@adedola12
Copy link

image

Please i get this error from vercel, how do i fix it

@drvcodenta
Copy link

drvcodenta commented Aug 23, 2023

@TheNinjan
Wrap the content of html inside clerk provider for layout.tsx inside both (auth) and (root), it solved the problem for me.

@Tuong-Duy-Anh
Copy link

Tuong-Duy-Anh commented Aug 24, 2023

Hi there, I got this error in the process of setting up MongoDB connection, after set up the user.model.ts and user.action.ts and use the related function in the onSubmit function. I get the error right after the route /onboarding was loaded
image

really need your help cause Ive been looking for 2 days now and still stuck

@Jaywalker300
Copy link

Hey guys, i'm stuck on the connecting to the database, on my console its not even detecting if I'm connected to a database at all. I've gone through the code countless times and still cant find the issue. when I click submit nothing happens. it just shows this.
error

@tokyoabc
Copy link

Hey guys, i'm stuck on the connecting to the database, on my console its not even detecting if I'm connected to a database at all. I've gone through the code countless times and still cant find the issue. when I click submit nothing happens. it just shows this.

I have the same problem as you and I don't know how to fix it. I had to start all over again to see if I made a mistake.

@mahdipratama
Copy link

Screenshot 2023-08-08 at 11 57 53 PM

I am getting this error while posting the thread. Can anyone please help in this regard?

Did you fix the bug?

@Madhannmady07
Copy link

Madhannmady07 commented Aug 26, 2023

I was doing my project with no errors , and even done everything correct .I was at this time stamp 3:39:57 But all of a sudden , when i execute the code , it gives me with this errors , saying "Unhandled Runtime Error : Cannot read properties of undefined (reading 'push')"

263465453-d815ae27-7228-4ee2-b3ac-1aa218455876

Help me by saying where the problem could be possibly originated ?

Please Help me to correct this problem, I have almost completed this project . Help me to complete the rest of it successfully . Please .

I believe someone will help me with this problem.

@Akaikenlol
Copy link

Hello, i got this error, after i replacing the global.css files , deleting the tailwind.config.ts (not js) and then replacing it.
I try figuring out by myself, it's say next router was not mounted, i try reading doc, googling it, and all the solutions are likes, try replacing or using next/navigation instead of next/router. And i try checking all my import and i only use next/navigation.
This is in onboarding page.
image

@Akaikenlol
Copy link

I got a solution for my problem.
After asking ChatGPT, I remove from AccountProfile.tsx and then wrap the

tag with in onboarding/page.tsx.

@Jaywalker300
Copy link

Hey guys, i'm stuck on the connecting to the database, on my console its not even detecting if I'm connected to a database at all. I've gone through the code countless times and still cant find the issue. when I click submit nothing happens. it just shows this.

I have the same problem as you and I don't know how to fix it. I had to start all over again to see if I made a mistake.

Same here. I started all over again but still can't locate the issue. Please email me at chiketravis300@gmail.com if you find a solution. Thank you.

@Avish24x
Copy link

scrnli_17_08_2023 15-23-56 I have set up clerk as in the video but i still get this error. Can anyone help !

have you been able to find a solution ?

@Lpreets
Copy link

Lpreets commented Aug 28, 2023

I'm having trouble making the communities work. Since the start of the project I haven't also been able to make the button appear where you can see which organization you are under.
This is my Github Repo if anyone wants to try run the project and see if they spot the problem for me, would be highly appreciated.
https://github.com/Lpreets/threads-clone

also link to where I have hosted this if you don't feel like doing repo clone to test and can perhaps spot the issue by just looking at the "finished" project.

https://threads-clone-lpreet.vercel.app/

@NotSideTrack
Copy link

NotSideTrack commented Aug 29, 2023

Anyone knows why the onboarding isn't autocompleting even when I'm signed in with a valid account. Thanks.

@Avish24x
Copy link

Anyone knows why the onboarding isn't autocompleting even when I'm signed in with a valid account. Thanks.

have you been able to find a solution ?

@Avish24x
Copy link

Anyone knows why the onboarding isn't autocompleting even when I'm signed in with a valid account. Thanks.

import AccountProfile from "@/components/forms/AccountProfile";
import { currentUser } from "@clerk/nextjs";

async function Page() {
const user = await currentUser();

const userInfo = {
id: "",
username: "",
name: "",
bio: "",
image: "",
};

const userData = {
id: user?.id || "", // Provide a default value if user?.id is undefined
objectId: userInfo?.id,
username: userInfo?.username || user?.username || "",
name: userInfo?.name || user?.firstName || "",
bio: userInfo?.bio || "",
image: userInfo?.image || user?.imageUrl || "",
};
return (


Onboarding



complete your profile to be able to use Thread

  <section className="mt-9 bg-dark-2 p-10">
    <AccountProfile user={userData} />
  </section>
</main>

);
}

export default Page;

this is working for me

@mccantsquincy
Copy link

Error in threads.action.ts Thread validation failed: author: Cast to ObjectId failed for value "user_2U6rLehxs7YVD1YueJ9bTXDNNea" (type string) at path "author" because of "BSONError" this si when I consoled error

I'm getting this same error as well! Have you been able to resolve this?

@janramirez
Copy link

ell! Have you been able to resolve this?

make sure to differentiate .id vs ._id,
I had to sift through the files and find that (in my case,) missing underscore in ._id

@NotSideTrack
Copy link

Anyone knows why the onboarding isn't autocompleting even when I'm signed in with a valid account. Thanks.

import AccountProfile from "@/components/forms/AccountProfile"; import { currentUser } from "@clerk/nextjs";

async function Page() { const user = await currentUser();

const userInfo = { id: "", username: "", name: "", bio: "", image: "", };

const userData = { id: user?.id || "", // Provide a default value if user?.id is undefined objectId: userInfo?.id, username: userInfo?.username || user?.username || "", name: userInfo?.name || user?.firstName || "", bio: userInfo?.bio || "", image: userInfo?.image || user?.imageUrl || "", }; return (

Onboarding

complete your profile to be able to use Thread

  <section className="mt-9 bg-dark-2 p-10">
    <AccountProfile user={userData} />
  </section>
</main>

); }

export default Page;

this is working for me

This helped, thank you! @Avish24x

@Avish24x
Copy link

Avish24x commented Aug 31, 2023

image

can someone help me please, i've been stuck for 2 days, i dont know why some classname not executed in my code, i do the tutorial clearly step by step , when i put classname that not in global css, it's not executed, exampe, this navbar background suppose to be black, and the image in next of threads text. please help me guys

try this your its the image you are trying to import..

// Image src="remove the braces" alt="logo" width={28} height={28} />

@Avish24x
Copy link

Hi guys, I'm having this error in the process of implementing updateUser() image really need your help, cause I have checked the typo and found no differents

You should check if you are using "use server" because you cant directly created database action through the browser side

@manipriyan77
Copy link

manipriyan77 commented Aug 31, 2023

image

getting a error like this while adding the custom global.css tailwind files can anyone help me to resolve this

@nullius-inVerba
Copy link

nullius-inVerba commented Sep 1, 2023

pic
This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

@Avish24x
Copy link

Avish24x commented Sep 1, 2023

pic This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

show the whole code brother

@nullius-inVerba
Copy link

pic This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

show the whole code brother
pic
I'm following exactly from the video.

@Avish24x
Copy link

Avish24x commented Sep 1, 2023

pic This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

show the whole code brother
pic
I'm following exactly from the video.

Can i see your the page in the browser ?

@Avish24x
Copy link

Avish24x commented Sep 1, 2023

pic This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

show the whole code brother
pic
I'm following exactly from the video.

you need to be signed in to see the OrganizationSwitcher
everything seems okay on your code tbh

@Akaikenlol
Copy link

Akaikenlol commented Sep 1, 2023

scrnli_17_08_2023 15-23-56 I have set up clerk as in the video but i still get this error. Can anyone help !

have you been able to find a solution ?

About this problem,

I try comment out the ClerkProvider tag in app>(auth)> layout.tsx file.
This solution work for me.
Forgive me if not working for you.

@Madhannmady07
Copy link

Screenshot 2023-09-03 090549

I'm getting this error , eventhough i went thru everything is correct . I don't know how to solve it . Please someone help me complete this .

@mihirksingh21
Copy link

image
can anyone help me resolving this issue while clearting App>(Auth)

@AstroKnight19
Copy link

AstroKnight19 commented Sep 3, 2023

s1
s2

How can I solve this issues and it shows 32 warning (unknown rule at @tailwind CSS[@APPY and imports]) in globals.css and iam having tsconfig.ts instead of .js / WHAT CAN I DO TO RESOLVE IT ?

@TiTANWASTAKEN
Copy link

Hey guys, i'm stuck on the connecting to the database, on my console its not even detecting if I'm connected to a database at all. I've gone through the code countless times and still cant find the issue. when I click submit nothing happens. it just shows this. error

am getting the same error . did anyone find or knows the solution to this ?

@nullius-inVerba
Copy link

pic This OrganizationSwitcher is not showing up in my app. I restarted the app many times, I even created a new app in Clerk just in case there were any issues from their side. There are no terminal errors, so I don't understand the issue here. Does anyone have any clue what could be wrong here?

show the whole code brother
pic
I'm following exactly from the video.

you need to be signed in to see the OrganizationSwitcher everything seems okay on your code tbh

Thanks for the help. I resolved the issue. I wrongly placed the <ClerkProvider/ > directly inside the HTML tag in the layout.tsx of the root folder instead of wrapping the body with it.

@nullius-inVerba
Copy link

nullius-inVerba commented Sep 3, 2023

image can anyone help me resolving this issue while clearting App>(Auth)

Did you provide ClerkProvider at both layout.tsx (auth and root folder)?

@BhattacharjiHRB
Copy link

image can anyone help me resolving this issue while clearting App>(Auth)

Did you provide ClerkProvider at both layout.tsx (auth and root folder)?

yess wrap the layout with ClerkProvider

@wesley-codes
Copy link

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.

Screenshot 2023-09-06 at 7 38 31 PM

@wesley-codes
Copy link

Did you fix this error?

No, I haven't. Do you have an idea ?

@itisMilan
Copy link

Screenshot 2023-08-08 at 11 57 53 PM I am getting this error while posting the thread. Can anyone please help in this regard?

Did you fix the bug?

Did you fix this error?

@temiloluwaalabi
Copy link

Good day, so I'm done with the project. No errors but I noticed after joining communities, the members field in the database doesn't get filled with the users Id and I'm unable to fetch all the members in a community

@Tuong-Duy-Anh
Copy link

Hi guys, I'm having this error in the process of implementing updateUser() image really need your help, cause I have checked the typo and found no differents

You should check if you are using "use server" because you cant directly created database action through the browser side

I have add the "use server" on the user.model.ts file but the problem still persist

@Akaikenlol
Copy link

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.

Screenshot 2023-09-06 at 7 38 31 PM

Same here sir. Did u find the solution for this error?

@wesley-codes
Copy link

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.
Screenshot 2023-09-06 at 7 38 31 PM

Same here sir. Did u find the solution for this error?

No, I didn’t. Still trying to fix it.

@Akaikenlol
Copy link

Akaikenlol commented Sep 10, 2023

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.
Screenshot 2023-09-06 at 7 38 31 PM

Same here sir. Did u find the solution for this error?

No, I didn’t. Still trying to fix it.

Sir, i found the solution for this sir, now my website deployment is okay now.
This is the solution from stack overflow.
It's work for me.

NOTE: Vercel uses dynamic IP addresses so you'll need to add an exception to access from any IP address in your MongoDB Atlas dashboard. To do this simplify navigate to the Network Access tab, hit the Add IP Address button, and then hit the Allow Access From Anywhere button or for the Access List Entry enter 0.0.0/0.

Here the result
image

@wesley-codes
Copy link

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.
Screenshot 2023-09-06 at 7 38 31 PM

Same here sir. Did u find the solution for this error?

No, I didn’t. Still trying to fix it.

Sir, i found the solution for this sir, now my website deployment is okay now. This is the solution from stack overflow. It's work for me.

NOTE: Vercel uses dynamic IP addresses so you'll need to add an exception to access from any IP address in your MongoDB Atlas dashboard. To do this simplify navigate to the Network Access tab, hit the Add IP Address button, and then hit the Allow Access From Anywhere button or for the Access List Entry enter 0.0.0/0.

Here the result image

Thank you,sir
It worked 👍🏻

@Akaikenlol
Copy link

Hi fellows, I have encountered issue in webhook (at least I believe so). The coummnity wasn't able to be added in to database, and the vercel returns 504 after logged in. I can't even reach the home page as video showed. Not sure which step(s) were wrong. image

Sir if you are still doing this project and if u still can't find the solution , I post the solution post above this reply sir.

@wesley-codes
Copy link

Good day. I tried creating a Thread within the clerk community, but the communityIdObject returns null.
Screenshot 2023-09-12 at 1 57 49 PM

@MFathurrohmanMauludin
Copy link

MFathurrohmanMauludin commented Sep 14, 2023

s1 s2

How can I solve this issues and it shows 32 warning (unknown rule at @tailwind CSS[@APPY and imports]) in globals.css and iam having tsconfig.ts instead of .js / WHAT CAN I DO TO RESOLVE IT?

First problem:
You can check whether the file exists by pressing the file path by holding down the CTRL key and then clicking.
or you can type or copy this path '../globals.css'.

Second problem:
I think you can follow the following method:
https://www.codeconcisely.com/posts/tailwind-css-unknown-at-rules/#adding-custom-at-rules

@rahulc0dy
Copy link

image
image

says true is not a type for required and the submit button does not work
https://youtu.be/O5cmLDVTgAs?feature=shared&t=8414 at 2:20:00

@Avish24x
Copy link

Avish24x commented Sep 14, 2023 via email

@msagerup
Copy link

Hi guys, I'm having this error in the process of implementing updateUser() image really need your help, cause I have checked the typo and found no differents

You should check if you are using "use server" because you cant directly created database action through the browser side

console log is your friend

@aman-senpai
Copy link

image

getting a error like this while adding the custom global.css tailwind files can anyone help me to resolve this

Set tailwind.config.ts first

@HunnyHunnyail
Copy link

HunnyHunnyail commented Sep 21, 2023

Hi Adrian, I hope you're doing good!
I'm having an error but not sure why, the app was and is running fine I am at the part where you start to implement the comments functionality.
But expectedly my computer got shut down and when I restarted it again and ran application again, then I started getting the error.

Even though this error occurs the adding post functionality stills works signing in is working even the post are being fetched and also database works fine but it's occuring from the currentUser that we're importing from the clerk, where ever the const user = await currentUser() is the error occurs.

I tried googling the error but didn't find any results.

image

Waiting for your reply....

@Lpreets
Copy link

Lpreets commented Sep 21, 2023

Hi!

This is especially for those who have problems with "OrganizationSwitcher"

I recently went back and tried to look into this. I couldn't anything wrong in the code, but I tried updating clerk just in case.
I then went to Clerk Dashboard and saw that I haven't enabled Organizations there!
So if you can't find a error in the code it might be the reason why.

Hopefully this helps anyone who might be having the same issues.

@HiLakshya
Copy link

This is the updated tailwind.config.ts if anyone is facing any error while getting started with global.css :

/** @type {import('tailwindcss').Config} */
module.exports = {

  plugins: [require("tailwindcss-animate")],
  
  darkMode: ["class"],
  content: [
    "./pages/**/*.{ts,tsx}",
    "./components/**/*.{ts,tsx}",
    "./app/**/*.{ts,tsx}",
    "./src/**/*.{ts,tsx}",
  ],
  theme: {
    container: {
      center: true,
      padding: "2rem",
      screens: {
        "2xl": "1400px",
      },
    },
    fontSize: {
      "heading1-bold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading1-semibold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading2-bold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading2-semibold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading3-bold": [
        "24px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading4-medium": [
        "20px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "body-semibold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "body-medium": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-normal": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "body1-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "base-regular": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "base-medium": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "base-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "base1-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "small-regular": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "small-medium": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "small-semibold": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "subtle-medium": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "500",
        },
      ],
      "subtle-semibold": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "600",
        },
      ],
      "tiny-medium": [
        "10px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "x-small-semibold": [
        "7px",
        {
          lineHeight: "9.318px",
          fontWeight: "600",
        },
      ],
    },
    extend: {
      colors: {
        "primary-500": "#877EFF",
        "secondary-500": "#FFB620",
        blue: "#0095F6",
        "logout-btn": "#FF5A5A",
        "navbar-menu": "rgba(16, 16, 18, 0.6)",
        "dark-1": "#000000",
        "dark-2": "#121417",
        "dark-3": "#101012",
        "dark-4": "#1F1F22",
        "light-1": "#FFFFFF",
        "light-2": "#EFEFEF",
        "light-3": "#7878A3",
        "light-4": "#5C5C7B",
        "gray-1": "#697C89",
        glassmorphism: "rgba(16, 16, 18, 0.60)",
      },
      boxShadow: {
        "count-badge": "0px 0px 6px 2px rgba(219, 188, 159, 0.30)",
        "groups-sidebar": "-30px 0px 60px 0px rgba(28, 28, 31, 0.50)",
      },
      screens: {
        xs: "400px",
      },
      keyframes: {
        "accordion-down": {
          from: { height: 0 },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: 0 },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
  // plugins: [require("tailwindcss-animate")],
};

@MFathurrohmanMauludin
Copy link

Hi Adrian, I hope you're doing good! I'm having an error but not sure why, the app was and is running fine I am at the part where you start to implement the comments functionality. But expectedly my computer got shut down and when I restarted it again and ran application again, then I started getting the error.

Even though this error occurs the adding post functionality stills works signing in is working even the post are being fetched and also database works fine but it's occuring from the currentUser that we're importing from the clerk, where ever the const user = await currentUser() is the error occurs.

I tried googling the error but didn't find any results.

image

Waiting for your reply....

you can check your "userSchema" (user.model.ts) and test with console.log() or using try catch.

@benjiroooo
Copy link

Does anybody else have a problem where the communities that are created, aren't being saved in MongoDB? My webhook is also going crazy with just saying attempting for each event:

image

image

Sorry if this is vague, just curious if other people have had the same problem

@HerbertNtim
Copy link

Screenshot (12)
I am facing this error after I logged myself out to check the authetication

@acelcabang123
Copy link

why is my mobile mode is vertical?? not horizontal?
image

@Hasham268
Copy link

Does anybody else have a problem where the communities that are created, aren't being saved in MongoDB? My webhook is also going crazy with just saying attempting for each event:

image

image

Sorry if this is vague, just curious if other people have had the same problem
I am also facing the same issue. Did you find any solution ?

@benjiroooo
Copy link

Does anybody else have a problem where the communities that are created, aren't being saved in MongoDB? My webhook is also going crazy with just saying attempting for each event:
image
image
Sorry if this is vague, just curious if other people have had the same problem
I am also facing the same issue. Did you find any solution ?

I did find a solution! I entered the wrong link for the deployment endpoint from vercel. Go on vercel and grab the deployment link and not the link from when you go to the deployed site in the search bar

@temiloluwaalabi
Copy link

temiloluwaalabi commented Oct 2, 2023 via email

@mujtbkhn
Copy link

mujtbkhn commented Oct 5, 2023

I tried deploying to vercel so I can add my URL in clerk we hook but it says “This Serverless Function has timed out.” with no build error.
Screenshot 2023-09-06 at 7 38 31 PM

Same here sir. Did u find the solution for this error?

No, I didn’t. Still trying to fix it.

Sir, i found the solution for this sir, now my website deployment is okay now. This is the solution from stack overflow. It's work for me.

NOTE: Vercel uses dynamic IP addresses so you'll need to add an exception to access from any IP address in your MongoDB Atlas dashboard. To do this simplify navigate to the Network Access tab, hit the Add IP Address button, and then hit the Allow Access From Anywhere button or for the Access List Entry enter 0.0.0/0.

Here the result image

Sirrrrrrr!! Thank You Sirrr!

@ParastooMarzi
Copy link

ParastooMarzi commented Oct 9, 2023

Screenshot 2023-10-09 035155

Hi, I can't fix this Error,
I didn't any changes in global.css file. I don'nt know why it happened

@temiloluwaalabi
Copy link

temiloluwaalabi commented Oct 9, 2023 via email

@ParastooMarzi
Copy link

thank you so much sir, I changed my tailwind.config and proble solved

@mujtbkhn
Copy link

mujtbkhn commented Oct 9, 2023

image
can anyone please help me with this , i am unable to see the communities thread i made two communities did exactly as mentioned in the videos cross checked every file of mine with adrian still unable to find the solution ie when creating thread with any community it gets created as "Mujtaba khan" which is my name , please help out on this!

@mujtbkhn
Copy link

mujtbkhn commented Oct 9, 2023

image can anyone please help me with this , i am unable to see the communities thread i made two communities did exactly as mentioned in the videos cross checked every file of mine with adrian still unable to find the solution ie when creating thread with any community it gets created as "Mujtaba khan" which is my name , please help out on this!

heres the deployed link to my threads
https://mujtabas-threads-rd4ujozow-mujjukhn538-gmailcom.vercel.app/

@temiloluwaalabi
Copy link

temiloluwaalabi commented Oct 9, 2023 via email

@fasaya
Copy link

fasaya commented Oct 9, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response
"ERROR": {"message: "src property must be a valid json object"}

Screenshot 2023-10-09 at 10 27 35 PM
Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

@ng9000
Copy link

ng9000 commented Oct 10, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response "ERROR": {"message: "src property must be a valid json object"}

Screenshot 2023-10-09 at 10 27 35 PM Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

steps -

  1. Go to vercel- your threads project- visit
  2. Copy its link from search bar
  3. Go to clerk - webhook
  4. Add new endpoint "copied link from step 1/api/webhook/clerk"
  5. get its signing secret and add it to environment variables in vercel

this will solve your problem

@fasaya
Copy link

fasaya commented Oct 10, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response "ERROR": {"message: "src property must be a valid json object"}
Screenshot 2023-10-09 at 10 27 35 PM Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

steps -

  1. Go to vercel- your threads project- visit
  2. Copy its link from search bar
  3. Go to clerk - webhook
  4. Add new endpoint "copied link from step 1/api/webhook/clerk"
  5. get its signing secret and add it to environment variables in vercel

this will solve your problem

Thank you for replying. I've actually done that. But still getting the same error.

@ng9000
Copy link

ng9000 commented Oct 10, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response "ERROR": {"message: "src property must be a valid json object"}
Screenshot 2023-10-09 at 10 27 35 PM Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

steps -

  1. Go to vercel- your threads project- visit
  2. Copy its link from search bar
  3. Go to clerk - webhook
  4. Add new endpoint "copied link from step 1/api/webhook/clerk"
  5. get its signing secret and add it to environment variables in vercel

this will solve your problem

Thank you for replying. I've actually done that. But still getting the same error.

try redeploying the project and follow from step 1

@fasaya
Copy link

fasaya commented Oct 10, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response "ERROR": {"message: "src property must be a valid json object"}
Screenshot 2023-10-09 at 10 27 35 PM Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

steps -

  1. Go to vercel- your threads project- visit
  2. Copy its link from search bar
  3. Go to clerk - webhook
  4. Add new endpoint "copied link from step 1/api/webhook/clerk"
  5. get its signing secret and add it to environment variables in vercel

this will solve your problem

Thank you for replying. I've actually done that. But still getting the same error.

try redeploying the project and follow from step 1

I finally solved it! Turns out my middleware is missing the "/" in front of the strings. Thank you tho!

@ParastooMarzi
Copy link

Screenshot (5)

Hi there!
What should I do with this unhandled error
Also in MongoDB collection section I have two choice: load a sample database and add my own data
I really confused

@ParastooMarzi
Copy link

Screenshot (6)

@temiloluwaalabi
Copy link

temiloluwaalabi commented Oct 10, 2023 via email

@ParastooMarzi
Copy link

Screenshot (7)

@mujtbkhn
Copy link

Hello there, check through your database to make sure the community was created also cross check to see if the questions should added under the community was added to the questions field in the community database. Make sure, you’ve changed from the user profile to the organization profile from the frontend before typing your threads. If all of this mentioned above is correct then you need to check through your code especially the comment or thread box to see you’re properly fetching the right informations.

On Mon, 9 Oct 2023 at 12:08, Mujtaba Khan @.> wrote: @.* commented on this gist. ------------------------------ [image: image] https://user-images.githubusercontent.com/86319200/273566716-4de8fa62-666b-448b-a4b2-46ea316a468a.png can anyone please help me with this , i am unable to see the communities thread i made two communities did exactly as mentioned in the videos cross checked every file of mine with adrian still unable to find the solution ie when creating thread with any community it gets created as "Mujtaba khan" which is my name , please help out on this! — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-4718716 or unsubscribe https://github.com/notifications/unsubscribe-auth/AOCUBOGUOJ5JTVMSH3D53L3X6PLKBBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFQKSXMYLMOVS2I5DSOVS2I3TBNVS3W5DIOJSWCZC7OBQXE5DJMNUXAYLOORPWCY3UNF3GS5DZVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub .

hey man sorry for the late reply i checked in mongoDB for community and found out i donot have any community colllection but i followed everything accordingly while making the community schema
image
please look into it and help me i really am getting frustrated of this
Thank You

@RickyFirmansyah27
Copy link

my organiaztion not show i try organization to sidebar but not show after all
image

@RickyFirmansyah27
Copy link

image

everythink is oke but only organiaztion swith not shown in my code

@Cllinlovetocode
Copy link

This is the updated tailwind.config.ts if anyone is facing any error while getting started with global.css :

/** @type {import('tailwindcss').Config} */
module.exports = {

  plugins: [require("tailwindcss-animate")],
  
  darkMode: ["class"],
  content: [
    "./pages/**/*.{ts,tsx}",
    "./components/**/*.{ts,tsx}",
    "./app/**/*.{ts,tsx}",
    "./src/**/*.{ts,tsx}",
  ],
  theme: {
    container: {
      center: true,
      padding: "2rem",
      screens: {
        "2xl": "1400px",
      },
    },
    fontSize: {
      "heading1-bold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading1-semibold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading2-bold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading2-semibold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading3-bold": [
        "24px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading4-medium": [
        "20px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "body-semibold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "body-medium": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-normal": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "body1-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "base-regular": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "base-medium": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "base-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "base1-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "small-regular": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "small-medium": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "small-semibold": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "subtle-medium": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "500",
        },
      ],
      "subtle-semibold": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "600",
        },
      ],
      "tiny-medium": [
        "10px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "x-small-semibold": [
        "7px",
        {
          lineHeight: "9.318px",
          fontWeight: "600",
        },
      ],
    },
    extend: {
      colors: {
        "primary-500": "#877EFF",
        "secondary-500": "#FFB620",
        blue: "#0095F6",
        "logout-btn": "#FF5A5A",
        "navbar-menu": "rgba(16, 16, 18, 0.6)",
        "dark-1": "#000000",
        "dark-2": "#121417",
        "dark-3": "#101012",
        "dark-4": "#1F1F22",
        "light-1": "#FFFFFF",
        "light-2": "#EFEFEF",
        "light-3": "#7878A3",
        "light-4": "#5C5C7B",
        "gray-1": "#697C89",
        glassmorphism: "rgba(16, 16, 18, 0.60)",
      },
      boxShadow: {
        "count-badge": "0px 0px 6px 2px rgba(219, 188, 159, 0.30)",
        "groups-sidebar": "-30px 0px 60px 0px rgba(28, 28, 31, 0.50)",
      },
      screens: {
        xs: "400px",
      },
      keyframes: {
        "accordion-down": {
          from: { height: 0 },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: 0 },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
  // plugins: [require("tailwindcss-animate")],
};

Hi there, thank you for shareing the updated tailwind.config.ts, i copy this code on my tailwind.config.ts, but the Syntax error of bg-dark-2 is still there, can you tell me what should do to fix it ?

@Oise1234
Copy link

I am having issue with my create-thread page.

Every time I attempt to go over there, it redirects me back to the onboarding page

@ng9000
Copy link

ng9000 commented Oct 27, 2023

I am having issue with my create-thread page.

Every time I attempt to go over there, it redirects me back to the onboarding page

You need to check your updateUser function and also in your mongo db that if onboarded is true or not. Also look in below screenshot and verify dont add other stuff just look at underlined code.
image

const user = await currentUser();
if (!user) return null;

const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

this above code redirects you back to onboarding log userInfo to check if onboarded is true or not

@Oise1234
Copy link

I am having issue with my create-thread page.
Every time I attempt to go over there, it redirects me back to the onboarding page

You need to check your updateUser function and also in your mongo db that if onboarded is true or not. Also look in below screenshot and verify dont add other stuff just look at underlined code. image

const user = await currentUser();
if (!user) return null;

const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

this above code redirects you back to onboarding log userInfo to check if onboarded is true

Thanks, that helped me a ton

@Oise1234
Copy link

Could you help me with another problem?

I am trying to post a thread but It gives me an error that says:

validation failed: author: Cast to ObjectId failed for value "user_2WzUyloILerRvAz7R6ZgWSGb034" (type string) at path "author" because of "BSONError"

@ng9000
Copy link

ng9000 commented Oct 27, 2023

Could you help me with another problem?

I am trying to post a thread but It gives me an error that says:

validation failed: author: Cast to ObjectId failed for value "user_2WzUyloILerRvAz7R6ZgWSGb034" (type string) at path "author" because of "BSONError"

Ok so look at your create-thread route you have to pass _id in userStringId
verify below SS if not solved share your code so I can look at it
image

@Oise1234
Copy link

Could you help me with another problem?
I am trying to post a thread but It gives me an error that says:
validation failed: author: Cast to ObjectId failed for value "user_2WzUyloILerRvAz7R6ZgWSGb034" (type string) at path "author" because of "BSONError"

Ok so look at your create-thread route you have to pass _id in userStringId verify below SS if not solved share your code so I can look at it image

Thanks, it fixed my problem.

@ianh8899
Copy link

Hi, I'm really struggling with the below issue. I've cleared the cache and used the updated tailwind, deleted node modules and re-installed but I still get this error. Any ideas?

image

@Prasannad02
Copy link

Screenshot (1)
I am getting this error in terminal Unrecognized key(s) in object: 'typescript' at "images" can anyone solve this

@ng9000
Copy link

ng9000 commented Oct 31, 2023

Screenshot (1) I am getting this error in terminal Unrecognized key(s) in object: 'typescript' at "images" can anyone solve this

https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#file-next-config-js
Copy this file in next.config.js

@Prasannad02
Copy link

Screenshot (1) I am getting this error in terminal Unrecognized key(s) in object: 'typescript' at "images" can anyone solve this

https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#file-next-config-js Copy this file in next.config.js

It's still showing this error Unrecognized key(s) in object: 'typescript' at "images"

@Moniruzzaman2525
Copy link

comment global css and un comment and again start

@Prasannad02
Copy link

comment global css and un comment and again start

no it's still showing this Invalid next.config.js options detected:
Unrecognized key(s) in object: 'typescript' at "images"

@SaurabPoudel
Copy link

comment global css and un comment and again start

no it's still showing this Invalid next.config.js options detected: Unrecognized key(s) in object: 'typescript' at "images"

this works for me but feel free to copy the next.config.js file from the source code itself

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "img.clerk.com",
      },
      {
        protocol: "https",
        hostname: "images.clerk.dev",
      },
      {
        protocol: "https",
        hostname: "uploadthing.com",
      },
      {
        protocol: "https",
        hostname: "placehold.co",
      },
    ],
  },
};

module.exports = nextConfig;

@minhnghia2k3
Copy link

Screenshot (1) I am getting this error in terminal Unrecognized key(s) in object: 'typescript' at "images" can anyone solve this

https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#file-next-config-js Copy this file in next.config.js

It's still showing this error Unrecognized key(s) in object: 'typescript' at "images"

I think it may has mistake here. The "typescript" must be outside of "images" object like this:

/** @type {import('next').NextConfig} */
const nextConfig = {
    experimental: {
        serverActions: true,
        serverComponentsExternalPackages: ["mongoose"],
    },
    images: {
        remotePatterns: [
            {
                protocol: "https",
                hostname: "img.clerk.com",
            },
            {
                protocol: "https",
                hostname: "images.clerk.dev",
            },
            {
                protocol: "https",
                hostname: "uploadthing.com",
            },
            {
                protocol: "https",
                hostname: "placehold.co",
            },
        ],
    },
    typescript: {
        ignoreBuildErrors: true,
    },
};

module.exports = nextConfig;

@Prasannad02
Copy link

comment global css and un comment and again start

no it's still showing this Invalid next.config.js options detected: Unrecognized key(s) in object: 'typescript' at "images"

this works for me but feel free to copy the next.config.js file from the source code itself

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "img.clerk.com",
      },
      {
        protocol: "https",
        hostname: "images.clerk.dev",
      },
      {
        protocol: "https",
        hostname: "uploadthing.com",
      },
      {
        protocol: "https",
        hostname: "placehold.co",
      },
    ],
  },
};

module.exports = nextConfig;

thank you minhnghia2k3 It's working

@Bamzhie
Copy link

Bamzhie commented Nov 4, 2023

4. api/webhook/clerk

hi, did you solve it? i'm having the same problem

@Bamzhie
Copy link

Bamzhie commented Nov 5, 2023

Does anyone have the same problem? The webhook keeps failing. It always returns 401 with this response "ERROR": {"message: "src property must be a valid json object"}
Screenshot 2023-10-09 at 10 27 35 PM Screenshot 2023-10-09 at 10 28 13 PM

// middleware.ts

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

export default authMiddleware({
    publicRoutes: ['api/webhook/clerk'],
    ignoredRoutes: ['api/webhook/clerk'],
    debug: true
});

export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

steps -

  1. Go to vercel- your threads project- visit
  2. Copy its link from search bar
  3. Go to clerk - webhook
  4. Add new endpoint "copied link from step 1/api/webhook/clerk"
  5. get its signing secret and add it to environment variables in vercel

this will solve your problem

Thank you for replying. I've actually done that. But still getting the same error.

try redeploying the project and follow from step 1

I finally solved it! Turns out my middleware is missing the "/" in front of the strings. Thank you tho!

hello i'm facing same problem. front of what string is the "/" missing? please

@pranjalbansal200
Copy link

I was making the Profile Tab where people can see their profile and threads and other's profile. I have done everything as per instructions, but I am not getting the threads displayed on the profile page as well as on the tab also it is showing 0 threads when I have posted 2 threads, I am unable to understand what the problem is. This is my github link: https://github.com/pranjalbansal200/threads , it will be really helpful if anyone can provide the solution

@LeinahI
Copy link

LeinahI commented Nov 14, 2023

Why the comment/replies doesn't shows up?
image

My code:
image

My MongoDB:
image

The thing I want to achieve 3:43:21
image

My whole code: https://github.com/LeinahI/Chirpy

@saadahmad-1
Copy link

This is the updated tailwind.config.ts if anyone is facing any error while getting started with global.css :

/** @type {import('tailwindcss').Config} */
module.exports = {

  plugins: [require("tailwindcss-animate")],
  
  darkMode: ["class"],
  content: [
    "./pages/**/*.{ts,tsx}",
    "./components/**/*.{ts,tsx}",
    "./app/**/*.{ts,tsx}",
    "./src/**/*.{ts,tsx}",
  ],
  theme: {
    container: {
      center: true,
      padding: "2rem",
      screens: {
        "2xl": "1400px",
      },
    },
    fontSize: {
      "heading1-bold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading1-semibold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading2-bold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading2-semibold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading3-bold": [
        "24px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading4-medium": [
        "20px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "body-semibold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "body-medium": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-normal": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "body1-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "base-regular": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "base-medium": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "base-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "base1-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "small-regular": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "small-medium": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "small-semibold": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "subtle-medium": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "500",
        },
      ],
      "subtle-semibold": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "600",
        },
      ],
      "tiny-medium": [
        "10px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "x-small-semibold": [
        "7px",
        {
          lineHeight: "9.318px",
          fontWeight: "600",
        },
      ],
    },
    extend: {
      colors: {
        "primary-500": "#877EFF",
        "secondary-500": "#FFB620",
        blue: "#0095F6",
        "logout-btn": "#FF5A5A",
        "navbar-menu": "rgba(16, 16, 18, 0.6)",
        "dark-1": "#000000",
        "dark-2": "#121417",
        "dark-3": "#101012",
        "dark-4": "#1F1F22",
        "light-1": "#FFFFFF",
        "light-2": "#EFEFEF",
        "light-3": "#7878A3",
        "light-4": "#5C5C7B",
        "gray-1": "#697C89",
        glassmorphism: "rgba(16, 16, 18, 0.60)",
      },
      boxShadow: {
        "count-badge": "0px 0px 6px 2px rgba(219, 188, 159, 0.30)",
        "groups-sidebar": "-30px 0px 60px 0px rgba(28, 28, 31, 0.50)",
      },
      screens: {
        xs: "400px",
      },
      keyframes: {
        "accordion-down": {
          from: { height: 0 },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: 0 },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
  // plugins: [require("tailwindcss-animate")],
};

Hi there, thank you for shareing the updated tailwind.config.ts, i copy this code on my tailwind.config.ts, but the Syntax error of bg-dark-2 is still there, can you tell me what should do to fix it ?

I'm too still having the error.
Screenshot 2023-11-25 192127

@LeinahI
Copy link

LeinahI commented Nov 25, 2023

This is the updated tailwind.config.ts if anyone is facing any error while getting started with global.css :

/** @type {import('tailwindcss').Config} */
module.exports = {

  plugins: [require("tailwindcss-animate")],
  
  darkMode: ["class"],
  content: [
    "./pages/**/*.{ts,tsx}",
    "./components/**/*.{ts,tsx}",
    "./app/**/*.{ts,tsx}",
    "./src/**/*.{ts,tsx}",
  ],
  theme: {
    container: {
      center: true,
      padding: "2rem",
      screens: {
        "2xl": "1400px",
      },
    },
    fontSize: {
      "heading1-bold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading1-semibold": [
        "36px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading2-bold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading2-semibold": [
        "30px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "heading3-bold": [
        "24px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "heading4-medium": [
        "20px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "body-semibold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "body-medium": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "body-normal": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "body1-bold": [
        "18px",
        {
          lineHeight: "140%",
          fontWeight: "700",
        },
      ],
      "base-regular": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "base-medium": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "base-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "base1-semibold": [
        "16px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "small-regular": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "400",
        },
      ],
      "small-medium": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "small-semibold": [
        "14px",
        {
          lineHeight: "140%",
          fontWeight: "600",
        },
      ],
      "subtle-medium": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "500",
        },
      ],
      "subtle-semibold": [
        "12px",
        {
          lineHeight: "16px",
          fontWeight: "600",
        },
      ],
      "tiny-medium": [
        "10px",
        {
          lineHeight: "140%",
          fontWeight: "500",
        },
      ],
      "x-small-semibold": [
        "7px",
        {
          lineHeight: "9.318px",
          fontWeight: "600",
        },
      ],
    },
    extend: {
      colors: {
        "primary-500": "#877EFF",
        "secondary-500": "#FFB620",
        blue: "#0095F6",
        "logout-btn": "#FF5A5A",
        "navbar-menu": "rgba(16, 16, 18, 0.6)",
        "dark-1": "#000000",
        "dark-2": "#121417",
        "dark-3": "#101012",
        "dark-4": "#1F1F22",
        "light-1": "#FFFFFF",
        "light-2": "#EFEFEF",
        "light-3": "#7878A3",
        "light-4": "#5C5C7B",
        "gray-1": "#697C89",
        glassmorphism: "rgba(16, 16, 18, 0.60)",
      },
      boxShadow: {
        "count-badge": "0px 0px 6px 2px rgba(219, 188, 159, 0.30)",
        "groups-sidebar": "-30px 0px 60px 0px rgba(28, 28, 31, 0.50)",
      },
      screens: {
        xs: "400px",
      },
      keyframes: {
        "accordion-down": {
          from: { height: 0 },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: 0 },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
  // plugins: [require("tailwindcss-animate")],
};

Hi there, thank you for shareing the updated tailwind.config.ts, i copy this code on my tailwind.config.ts, but the Syntax error of bg-dark-2 is still there, can you tell me what should do to fix it ?

I'm too still having the error. Screenshot 2023-11-25 192127

that bg-dark-2 came from tailwind.config.js

@rjay-git
Copy link

Im having issue calling onSubmit. When debugging, it hits the onSubmit button but it doesnt go inside the function. Like in this screenshot, it doesnt go to the next line 54
image

@rjay-git
Copy link

rjay-git commented Dec 2, 2023

Im having issue calling onSubmit. When debugging, it hits the onSubmit button but it doesnt go inside the function. Like in this screenshot, it doesnt go to the next line 54 image

nvm i found it. its a typo

@kravitexx
Copy link

Screenshot (6)

did you got the solution?

@kravitexx
Copy link

I just cloned the repo from github into my PC and then installed all the required things..as per video. Then I also changed the global and tailwindconfig.js as per the video after shadcn init. and also made env.local and all the API needed. so after doing all the steps from video. I have not yet replayed the website or hosted it on server. It is still in my PC.
After running it , I got this error.
Screenshot (242)
and this in the vs code terminal:
▲ Next.js 14.0.3

⚠ Invalid next.config.js options detected:
⚠ Expected object, received boolean at "experimental.serverActions"
⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config
⚠ Server Actions are available by default now, experimental.serverActions option can be safely removed.
✓ Ready in 4.6s
○ Compiling /middleware ...
✓ Compiled /middleware in 563ms (273 modules)
○ Compiling / ...
✓ Compiled / in 3.6s (1105 modules)
(node:9496) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.
(Use node --trace-deprecation ... to show where the warning was created)
✓ Compiled in 1599ms (404 modules)
MongoDB connected
MongoServerError: bad auth : authentication failed
at Connection.onMessage (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:202:26)
at MessageStream. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:61:60)
at MessageStream.emit (node:events:519:28)
at processIncomingData (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
at MessageStream._write (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:564:12)
at _write (node:internal/streams/writable:493:10)
at Writable.write (node:internal/streams/writable:502:10)
at TLSSocket.ondata (node:internal/streams/readable:1007:22)
at TLSSocket.emit (node:events:519:28)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)
at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)
at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
ok: 0,
code: 8000,
codeName: 'AtlasError',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}
Error fetching users: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms
at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms
at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms
at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
digest: "3882132667"
⨯ lib\actions\user.actions.ts (21:10) @ fetchUser
⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms
at fetchUser (./lib/actions/user.actions.ts:36:15)
at async Home (page.tsx:24:22)
19 | });
20 | } catch (error: any) {

21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |
⨯ lib\actions\user.actions.ts (21:10) @ fetchUser
⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms
at fetchUser (./lib/actions/user.actions.ts:36:15)
at async Home (page.tsx:24:22)
digest: "2116173799"
19 | });
20 | } catch (error: any) {
21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |

Please do help me with this

@alimbit
Copy link

alimbit commented Dec 7, 2023

I installed the tailwind-animate after that I didn't get the bg-dark-2 missing class error one thing I also did is I copied the code of tailwind from the GitHub repository not from the gist files.

@btreynor
Copy link

@LeinahI, did you ever figure out why the replies to the comments were not showing? I am having similar issues on my side as well. Thanks for any help.

@btreynor
Copy link

@LeinahI Never mind. I figured out the issue. Thanks anyway

@Sarthak412
Copy link

I am facing an issue with the Clerk Authentication. When I run "npm run dev" my application is directly loading the home page of Threads instead of taking me to sign-in page. Can anyone please help me with this issue?

@Kevttv
Copy link

Kevttv commented Dec 13, 2023

I need help, I just started with the tutorial but I have this problem
error

@Kevttv
Copy link

Kevttv commented Dec 13, 2023

The next js version has something to do with the error?

@Blitz03
Copy link

Blitz03 commented Dec 14, 2023

I need help, I just started with the tutorial but I have this problem error

Wrap your application with ClerkProvider in the layout.tsx files in both the (auth) and (root) folders.

@BREW45Z
Copy link

BREW45Z commented Dec 15, 2023

please i keep having this problem when i try to create thread, when i type in and click submit i get a message like invalid url
Screenshot 2023-12-15 at 13 51 25
Screenshot 2023-12-15 at 13 53 26

@Kevttv
Copy link

Kevttv commented Dec 15, 2023

I have a new problem, it says that the cookie "__client_uat" has been rejected by an invalid domain.

imagen

@Kevttv
Copy link

Kevttv commented Dec 15, 2023

imagen

@Sarthak412
Copy link

please i keep having this problem when i try to create thread, when i type in and click submit i get a message like invalid url Screenshot 2023-12-15 at 13 51 25 Screenshot 2023-12-15 at 13 53 26

Try adding userId={userInfo._id} in your PostThread component.

@THOUFIQHUSSAIN-J
Copy link

please i keep having this problem when i try to create thread, when i type in and click submit i get a message like invalid url Screenshot 2023-12-15 at 13 51 25 Screenshot 2023-12-15 at 13 53 26

Check the ThreadValidation->threads.ts file, remove .url() from the thread object.

@aarondacua
Copy link

aarondacua commented Dec 21, 2023

To prevent Clerk authentication from protecting (401) the api route, remove the rule matching "/api/uploadthing" from the apiRoutes array passed to authMiddleware
2. To make the route accessible to both signed in and signed out users, add "/api/uploadthing" to the publicRoutes array passed to authMiddleware
3. To prevent Clerk authentication from running at all, add "/api/uploadthing" to the ignoredRoutes array passed to authMiddleware
4. Pass a custom afterAuth to authMiddleware, and replace Clerk's default behavior of redirecting unless a route is included in publicRoutes

it can upload image to upload thing but does not save the name and bio.

and if I dont upload image. the data will save in the mongodb.

please help

@Sarthak412
Copy link

To prevent Clerk authentication from protecting (401) the api route, remove the rule matching "/api/uploadthing" from the apiRoutes array passed to authMiddleware 2. To make the route accessible to both signed in and signed out users, add "/api/uploadthing" to the publicRoutes array passed to authMiddleware 3. To prevent Clerk authentication from running at all, add "/api/uploadthing" to the ignoredRoutes array passed to authMiddleware 4. Pass a custom afterAuth to authMiddleware, and replace Clerk's default behavior of redirecting unless a route is included in publicRoutes

it can upload image to upload thing but does not save the name and bio.

and if I dont upload image. the data will save in the mongodb.

please help

export default authMiddleware({
// An array of public routes that don't require authentication
publicRoutes: ["/", "/api/webhook/clerk", "/api/uploadthing"],
});

Add this to you middleware.ts file. You need to include the '/api/uploadthing' to the public routes.

@vietgs03
Copy link

z5007952452942_fb98b60196548e99c98961b748a1164b
i try to updateUser and have a new problem with DB

@Sarthak412
Copy link

z5007952452942_fb98b60196548e99c98961b748a1164b i try to updateUser and have a new problem with DB

Please review the file responsible for updating or creating the user, and within that file, check if there is a connection being made to the MongoDB database. The "buffering timed out" error typically occurs when there is an issue connecting to the database. Investigating the connection logic in that specific file may provide insights into resolving the error.

@zaeniahmad-id
Copy link

image I can't create communities in my db my webhooks keeps on failing

I have same problems

@ChikenduHillary
Copy link

Good day guys, please this is what I got after deployment, please I need help
Screenshot_20240104-182654

@phunghoang1509
Copy link

image
image
image
image
Please! Can someone help me fix this error? I've checked all the logic and still can't figure out where the problem lies.
"I appreciate it very much."

@Sarthak412
Copy link

image image image image Please! Can someone help me fix this error? I've checked all the logic and still can't figure out where the problem lies. "I appreciate it very much."

Try this
if (!userInfo?.onboarded) redirect("/onboarding");

@phunghoang1509
Copy link

image image image image Please! Can someone help me fix this error? I've checked all the logic and still can't figure out where the problem lies. "I appreciate it very much."

Try this if (!userInfo?.onboarded) redirect("/onboarding");

It's not working, the website says "This page is not working now localhost has redirected you too many times." I think my userInfo is not being read even though it is in the MongoDB database. I don't know how to fix it

@ChikenduHillary
Copy link

Please guys does anyone knows what might be the cause of this error???
error

@migueej
Copy link

migueej commented Jan 8, 2024

terminal
loop

When user selects a new image in onboarding and fill out the rest of the form, after hitting Submit, it will go into an infinite loop saying "[UT] Call unsuccessful after 8 tries. Retrying in 64 seconds..." if user does not select image and fill out the rest of the form, it will go through normally... before the project was working fine with images but it's broken now. If anyone has a fix would be appreciated!

@TalhaAbbas55
Copy link

I just cloned the repo from github into my PC and then installed all the required things..as per video. Then I also changed the global and tailwindconfig.js as per the video after shadcn init. and also made env.local and all the API needed. so after doing all the steps from video. I have not yet replayed the website or hosted it on server. It is still in my PC. After running it , I got this error. Screenshot (242) and this in the vs code terminal: ▲ Next.js 14.0.3

⚠ Invalid next.config.js options detected: ⚠ Expected object, received boolean at "experimental.serverActions" ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config ⚠ Server Actions are available by default now, experimental.serverActions option can be safely removed. ✓ Ready in 4.6s ○ Compiling /middleware ... ✓ Compiled /middleware in 563ms (273 modules) ○ Compiling / ... ✓ Compiled / in 3.6s (1105 modules) (node:9496) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead. (Use node --trace-deprecation ... to show where the warning was created) ✓ Compiled in 1599ms (404 modules) MongoDB connected MongoServerError: bad auth : authentication failed at Connection.onMessage (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:202:26) at MessageStream. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:61:60) at MessageStream.emit (node:events:519:28) at processIncomingData (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:124:16) at MessageStream._write (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:33:9) at writeOrBuffer (node:internal/streams/writable:564:12) at _write (node:internal/streams/writable:493:10) at Writable.write (node:internal/streams/writable:502:10) at TLSSocket.ondata (node:internal/streams/readable:1007:22) at TLSSocket.emit (node:events:519:28) at addChunk (node:internal/streams/readable:559:12) at readableAddChunkPushByteMode (node:internal/streams/readable:510:3) at Readable.push (node:internal/streams/readable:390:5) at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) { ok: 0, code: 8000, codeName: 'AtlasError', connectionGeneration: 0, [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' } } Error fetching users: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) ⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) ⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) digest: "3882132667" ⨯ lib\actions\user.actions.ts (21:10) @ fetchUser ⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms at fetchUser (./lib/actions/user.actions.ts:36:15) at async Home (page.tsx:24:22) 19 | }); 20 | } catch (error: any) {

21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |
⨯ lib\actions\user.actions.ts (21:10) @ fetchUser
⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms
at fetchUser (./lib/actions/user.actions.ts:36:15)
at async Home (page.tsx:24:22)
digest: "2116173799"
19 | });
20 | } catch (error: any) {
21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |

Please do help me with this

just apply this configuration and it will work

"

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true,
serverComponentsExternalPackages: ["mongoose"],
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "img.clerk.com",
},
{
protocol: "https",
hostname: "images.clerk.dev",
},
{
protocol: "https",
hostname: "uploadthing.com",
},
{
protocol: "https",
hostname: "placehold.co",
},
],
},
typescript: {
ignoreBuildErrors: true,
},
};

module.exports = nextConfig;
"

@waltodd
Copy link

waltodd commented Jan 21, 2024

Good day guys, please this is what I got after deployment, please I need help Screenshot_20240104-182654

fix-error

@stmoerman
Copy link

Just a note for people having issues with the next config file.

If you need ECMAScript modules, you can use next.config.mjs and with Next.js 14 you no longer need to mark server actions as experimental:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverComponentsExternalPackages: ["mongoose"],
  },
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "img.clerk.com",
      },
      {
        protocol: "https",
        hostname: "images.clerk.dev",
      },
      {
        protocol: "https",
        hostname: "uploadthing.com",
      },
      {
        protocol: "https",
        hostname: "placehold.co",
      },
    ],
  },
};

module.exports = nextConfig;

@Victorosayame
Copy link

Screenshot (66)
i keep getting this error and it doesn't connect to db,please can some one help me out

@Sarthak412
Copy link

Screenshot (66) i keep getting this error and it doesn't connect to db,please can some one help me out

I got this error because I was not connecting to my mongodb check if you are connecting to mongoDB before performing the findOneAndUpdate() operation.

@igor-hara
Copy link

Did you find solution for this?
now i'm stuck with it :D

@Victorosayame
Copy link

Victorosayame commented Jan 26, 2024 via email

@kravitexx
Copy link

Hi i need help about this, I made a an organization in this but it doesnt show up on communitites tab as well as suggested community area. I m making the threads clone app using the video from javascriptmastery. I have installed all the necessary dependencies. if you are available please do help me with this
Screenshot 2024-01-31 011956

@kravitexx
Copy link

The next js version has something to do with the error?

i think that too...i wnted to make this project for my clg exam and here i am stuck now

@vipul7447
Copy link

Screenshot (48)
Can anyone please help me out...!!

@vipul7447
Copy link

Screenshot (49)
Hii everyone, can anyone resolve this issue ?

@Fy50167
Copy link

Fy50167 commented Mar 2, 2024

When I try to create a user, I receive this error:
Failed to simulate callback for file. Is your webhook configured correctly? 9aae6779-a988-418c-a87f-f0437ef3e149-hgmxm8.jpg

I've already tried adding 'api/uploadthing' to my public routes in my middleware. I also tried adding the routes to both of the exact files (api/uploading/route, api/uploadthing/core) just in case that might help but no luck. It seems like the error occurs randomly, I've been able to create three users so far but every other time I've received the error. Unfortunately no idea what the common thread between those three instances was.

@kkunal026
Copy link

My profile page is not working. When I make the profile folder -> id -> page.tsx and run it, it says "404-not found" and the profile page is not opening what should i do ?

311332378-207be27b-a94e-40dc-939d-8807f730d7c0
311332488-925de9a3-7d56-4937-9889-73b98666fe92
311416447-71da7633-a472-4c59-b490-8ef378ed1bba

@BestOlumese
Copy link

Screenshot (48) Can anyone please help me out...!!

bro check where you define the type of the props in your tsx it is very important

@TalhaAbbas55
Copy link

terminal loop

When user selects a new image in onboarding and fill out the rest of the form, after hitting Submit, it will go into an infinite loop saying "[UT] Call unsuccessful after 8 tries. Retrying in 64 seconds..." if user does not select image and fill out the rest of the form, it will go through normally... before the project was working fine with images but it's broken now. If anyone has a fix would be appreciated!

getting same error @adrianhajdin please help

@Atharvasurya
Copy link

Screenshot_4

@Atharvasurya
Copy link

Screenshot_5
Having this error in the terminal, while submitting the onboarding page and changes are not reflecting in 'test.users in mongodb'

@MaxT6
Copy link

MaxT6 commented Apr 4, 2024

Just a note for people having issues with the next config file.

If you need ECMAScript modules, you can use next.config.mjs and with Next.js 14 you no longer need to mark server actions as experimental:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverComponentsExternalPackages: ["mongoose"],
  },
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "img.clerk.com",
      },
      {
        protocol: "https",
        hostname: "images.clerk.dev",
      },
      {
        protocol: "https",
        hostname: "uploadthing.com",
      },
      {
        protocol: "https",
        hostname: "placehold.co",
      },
    ],
  },
};

module.exports = nextConfig;

Thank you to stmoerman! This solved my next.config.mjs issue, however I had to make one small change and switched module.exports = nextConfig; to export default nextConfig;

@orlando-guy
Copy link

orlando-guy commented Apr 7, 2024

Hi everyone, I hope you have a good day, I'm stuck on this, it's what I got after deployment on Vercel, please I need help.
Screen Shot 2024-04-07 at 12 56 40

@luidev0
Copy link

luidev0 commented Apr 25, 2024

I've encountered this problem. Have anyone fixed it?
image

@RobBloxham
Copy link

I've encountered this problem. Have anyone fixed it? image

Your issue is most likely in your uploadthing core.ts on line 12 it should read media: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })

@NaydenBanchevski
Copy link

I got the same issue today in the AccountProfile. Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.

@NaydenBanchevski
Copy link

I got the same issue today in the AccountProfile. Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.

Use file instead of fileUrl. Its deprecated.

I get the same error.

@RobBloxham
Copy link

I got the same issue today in the AccountProfile. Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.

Use file instead of fileUrl. Its deprecated.

I get the same error.

Your issue is most likely in your uploadthing core.ts on line 12 it should read media: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })

@NaydenBanchevski
Copy link

I got the same issue today in the AccountProfile. Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.

Use file instead of fileUrl. Its deprecated.

I get the same error.

Your issue is most likely in your uploadthing core.ts on line 12 it should read media: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })

I appreciate your response. Unfortunately I still get the same error : Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.ts(2339)

@Ayushhgupta39
Copy link

Screenshot (49) Hii everyone, can anyone resolve this issue ?

how was your issue solved?

@designsbyluis
Copy link

designsbyluis commented May 29, 2024

I got the same issue today in the AccountProfile. Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.

Use file instead of fileUrl. Its deprecated.

I get the same error.

Your issue is most likely in your uploadthing core.ts on line 12 it should read media: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })

I appreciate your response. Unfortunately I still get the same error : Property 'fileUrl' does not exist on type 'ClientUploadedFileData<{ uploadedBy: string; }>'.ts(2339)

Sorry meant "url", try (.url) instead and remove File. It should fix your issue.

@Ayushhgupta39
Copy link

Hey guys, I just restarted my dev server today and getting this error:
image

Everything was working fine last time I worked on this, but suddenly getting this. Can anyone please help?

@gitSuyog404
Copy link

gitSuyog404 commented Jun 18, 2024

I am facing an error and do not know how to solve this can anyone help me with this ???
Video: 23:17

In the tutorial authMiddleware is being used but as of now it has been deprecated so i copied this from clerk as shown in the tutorial.

Screenshot 2024-06-18 160540

@Swapnanilmanna1701
Copy link

i got the same issue, use auth middleware instead of clerkMiddleware. although it shows "authMiddleware' is deprecated".
But your job is done and eliminate the home route to get the desired result.
code:
import { authMiddleware } from "@clerk/nextjs/server";

export default authMiddleware({
publicRoutes: ["/api/webhook/clerk"],
ignoredRoutes: ["/api/webhook/clerk"],

});

export const config = {
matcher: ['/((?!.\..|_next).)', '/', '/(api|trpc)(.)'],
};

@FestusKoech
Copy link

i got the same issue, use auth middleware instead of clerkMiddleware. although it shows "authMiddleware' is deprecated". But your job is done and eliminate the home route to get the desired result. code: import { authMiddleware } from "@clerk/nextjs/server";

export default authMiddleware({ publicRoutes: ["/api/webhook/clerk"], ignoredRoutes: ["/api/webhook/clerk"],

});

export const config = { matcher: ['/((?!...|next).)', '/', '/(api|trpc)(._)'], };

doesn't work for me

@FestusKoech
Copy link

I just cloned the repo from github into my PC and then installed all the required things..as per video. Then I also changed the global and tailwindconfig.js as per the video after shadcn init. and also made env.local and all the API needed. so after doing all the steps from video. I have not yet replayed the website or hosted it on server. It is still in my PC. After running it , I got this error. Screenshot (242) and this in the vs code terminal: ▲ Next.js 14.0.3

⚠ Invalid next.config.js options detected: ⚠ Expected object, received boolean at "experimental.serverActions" ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config ⚠ Server Actions are available by default now, experimental.serverActions option can be safely removed. ✓ Ready in 4.6s ○ Compiling /middleware ... ✓ Compiled /middleware in 563ms (273 modules) ○ Compiling / ... ✓ Compiled / in 3.6s (1105 modules) (node:9496) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead. (Use node --trace-deprecation ... to show where the warning was created) ✓ Compiled in 1599ms (404 modules) MongoDB connected MongoServerError: bad auth : authentication failed at Connection.onMessage (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:202:26) at MessageStream. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:61:60) at MessageStream.emit (node:events:519:28) at processIncomingData (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:124:16) at MessageStream._write (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:33:9) at writeOrBuffer (node:internal/streams/writable:564:12) at _write (node:internal/streams/writable:493:10) at Writable.write (node:internal/streams/writable:502:10) at TLSSocket.ondata (node:internal/streams/readable:1007:22) at TLSSocket.emit (node:events:519:28) at addChunk (node:internal/streams/readable:559:12) at readableAddChunkPushByteMode (node:internal/streams/readable:510:3) at Readable.push (node:internal/streams/readable:390:5) at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) { ok: 0, code: 8000, codeName: 'AtlasError', connectionGeneration: 0, [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' } } Error fetching users: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) ⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) ⨯ Internal error: MongooseError: Operation users.countDocuments() buffering timed out after 10000ms at Timeout. (C:\Users\karti\Documents\MY_PROJECTS\test1\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) digest: "3882132667" ⨯ lib\actions\user.actions.ts (21:10) @ fetchUser ⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms at fetchUser (./lib/actions/user.actions.ts:36:15) at async Home (page.tsx:24:22) 19 | }); 20 | } catch (error: any) {

21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |
⨯ lib\actions\user.actions.ts (21:10) @ fetchUser
⨯ Error: Failed to fetch user: Operation users.findOne() buffering timed out after 10000ms
at fetchUser (./lib/actions/user.actions.ts:36:15)
at async Home (page.tsx:24:22)
digest: "2116173799"
19 | });
20 | } catch (error: any) {
21 | throw new Error(Failed to fetch user: ${error.message});
| ^
22 | }
23 | }
24 |

Please do help me with this

did you manage?

@FestusKoech
Copy link

Hi everyone, I hope you have a good day, I'm stuck on this, it's what I got after deployment on Vercel, please I need help. Screen Shot 2024-04-07 at 12 56 40

did you fix?

@WelldiusPrimeX
Copy link

i keep getting this error : MongoParseError: URI malformed, around the 2:22:01 mark when working on the backend and i also get another error : index.esm.mjs:2279 Uncaught (in promise) Error: Failed to create/update user: Operation users.findOneAndUpdate() buffering timed out after 10000ms, pls i noticed some people also encountered the same error, please did anyone find the solution?

@FestusKoech
Copy link

i keep getting this error : MongoParseError: URI malformed, around the 2:22:01 mark when working on the backend and i also get another error : index.esm.mjs:2279 Uncaught (in promise) Error: Failed to create/update user: Operation users.findOneAndUpdate() buffering timed out after 10000ms, pls i noticed some people also encountered the same error, please did anyone find the solution?

do not use characters in your password like $,@,#, etc. MongoDB will confuse it for termination. use auto generated password or just pure letters and numbers, no characters. It should work.

@WelldiusPrimeX
Copy link

WelldiusPrimeX commented Jun 29, 2024 via email

@WelldiusPrimeX
Copy link

WelldiusPrimeX commented Jul 4, 2024

anytime i click on responses to my messages on the activity page i get this error:

Unhandled Runtime Error
Error: Error fetching thread: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Thread"

Source
lib/actions/thread.actions.ts (109:11) @ fetchThreadById

107 | return thread;
108 | } catch (error: any) {

109 | throw new Error(Error fetching thread: ${error.message});
| ^
110 | }
111 | }
112 |
Call Stack

please did anybody experience this and any solution to this?

@FestusKoech
Copy link

FestusKoech commented Jul 5, 2024 via email

@WelldiusPrimeX
Copy link

concerning the password issue there was a time when that gave me problem around the 2 hr mark but i have resolved that since, this current issue is at the 4:49 mark once i click response in the activity page i end up with that error message i pasted, secondly what do u mean database named threads and how can i do that because im not sure i saw anything like that in the tutorial, how can i name the database threads????thank you as i anticipate your response

Make sure you have the database named 'Threads' as it is and do not use funny symbols and characters in your database password. If you use something like @, or # etc. Javascript will mistake it for the end of the password. Use auto-generated password, or simply letters and numbers, no characters. Hope this helps.

On Thu, Jul 4, 2024 at 10:17 PM WelldiusPrimeX @.> wrote: @.* commented on this gist. ------------------------------ anytime i click on responses to my messages on the activity page i get this error: Unhandled Runtime Error Error: Error fetching thread: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Thread" Source lib/actions/thread.actions.ts (109:11) @ fetchThreadById 107 | return thread; 108 | } catch (error: any) { 109 | throw new Error(Error fetching thread: ${error.message}); | ^ 110 | } 111 | } 112 | Call Stack — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-5111328 or unsubscribe https://github.com/notifications/unsubscribe-auth/AJMFIQULSTKYPEQ77BUPF4DZKWNTBBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub .

@FestusKoech
Copy link

FestusKoech commented Jul 6, 2024 via email

@WelldiusPrimeX
Copy link

no, for the database name just leave it, the problem should be solved by now after the password. Kindly share the screenshot On Sat, Jul 6, 2024 at 12:45 AM WelldiusPrimeX @.> wrote:

@.
* commented on this gist. ------------------------------ concerning the password issue there was a time when that gave me problem around the 2 hr mark but i have resolved that since, this current issue is at the 4:49 mark once i click response in the activity page i end up with that error message i pasted, secondly what do u mean database named threads and how can i do that because im not sure i saw anything like that in the tutorial, how can i name the database threads????thank you as i anticipate your response Make sure you have the database named 'Threads' as it is and do not use funny symbols and characters in your database password. If you use something like @, or # etc. Javascript will mistake it for the end of the password. Use auto-generated password, or simply letters and numbers, no characters. Hope this helps. … <#m_2640396956183329713_> On Thu, Jul 4, 2024 at 10:17 PM WelldiusPrimeX @.*> wrote: @.** commented on this gist. ------------------------------ anytime i click on responses to my messages on the activity page i get this error: Unhandled Runtime Error Error: Error fetching thread: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Thread" Source lib/actions/thread.actions.ts (109:11) @ fetchThreadById 107 | return thread; 108 | } catch (error: any) { 109 | throw new Error(Error fetching thread: ${error.message}); | ^ 110 | } 111 | } 112 | Call Stack — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-5111328 or unsubscribe https://github.com/notifications/unsubscribe-auth/AJMFIQULSTKYPEQ77BUPF4DZKWNTBBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub . — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-5112538 or unsubscribe https://github.com/notifications/unsubscribe-auth/AJMFIQWE4RSFWHKQVYQOV5DZK4HYPBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub .

please do u mean screenshot of the error or screenshot of the pages referenced in the error?

@WelldiusPrimeX
Copy link

20240706_093709
20240706_093752

20240706_093845

20240706_093917

These are the screenshot one shows the error message in the browser, one shows the error message in the terminal and one shows my fetchthreadbyid and the last one shows my page/id page line that was referenced in the error message in the terminal

@WelldiusPrimeX
Copy link

please let me know if you need any other thing to help me resolve the error

no, for the database name just leave it, the problem should be solved by now after the password. Kindly share the screenshot On Sat, Jul 6, 2024 at 12:45 AM WelldiusPrimeX @.> wrote:

@.
* commented on this gist. ------------------------------ concerning the password issue there was a time when that gave me problem around the 2 hr mark but i have resolved that since, this current issue is at the 4:49 mark once i click response in the activity page i end up with that error message i pasted, secondly what do u mean database named threads and how can i do that because im not sure i saw anything like that in the tutorial, how can i name the database threads????thank you as i anticipate your response Make sure you have the database named 'Threads' as it is and do not use funny symbols and characters in your database password. If you use something like @, or # etc. Javascript will mistake it for the end of the password. Use auto-generated password, or simply letters and numbers, no characters. Hope this helps. … <#m_2640396956183329713_> On Thu, Jul 4, 2024 at 10:17 PM WelldiusPrimeX @.*> wrote: @.** commented on this gist. ------------------------------ anytime i click on responses to my messages on the activity page i get this error: Unhandled Runtime Error Error: Error fetching thread: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Thread" Source lib/actions/thread.actions.ts (109:11) @ fetchThreadById 107 | return thread; 108 | } catch (error: any) { 109 | throw new Error(Error fetching thread: ${error.message}); | ^ 110 | } 111 | } 112 | Call Stack — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-5111328 or unsubscribe https://github.com/notifications/unsubscribe-auth/AJMFIQULSTKYPEQ77BUPF4DZKWNTBBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub . — Reply to this email directly, view it on GitHub https://gist.github.com/adrianhajdin/060e4c9d3d8d4274b7669e260dbbcc8e#gistcomment-5112538 or unsubscribe https://github.com/notifications/unsubscribe-auth/AJMFIQWE4RSFWHKQVYQOV5DZK4HYPBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDUOJ2WLJDOMFWWLO3UNBZGKYLEL5YGC4TUNFRWS4DBNZ2F6YLDORUXM2LUPGBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMZYGY4TINJRU52HE2LHM5SXFJTDOJSWC5DF . You are receiving this email because you commented on the thread. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub .

@FestusKoech
Copy link

I had those errors too. The password for Atlas and Mongo configuration file must be the same. Go to .env and make sure it matches the one on the Atlas browser configuration password.

@WelldiusPrimeX
Copy link

This stuff is really becoming fustrating, i just changed my password again and i have effected the change in my env file and still no difference unless if i dont understand what you are saying, i doubt this is what is causing the problem because if it was the site wont work at all but in my case evething is working until u vlick the thread in the activity page thats when the fetchthreadbyid errors throws up that error about cast to objectid failed for undefined i honestly dont even know what to do again

I had those errors too. The password for Atlas and Mongo configuration file must be the same. Go to .env and make sure it matches the one on the Atlas browser configuration password.

@WelldiusPrimeX
Copy link

Pls i want to confirm are you saying you also encountered the cast to objectid failed error at the activity page around the 4:49 hr mark or at another place because its getting really frustrating

I had those errors too. The password for Atlas and Mongo configuration file must be the same. Go to .env and make sure it matches the one on the Atlas browser configuration password.

@FestusKoech
Copy link

FestusKoech commented Jul 6, 2024 via email

@FestusKoech
Copy link

FestusKoech commented Jul 6, 2024 via email

@WelldiusPrimeX
Copy link

this is the link: https://github.com/WelldiusPrimeX/socialmediaapp.git

send your github link I will check the error

@kindaboringkvg
Copy link

kindaboringkvg commented Jul 16, 2024

Everytime I try to open create thread it takes me back to onboarding. please help

my onboarding page is showing error Property 'username' does not exist on type '{}'
and it is showing in every userData that i have created

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment