Why mode: "no-cors" won't fix your CORS errors

·

2 min read

When dealing with CORS, you've probably seen this error message before. It says to set the request's mode to no-cors, but it doesn't really work as expected. Let's see what actually happens.

CORS Error

CORS Error

Vague error message

It says, "If an opaque response serves your need, set the request mode to no-cors to disable CORS." Naturally, people might read this and think, "Oh, okay, I'm going to use mode no-cors to disable CORS." However, when you do that, the response becomes unreadable. The status code, headers, and body are all empty. In simple terms, what you are getting is an opaque response.

Opaque Response Example Opaque Response Example

Opaque response

An opaque response means you cannot inspect the response details. When the error message mentions that "if an opaque response serves your need," it really means that if you only care about sending the request and do not need to process or examine the response, then using mode no-cors is acceptable.

An opaque filtered response is a filtered response whose type is "opaque", URL list is « », status is 0, status message is the empty byte sequence, header list is « », body is null, and body info is a new response body info. (WHATWG)

Actually fixing the issue

We covered the solution in our common CORS mistakes article, but here is a brief overview. In order to handle CORS properly, you have two options:

  1. If you own the resource
    Add the appropriate CORS header on the server. This means configuring your server to include headers like Access-Control-Allow-Origin to explicitly allow requests from your origin.

    Access-Control-Allow-Origin: your-origin.com
    
  2. If you do not own the resource
    Use a CORS proxy. A proxy acts as an intermediary that makes the request on your behalf and then returns the response to your code, bypassing the browser's CORS restrictions.

    fetch("https://proxy.corsfix.com/?https://example.com/api")
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((err) => console.error(err));
    

    CORS Proxy usage example

Using these options ensures that you receive the response that you can read and handle appropriately. These solutions work because they address the root cause of CORS errors.

Conclusion

The no-cors error message can be misleading. It definitely can be worded more clearly: using mode no-cors lets you send the request, but you will not be able to read the response. Now you know how to actually fix the CORS error by either configuring your server or using a CORS proxy.

If you are looking for a CORS proxy, check out Corsfix. It is free to get started, and you only need to upgrade when you go to production.