Skip to content

Commit

Permalink
Fixed errors while build Next.js
Browse files Browse the repository at this point in the history
  • Loading branch information
berkanumutlu committed Nov 8, 2024
1 parent 5d669d5 commit e84097e
Show file tree
Hide file tree
Showing 24 changed files with 127 additions and 96 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
NODE_ENV="development"
NEXT_PUBLIC_SITE_URL="http://localhost:3000"

# AUTH with CLERK
Expand Down
1 change: 1 addition & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
NODE_ENV="development"
NEXT_PUBLIC_SITE_URL="http://localhost:3000"

# AUTH with CLERK
Expand Down
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
src/components/ui/**
7 changes: 7 additions & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { PrismaClient } from "@prisma/client";

declare global {
var prisma: PrismaClient | undefined;
}

export { };
2 changes: 2 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
webpack: (config) => {
config.externals.push({
"utf-8-validate": "commonjs utf-8-validate",
Expand Down
16 changes: 16 additions & 0 deletions next.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Server as NetServer } from "http";
import { Socket as NetSocket } from "net";
import { Server as ServerIOServer } from "socket.io";
import { NextApiResponse as OriginalNextApiResponse } from "next";

declare module "next" {
type NextApiResponseWithSocket<T = any> = OriginalNextApiResponse<T> & {
socket: NetSocket & {
server: NetServer & {
io?: ServerIOServer;
};
};
};

export type NextApiResponse<T = any> = NextApiResponseWithSocket<T>
}
26 changes: 0 additions & 26 deletions src/app/(setup)/page.tsx

This file was deleted.

2 changes: 2 additions & 0 deletions src/app/api/direct-messages/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ async function fetchDirectMessages(conversationId: string, cursor?: string) {
return await db.directMessage.findMany(queryOptions);
}

export const dynamic = 'force-dynamic';

export async function GET(req: Request) {
try {
const profile = await currentProfile();
Expand Down
2 changes: 2 additions & 0 deletions src/app/api/messages/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { currentProfile } from "@/lib/current-profile";

const MESSAGES_LIMIT = 15;

export const dynamic = 'force-dynamic';

async function fetchMessages(channelId: string, cursor?: string) {
const queryOptions: Prisma.MessageFindManyArgs = {
take: MESSAGES_LIMIT,
Expand Down
28 changes: 28 additions & 0 deletions src/app/api/servers/server-url/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { currentProfile } from "@/lib/current-profile";

export const dynamic = 'force-dynamic';

export async function GET() {
try {
const profile = await currentProfile();
if (!profile) {
return NextResponse.json({ serverUrl: "" });
}
const server = await db.server.findFirst({
where: {
members: {
some: {
profileId: profile.id
}
}
}
});
const serverUrl = server ? `/servers/${server.id}` : "";
return NextResponse.json({ serverUrl });
} catch (error) {
console.error("[SERVER_URL_GET]", error);
return NextResponse.json({ serverUrl: "" });
}
}
29 changes: 19 additions & 10 deletions src/app/client-page.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
"use client";

import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import Image from "next/image";
import { useRouter } from 'next/navigation';
import { useAuth } from '@clerk/nextjs';
import { useTheme } from 'next-themes';
import { useModal } from '@/hooks/use-modal-store';

interface HomeClientProps {
serverUrl: string | null;
}

export default function Home({ serverUrl }: HomeClientProps) {
export default function HomeClient() {
const router = useRouter();
const { theme } = useTheme();
const { isSignedIn } = useAuth();
const { isSignedIn, isLoaded } = useAuth();
const { onOpen } = useModal();
const signInUrl = process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL ?? '/sign-in';
const [serverUrl, setServerUrl] = useState("");

useEffect(() => {
if (!isSignedIn) {
if (isLoaded && !isSignedIn) {
router.push(signInUrl);
} else if (isSignedIn) {
fetchServerUrl();
}
}, [isLoaded, isSignedIn, router, signInUrl]);

const fetchServerUrl = async () => {
try {
const response = await fetch('/api/servers/server-url');
const data = await response.json();
setServerUrl(data.serverUrl);
} catch (error) {
console.error('Error fetching server URL:', error);
}
}, [isSignedIn, router, signInUrl]);
};

if (!isSignedIn) {
if (!isLoaded || !isSignedIn) {
return null;
}

Expand Down
21 changes: 11 additions & 10 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import ClientLayout from "./client-layout";
import { ClerkProvider } from "@clerk/nextjs";
import { cn } from "@/lib/utils";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { ModalProvider } from "@/components/providers/modal-provider";
import { SocketProvider } from "@/components/providers/socket-provider";
import { QueryProvider } from "@/components/providers/query-provider";
import dynamic from 'next/dynamic';

const font = Open_Sans({ subsets: ['latin'] });

const DynamicModalProvider = dynamic(() => import('@/components/providers/modal-provider').then(mod => mod.ModalProvider), { ssr: false });
const DynamicSocketProvider = dynamic(() => import('@/components/providers/socket-provider').then(mod => mod.SocketProvider), { ssr: false });
const DynamicQueryProvider = dynamic(() => import('@/components/providers/query-provider').then(mod => mod.QueryProvider), { ssr: false });

export const metadata: Metadata = {
title: "Discord Clone By Berkan Ümütlü",
description: "Built with Next.js 14, React, Socket.io, Prisma, Tailwind, PostgreSQL"
Expand All @@ -31,23 +33,22 @@ export default function RootLayout({
<ThemeProvider
attribute="class"
defaultTheme="system"
/* forcedTheme="dark" */
enableSystem={false}
storageKey="discord-theme"
>
<main className="main">
<SocketProvider>
<DynamicSocketProvider>
<ClientLayout>
<ModalProvider />
<QueryProvider>
<DynamicModalProvider />
<DynamicQueryProvider>
{children}
</QueryProvider>
</DynamicQueryProvider>
</ClientLayout>
</SocketProvider>
</DynamicSocketProvider>
</main>
</ThemeProvider>
</body>
</html>
</ClerkProvider>
);
}
}
27 changes: 7 additions & 20 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
import { db } from '@/lib/db';
import { currentProfile } from '@/lib/current-profile';
import HomeClient from './client-page';
import dynamic from 'next/dynamic';

