serjou
serjou

Reputation: 25

I am getting CORS error when cookies are not set

I always have so much pain with CORS and here is my situation.
I am sending get request from my frontend:

const axiosInstance = Axios.create({
  baseURL: process.env['NEXT_PUBLIC_API_URL'],
  withCredentials: true,
});

const { data } = await axiosInstance.get<string>(ApiRoutes.NONCE);

On my backend CORS is configured in this way:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Request handler is following:

session_id = generate_session_id()

COOKIES[session_id] = {
    'nonce': generate_nonce()
}

response.set_cookie(
    key=COOKIE_SESSION_ID_KEY,
    value=session_id,
    samesite='none',
    secure=True)

return COOKIES[session_id]['nonce']

The problem is when I get /nonce for the first time, when Cookie is not set, I get CORS error CORS error But when I get it for second time, everything works fine, because Cookies are already set. Everything is fine Why do I get CORS error when cookies are not set and how to fix this?

Upvotes: 0

Views: 31

Answers (1)

serjou
serjou

Reputation: 25

I fixed this by changing allow_origins from * to my domain. Seems like this is blocked on Chrome's side

I've found a solution here: How to debug CORS errors

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

Upvotes: 0

Related Questions