Next.js Discord

Discord Forum

Preflight error when calling get from client side

Answered
Horned oak gall posted this in #help-forum
Open in Discord
Horned oak gallOP
I have a preflight error on a getMessages call inside a useEffect()
Pretty stumped at this point on it after trying for ~4 hours now to get it working.
"use client"

type Props = {
    senderIdentityId: number,
    receiverIdentityId: number | null,
    displayConversationName: string | null
}

export default function DisplayConversation({ senderIdentityId, receiverIdentityId, displayConversationName}: Props) {

    const {data: session, status} = useSession();
    const textareaRef = useRef<HTMLTextAreaElement | null>(null);
    const [messageInput, setMessageInput] = useState<string>('');
    const [callUseEffect, setCallUseEffect] = useState<boolean>(false);

    useEffect(() => {
        if (senderIdentityId && receiverIdentityId) {
            getMessages(senderIdentityId, receiverIdentityId)
        }
        return () => setCallUseEffect(false);
    }, [callUseEffect])

    const getMessages = async (identity1: number, identity2: number | null) => {
        try {
            let messagesData = await getConversationForIdentities(identity1, identity2, session?.user.backendToken)
            setMessages(messagesData)
        } catch (error) {
            console.log("Get conversation for identities error: " + error)
        }
    }

    const sendUserMessage = async () => {
        setIsLoadingMessageSend(true)
        try {
            await postUserMessage(session?.user.identityId, receiverIdentityId, messageInput, session?.user.backendToken);

            setMessageInput('')
            textareaRef.current?.focus();
            // getMessages(session?.user.identityId!, receiverIdentityId);
            setCallUseEffect(true);
        } catch (error) {
            console.log("Send user message error: " + error)
        } finally {
            setIsLoadingMessageSend(false)
        }
    }
}
Answered by Horned oak gall
For future people that run across this.

Long story short I had a fundamental misunderstanding as to what exactly an "api route" was in nextjs and thought that my constant exports in a lib folder were only ever reaching out on server side.

This resulted in my exports of this to run correctly when used in my local env and when they are called via server side. However when trying to run them on a VM the server side callouts would work fine but the client side was acting up since it was looking for a localhost on the clients machine that did not exist. I have added a "use server" to the top of my lib export as a TEMPORARY solution. In reality I need to go through and refactor my callouts from my lib folder into proper api route callouts as tech debt.
View full answer

8 Replies

Horned oak gallOP
export default async function getConversationForIdentities(identityId1, identityId2, token) {
    const res = await fetch( `${process.env.NEXT_PUBLIC_HADES_URL}/message/identity/${identityId1}/conversation/${identityId2}`, {
        method: "GET",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + token,
        }
    })

    if (!res.ok) throw new Error('Failed to fetch conversation')

    return res.json()
}

Removed code not related to the useEffect to reduce size.
Additional information: the getConversationForIdentities func calls out to a java backend that I have cors enabled on and even set it to all urls temporary to make sure that wasn't the cause.

The app does have other calls to the backend working fine (this is the only call using a useEffect on client side however) and the domain is proxied on cloudflare(cloudflare claims they do not interfere with any cors headers and passes them accordingly and I checked firewall settings to make sure nothing there was blocking it)
The senderId and receiverId's do not change once the page is rendered and is why they aren't included in the useEffect dependency array but there's situations where they aren't there on page load which is why there's a check for them as well.
Also another important part of this is locally it works fine. Even running the app in prod locally it doesn't have an issue. Only once I try to use this specific call on the VM hosted "stage" do I encounter issues with the preflight failure
Horned oak gallOP
Disabled cloudflare proxy, combed through to make sure there was no settings messing headers and still same issue for this 1 specific call.
Horned oak gallOP
Opened the java app to allow CORS on all origins just to make sure it wasn't a URL mismatch and still same issue.
Horned oak gallOP
Sooo long story short after many hours of debugging now the useEffect() hook is calling all of the api route code inside itself on the client end instead of firing the api route code on the VM'd nextjs server.

Is there a way to make a useEffect() call out to the nextjs server to then run the api route?
Horned oak gallOP
For future people that run across this.

Long story short I had a fundamental misunderstanding as to what exactly an "api route" was in nextjs and thought that my constant exports in a lib folder were only ever reaching out on server side.

This resulted in my exports of this to run correctly when used in my local env and when they are called via server side. However when trying to run them on a VM the server side callouts would work fine but the client side was acting up since it was looking for a localhost on the clients machine that did not exist. I have added a "use server" to the top of my lib export as a TEMPORARY solution. In reality I need to go through and refactor my callouts from my lib folder into proper api route callouts as tech debt.
Answer