export default async function Home() {
const profile = await currentProfile();
if (!profile) return null;
const server = await db.server.findFirst({
where: {
members: {
some: {
profileId: profile.id
}
}
}
});
let serverUrl = "";
if (server) {
serverUrl = `/servers/${server.id}`;
}
const DynamicHomeClient = dynamic(() => import('./client-page'), {
ssr: false,
loading: () => <div>Loading...</div>
});

return <HomeClient serverUrl={serverUrl} />;
export default function Home() {
return <DynamicHomeClient />;
}
2 changes: 1 addition & 1 deletion src/components/chat/chat-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { useModal } from "@/hooks/use-modal-store";

interface ChatInputProps {
apiUrl: string;
query: Record<string, any>;
query: Record<string, string | number>;
name: string;
type: "conversation" | "channel";
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/chat/chat-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export const ChatItem = ({
{!fileUrl && !isEditing && (
<p className={cn(
"text-sm text-zinc-600 dark:text-zinc-300",
isDeleted && "mt-1 italic text-xs text-zinc-500 dark:text-zinc-400"
isDeleted && "mt-2 italic text-xs text-zinc-500 dark:text-zinc-400"
)}>
{isDeleted
? `This message has been deleted${canActionMessage ? ` at: ${deletedAt}` : '.'}`
Expand Down
4 changes: 2 additions & 2 deletions src/components/emoji-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { useTheme } from "next-themes";
import { SmilePlus } from "lucide-react";
import Picker from "@emoji-mart/react";
import data from "@emoji-mart/data";
import data, { Skin } from "@emoji-mart/data";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";

interface EmojiPickerProps {
Expand All @@ -21,7 +21,7 @@ export const EmojiPicker = ({
<SmilePlus className="text-zinc-500 hover:text-zinc-600 dark:text-zinc-400 dark:hover:text-zinc-300 transition" />
</PopoverTrigger>
<PopoverContent side="right" sideOffset={40} className="mb-16 bg-transparent border-none shadow-none drop-shadow-none">
<Picker data={data} theme={resolvedTheme} onEmojiSelect={(emoji: any) => onChange(emoji.native)} />
<Picker data={data} theme={resolvedTheme} onEmojiSelect={(emoji: Skin) => onChange(emoji.native)} />
</PopoverContent>
</Popover>
)
Expand Down
15 changes: 8 additions & 7 deletions src/components/providers/socket-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { io as ClientIO } from "socket.io-client";
import { io as ClientIO, Socket } from "socket.io-client";

type SocketContextType = {
socket: any | null;
socket: Socket | null;
isConnected: boolean;
};

Expand All @@ -22,14 +22,15 @@ export const SocketProvider = ({
}: {
children: React.ReactNode
}) => {
const [socket, setSocket] = useState(null);
const [socket, setSocket] = useState<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);

useEffect(() => {
const socketInstance = new (ClientIO as any)(process.env.NEXT_PUBLIC_SITE_URL!, {
const socketInstance = ClientIO(process.env.NEXT_PUBLIC_SITE_URL!, {
path: "/api/socket/io",
addTrailingSlash: false
});

socketInstance.on("connect", () => {
setIsConnected(true);
});
Expand All @@ -40,12 +41,12 @@ export const SocketProvider = ({

return () => {
socketInstance.disconnect();
}
};
}, []);

return (
<SocketContext.Provider value={{ socket, isConnected }}>
{children}
</SocketContext.Provider>
)
}
);
};
2 changes: 1 addition & 1 deletion src/components/server/server-member.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const ServerMember = ({
const icon = roleIconMap[member.role];

const onClick = () => {
router.push(`/servers/${params?.serverId}/conversations/${member.id}`);
router.push(`/servers/${server.id}/conversations/${member.id}`);
};

return (
Expand Down
2 changes: 1 addition & 1 deletion src/components/ui/command.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
Expand Down
2 changes: 1 addition & 1 deletion src/components/ui/input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
Expand Down
Loading

0 comments on commit e84097e

Please sign in to comment.