CORS issue with Express Server API to Next.js

16,839

First of all, CORS is configured on the server side. You configure your server to allow calls from specific origins.

In your code, onLoginClick is a client-side code, it runs on the browser, client cannot decide which origin the server should allowed to, that would defeat the purpose of having CORS.

Usually you don't need to change the cors configuration in a Next.js app, because you would be calling the API from the same origin that hosted the client side app.

By default, Next.js only support same-origin for API Routes, if you need to customize it, you can use micro-cors.

Share:
16,839

Related videos on Youtube

Peter Ayello Wright
Author by

Peter Ayello Wright

Updated on June 04, 2022

Comments

  • Peter Ayello Wright
    Peter Ayello Wright almost 2 years

    I have a user authentication server setup using Express and Node.js in my localhost Port 3333 and I am trying to connect to the endpoint in Next.js port 3000 using isomorphic-unfetch for the fetch. I am getting a CORS 401 error, I have done a fair bit of research already but just wanted to know whether it was possible connecting to a Express server on localhosts? I have tried adding "Access-Control-Allow-Origin": "*", "Content-Type": "multipart/form-data" to a header object. The express server has cors setup already.

    This function below is called on click of a button.

    onLoginClick = async () => {
      let header = new Headers({
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "multipart/form-data"
      });
      const res = await fetch("http://localhost:3333", {
        method: "POST",
        header,
        body: JSON.stringify({
          username: "USER",
          password: "PASSWORD"
        })
      });
    }
    

    Error message -

    http://localhost:3333/ 401 (Unauthorized)
    Response {type: "cors", url: "http://localhost:3333/", redirected: false, status: 401, ok: false, …}
    
    • Andy
      Andy over 4 years
      share your codes and error message please
    • james emanon
      james emanon almost 3 years
      Did you ever find a solution to this?