1

I was developing my project on Next.js 14 which had frontend and backend seperated. I encountered an error named Error: Unsupported Server Component type: Module. The error appears in the page.tsx file.As I understand it, this error is associated with the use of server components, although everywhere there is a directive 'use client'.Here is the code for the page.tsx file and the code for the files that are related to it.(Chat.tsx, MessageField.tsx)


page.tsx

import type { Metadata } from 'next'
import { Chat } from '@/components/screens/chats/chat/Chat'
import { NO_INDEX_PAGE } from '@/constants/seo.constants'

export const metadata: Metadata = {
    ...NO_INDEX_PAGE,
}

export default function ChatPage({ params }: { params: { id: string } }) {
    return <Chat id={params.id} />
}

Chat.tsx

'use client'
import { $fetch } from "@/$api/api.fetch";
import { MessageField } from "./MessageField";
import { useQuery } from "@tanstack/react-query";
import { IChat } from "@/types/chat.types";
import { Message } from "./Message";
import { ChatHeader } from "./ChatHeader";
import { useAuth } from "@/hooks/useAuth";
import { Loader } from "@/components/ui/loader/Loader";
import { useEffect, useRef } from "react";

export function Chat({ id }: { id: string }){
    const {user} = useAuth()
    const {data, isLoading} = useQuery({
        queryKey: ['chat', id],
        queryFn: () =>
            $fetch.get<{ data: IChat }>(
                `/chats/${id}
                ?populate[messages][populate][sender][populate][avatar]=*
                &populate[participants][populate][avatar]=*`,
                true
            ),
        select: data => data.data,
        enabled: !!id,
    })

    const correspondent = data?.participants.find(u => u.email !== user?.email)
    const endOfMessagesRef = useRef<HTMLDivElement>(null);

    const scrollToBottom = () => {
        endOfMessagesRef.current?.scrollIntoView({ behavior: "smooth" });
    };
    useEffect(scrollToBottom, [data]);
    
    return (
    <div className="w-8/12 border-r border-border h-full grid"
    style={{
        gridTemplateRows: isLoading ? '1fr .089fr' : '.6fr 6fr .6fr',
    }}
    >
        {isLoading ? (
                <div className='flex items-center justify-center'>
                    <Loader />
                </div>
            ) : (
                <>
                    <ChatHeader correspondent={correspondent} />
                    <div className='p-layout border-t border-border' style={{ overflowY: 'auto', maxHeight: '570px' }}>
                        {data?.messages.map(message => (
                            <Message key={message.id} message={message} />
                        ))}
                        <div ref={endOfMessagesRef} />
                    </div>
                </>
            )}
            <MessageField />
        </div>
    )
}

MessageField.tsx

'use client'
import { $fetch } from "@/$api/api.fetch"
import Field from "@/components/ui/field/Field"
import { useAuth } from "@/hooks/useAuth"
import { useReactQuerySubscription } from "@/hooks/useReactQuerySubscription"
import { useMutation } from "@tanstack/react-query"
import { ArrowRightToLine, Send } from "lucide-react"
import { useParams } from "next/navigation"
import { useState } from "react"

export function MessageField() {

    const [message, setMessage] = useState('')
    const send = useReactQuerySubscription()
    const {id} = useParams()
    const { user } = useAuth()
    const { mutate } = useMutation({
        mutationKey: ['update chat', id],
        mutationFn: () =>
            $fetch.post(
                '/messages',
                {
                    data: {
                        text: message,
                        sender: Number(user?.id),
                        chat: id,
                    },
                },
                true
            ),
        onSuccess() {
            setMessage('')
            send({
                operation: 'update',
                entity: 'chat',
                id: id.toString(),
            })
        },
    })
    const onSubmit = () => {
        if(!message) return
        mutate()
    }

    return (
    <div className="border-t border-border p-layout flex items-center justify-between">
        <Field 
        placeholder="Напсать сообщение..." 
        Icon={ArrowRightToLine}
        value={message}
        onChange={e => setMessage(e.target.value)}
        onKeyDown={e => {
            if (e.key === 'Enter') onSubmit()
        }}
        className="w-4/5"
        />
        <button 
            onClick={onSubmit} 
            disabled={!message}
            className="hover:text-[#4E7869] cursor-pointer transition-colors">
            <Send />
        </button>
    </div>
    )
}

I've tried everything possible to fix this problem. All similar errors on stackoverflow.com. I even downgraded the Next version, thinking that there might be something wrong with my version. I am doing this project following the example and in that example no such error appeared)).I really hope that I just imported something wrong or added something unnecessary. So far this error is unsolvable for me((.

2
  • problem was with imports)) Commented Apr 21, 2024 at 14:11
  • So you figured it out? If so, it's best practice to post your solution as an answer to your own question (and accept it) so that future readers can benefit from your findings. If you don't want to do that, I'd suggest closing this question. Commented Sep 20 at 12:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.