Next.js Discord

Discord Forum

Easiest/Best Way to Resolve CORS Error on client side post?

Answered
Baldfaced hornet posted this in #help-forum
Open in Discord
Baldfaced hornetOP
I have ran into this CORS issue when trying to have a user register for my app. Below is the setup up but it is a client side form that uses a post request I have in my lib path to then post the registration to my backend(Java api).

1. The post function that communicates to the Java backend located in src/lib/postUserSignUp.tsx
export default async function postUserLogin(firstName, lastName, email, password, username, termsAndPrivacyAgreed) {
    const res = await fetch( `${process.env.NEXT_PUBLIC_HADES_URL}/user/register`, {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ firstName: firstName, lastName: lastName, email: email, password: password, username: username, termsAndPrivacyAgreed: termsAndPrivacyAgreed })
    })

    if (!res.ok) throw new Error('Error signing up')

    return res.json()
}


2. The page that calls the above function to submit the user registration(cut off not important parts to this error)
 'use client'
import postUserSignUp from "@/lib/postUserSignUp";
...imports
...func
const handleFormSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            //submit sign up
            const response = postUserSignUp(form.firstName, form.lastName, form.email, form.password, form.username, form.termsAndPrivacyAgreed)

            console.log(response)
            // TODO: then router.push('/login') ----push them to login page
            router.push("/auth/sign-in")

        } catch (error) {

        }
    };
Answered by joulev
1. if your backend endpoint can be made known to everyone, then simply configuring cors in the backend is the easiest and best solution, since it doesn't require you to have a server for the nextjs app

2. server actions can be used when you are not fine with exposing backend endpoint or api key on the client. basically in this case you are making a proxy of your backend. this requires a nextjs running server so cannot be deployed with static exports

3. if you do choose to use server actions, upgrade to nextjs 14. [upgrading is very easy](https://nextjs.org/docs/app/building-your-application/upgrading/codemods#140)
View full answer

7 Replies

Baldfaced hornetOP
Wondering how best to go about this.. have seen multiple approaches and am curious as to what the "standard" or best-practice is
Things I've seen so far:
1. Write 2 different post functions... one that just post to the nextjs backend then have one in there that post to the java backend(seems hacky and incorrect)
2. Add a cors library and define the backend endpoint that is okay to communicate to
3. Use server actions(not familiar as I am only on nextjs13 right now and would require to update or turn on this experimental feature first although it is what I am currently looking into more)
Baldfaced hornetOP
Okay so I added the experimental feature to my next.config.js and added 'use server' at the top of postUserSignUp.tsx and it worked... Definitely seems like the best approach? Is there any downside to doing it this way?

Follow up question: Can server actions be used as "experimental" safely in v13.4 or should I upgrade to 14 to avoid issues? Also anyone have experience going from v13.4 to v14? Was it pretty easy? Anything specific I should know?
1. if your backend endpoint can be made known to everyone, then simply configuring cors in the backend is the easiest and best solution, since it doesn't require you to have a server for the nextjs app

2. server actions can be used when you are not fine with exposing backend endpoint or api key on the client. basically in this case you are making a proxy of your backend. this requires a nextjs running server so cannot be deployed with static exports

3. if you do choose to use server actions, upgrade to nextjs 14. [upgrading is very easy](https://nextjs.org/docs/app/building-your-application/upgrading/codemods#140)
Answer
@Baldfaced hornet So I opted for upgrading to v14 Small issue when I am trying to run the "codemods" I keep running into this error
Hmm can try making the changes manually. Do you use TypeScript? If you do, you can just run the app and TypeScript will error in places where you need to update the metadata/viewport export
I myself have never used the code mods lol, I always make those changes manually