CORS issue with Express Server API to Next.js

Peter Ayello Wright picture Peter Ayello Wright · Jan 19, 2020 · Viewed 15.8k times · Source

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, …}

Answer

Andy picture Andy · Jan 19, 2020

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.