fetch function mode sors, no-cors, same-origin

nodejsnextjs

The mode option in the fetch function specifies the mode of the request, which determines whether or not the request can be made across origin (different domain, protocol, or port). Here’s what each mode means:

  • ‘cors’: Cross-Origin Resource Sharing. Allows the browser to send requests to any origin, as long as the server returns the appropriate CORS headers. This is the most common mode.

  • ‘no-cors’: No CORS. Allows the browser to send requests to any origin, but the response will always be opaque, meaning that you cannot access the response’s properties (e.g. response.text() will always throw an error). This mode is typically used for making requests to endpoints that do not return CORS headers, such as APIs that only support JSONP.

  • ‘same-origin’: Same-Origin. Only allows the browser to send requests to the same origin (same domain, protocol, and port).

Here’s an example of using the mode option:

const res = await fetch('/api/example', {
  mode: 'cors',
})

This example sends a request to the /api/example endpoint with the mode set to cors, allowing the browser to send the request to any origin as long as the server returns the appropriate CORS headers.