šŸ¶
React.js

Fetch API: Using "no-cors" Mode

By Filip on 05/01/2024

Learn how using `fetch` with `mode: 'no-cors'` can restrict your access to response data and explore alternative methods for cross-origin communication.

Fetch API: Using "no-cors" Mode

Table of Contents

Introduction

This article explains Cross-Origin Resource Sharing (CORS) and the 'no-cors' mode, a way to make requests to resources without CORS enabled. CORS is a security mechanism that restricts how websites access resources from other domains. The 'no-cors' mode allows bypassing CORS restrictions but limits you to simple HTTP methods, restricts access to response headers and the body, and prevents direct reading of the response body in JavaScript. To use 'no-cors' mode, identify the API endpoint, construct a fetch request with the mode set to 'no-cors', and handle the opaque response, accessing limited headers and checking the status. Remember, 'no-cors' mode is not ideal for situations requiring direct response body access and has security implications as it bypasses CORS. Consider alternatives like JSONP or server-side proxies if needed. If the API supports CORS, using the default 'cors' mode is recommended for better data access and security. An example demonstrates fetching data from the GitHub API using 'no-cors' mode, showing how to check the status and 'Content-Type' header despite limitations in accessing the response body.

Step-by-Step Guide

Before diving into the steps, let's clarify what CORS and the 'no-cors' mode are:

  • CORS (Cross-Origin Resource Sharing): A security mechanism that restricts how websites access resources from other domains. It prevents malicious scripts from one website from accessing data on another website without permission.
  • 'no-cors' mode: A fetch option that allows making requests to resources without CORS enabled. However, it comes with limitations:
    • You can only use simple HTTP methods like GET, HEAD, and POST.
    • You have limited access to response headers and the body.
    • You cannot read the response body directly in JavaScript.

Steps to use 'no-cors' mode with Fetch API:

  1. Identify the API endpoint: Determine the URL of the API you want to access.
  2. Construct the fetch request:
    fetch('https://api.example.com/data', {
        method: 'GET', // or 'HEAD', 'POST'
        mode: 'no-cors' // This is crucial for bypassing CORS
    })
  3. Handle the response:
    • Opaque responses: In 'no-cors' mode, responses are considered "opaque," meaning you cannot directly access the body content. You can still check the response status and headers.
    .then(response => {
        if (response.ok) {
            console.log("Request successful!");
            // Access response headers (e.g., response.headers.get('Content-Type'))
        } else {
            console.error("Request failed:", response.status);
        }
    })
    • Limited header access: You can only access a few response headers like 'Cache-Control', 'Content-Language', 'Content-Type', 'Expires', 'Last-Modified', and 'Pragma'.
  4. Error handling:
    .catch(error => {
        console.error("Fetch error:", error);
    });

Important considerations:

  • Limited data access: 'no-cors' mode is not suitable for situations where you need to read the response body directly in JavaScript. Consider alternative solutions like JSONP or server-side proxies for such cases.
  • Security implications: Be cautious when using 'no-cors' mode, as it bypasses CORS security measures. Ensure you trust the API and understand the potential risks.
  • Alternatives: If the API supports CORS, it's generally recommended to use the default 'cors' mode for better data access and security.

Example: Fetching data with 'no-cors' mode

fetch('https://api.github.com/users/geminibot', {
    method: 'GET',
    mode: 'no-cors'
})
.then(response => {
    if (response.ok) {
        console.log("Request successful!");
        console.log("Content-Type:", response.headers.get('Content-Type'));
    } else {
        console.error("Request failed:", response.status);
    }
})
.catch(error => {
    console.error("Fetch error:", error);
});

This example attempts to fetch data from the GitHub API using 'no-cors' mode. While you won't be able to access the response body directly, you can still check the status and the 'Content-Type' header.

Code Example

This JavaScript code demonstrates a 'no-cors' fetch request to an API endpoint. It sends a GET request and handles the response, checking for success and accessing limited headers. Error handling is included. Remember, 'no-cors' mode restricts access to the response body and certain headers, and should be used with caution due to potential security risks.

const apiUrl = 'https://api.example.com/data'; // Replace with your API endpoint

fetch(apiUrl, {
  method: 'GET',
  mode: 'no-cors'
})
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  console.log("Request successful!");
  // Access limited headers
  console.log("Content-Type:", response.headers.get('Content-Type'));
})
.catch(error => {
  console.error("Fetch error:", error);
});

Explanation:

  1. API Endpoint: Replace apiUrl with the actual URL of the API you want to access.
  2. Fetch Request: We use the fetch API with the URL and options.
    • method: 'GET' specifies the HTTP method. Remember, 'no-cors' only allows simple methods like GET, HEAD, and POST.
    • mode: 'no-cors' is crucial for bypassing CORS restrictions.
  3. Response Handling:
    • We check response.ok to see if the request was successful (status code in the 200-299 range).
    • If successful, we log a success message and access the Content-Type header as an example.
    • If not successful, we throw an error with the status code.
  4. Error Handling: We catch any errors that occur during the fetch process and log them to the console.

Important Reminders:

  • You cannot directly access the response body with 'no-cors'.
  • Only a limited set of headers are accessible.
  • Use 'no-cors' cautiously due to security implications.
  • Consider alternatives like CORS-enabled APIs or server-side proxies when possible.

Additional Notes

  • Preflight Requests: Even with 'no-cors', the browser may still send a preflight OPTIONS request to check if the actual request is safe to send. This can impact performance, especially for APIs that don't expect or handle OPTIONS requests efficiently.
  • Caching: Responses retrieved with 'no-cors' are typically opaque and not cached by the browser. This can lead to repeated requests for the same resource, impacting performance and potentially exceeding API rate limits.
  • Alternatives to 'no-cors':
    • CORS Proxy: Implement a server-side proxy that adds CORS headers to the response, allowing your frontend to access the data directly.
    • JSONP: For older APIs that don't support CORS, JSONP can be used, but it has limitations and security considerations.
    • WebSockets: For real-time communication, WebSockets can be a suitable alternative, as they have their own cross-origin policies.
  • Browser Compatibility: While 'no-cors' is supported by modern browsers, there might be slight variations in behavior. Testing across different browsers is recommended.
  • Debugging: Debugging 'no-cors' requests can be challenging due to the limited information available. Browser developer tools and network monitoring tools can help inspect requests and responses.

Security Best Practices:

  • Only use 'no-cors' with trusted APIs: Bypassing CORS can expose your application to security risks. Ensure you understand the potential implications and trust the API provider.
  • Validate API responses: Even though you cannot directly access the response body, you can still validate response headers and status codes to ensure data integrity.
  • Be mindful of sensitive data: Avoid sending sensitive information in 'no-cors' requests, as it might be exposed in request headers or other channels.

Use Cases for 'no-cors':

  • Fetching public resources: When you only need to check the availability or metadata of a resource, such as an image or a file, 'no-cors' can be sufficient.
  • Triggering server-side actions: You can use 'no-cors' to send simple requests that trigger actions on the server, even if you don't need to access the response data directly.
  • Analytics and tracking: For sending basic analytics data or tracking user interactions, 'no-cors' can be a lightweight option.

Summary

Topic Description
CORS (Cross-Origin Resource Sharing) A security mechanism that controls how websites access resources from other domains.
'no-cors' mode A fetch option that allows requests to resources without CORS enabled, but with limitations.
Limitations of 'no-cors' mode * Only simple HTTP methods (GET, HEAD, POST) allowed. * Limited access to response headers and body. * Cannot directly read response body in JavaScript.
Steps to use 'no-cors' mode 1. Identify API endpoint URL. 2. Construct fetch request with mode: 'no-cors'. 3. Handle opaque response (check status, access limited headers). 4. Implement error handling.
Important Considerations * Limited data access - not suitable for reading response body. * Security implications - bypasses CORS security. * Consider alternatives like JSONP or server-side proxies if needed. * Use 'cors' mode if API supports it.

Conclusion

In conclusion, understanding CORS and the 'no-cors' mode is crucial for developers working with cross-origin requests. While 'no-cors' offers a way to bypass CORS restrictions, it comes with limitations in data access and potential security risks. Carefully evaluate your use case and consider alternatives like CORS-enabled APIs or server-side proxies whenever possible. Remember to prioritize security and be mindful of the implications of bypassing CORS. By understanding these concepts and best practices, you can make informed decisions about handling cross-origin requests in your web applications.

References

  • Fetch API: The Ultimate Guide to CORS and 'no-cors' | by ... Fetch API: The Ultimate Guide to CORS and 'no-cors' | by ... | Do you need to fetch data from a third-party API or server in your web application? If so, you may have encountered Cross-Origin Resourceā€¦
  • Using the Fetch API - Web APIs | MDN Using the Fetch API - Web APIs | MDN | The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
  • javascript - How to fix the "set the request's mode to 'no-cors'" error ... javascript - How to fix the "set the request's mode to 'no-cors'" error ... | Jan 22, 2019 ... ... mode to 'no-cors' to fetch the resource with CORS disabled. I have tried ... Trying to use fetch and pass in mode: no-cors Ā· 0 Ā· Wordpress allowĀ ...
  • Plugin won't connect to API - Ask the community - Figma Community ... Plugin won't connect to API - Ask the community - Figma Community ... | Hello! I am trying to hookup a plugin to an API. Basically, I am extracting the local variables from a Figma file and I want to store them in a database. Thus far, I am able to get the variables to my codebase. I have also built a simple API that adds a row to my database. I know that the API works because I have tested it in Postman and get the expected response. The function to use this API call in the code looks like this: async function sendJSONToDB(files) { console.log("in download")...
  • axios vs fetch - no-cors mode... Ā· Issue #1358 axios vs fetch - no-cors mode... Ā· Issue #1358 | Axios - fails axios('https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', { method: 'HEAD', mode: 'no-cors', headers: { 'Access-Control-Allow-Origin': '*', Accept: 'application/json', '...
  • API, Error Using the Get users by usernames - Twitter API v2 - X ... API, Error Using the Get users by usernames - Twitter API v2 - X ... | Hi. Iā€™m trying to use the Twitter API v2, but iā€™m having some issues. Iā€™m trying to use twitterā€™s sample github code ( get_users_with_bearer_token.js). Getting some errors. ā€œError: incorrect header checkā€. Iā€™m basically using the same code, funny thing is that the Network tab contains the correct response, requestā€™s response code is 200 ok.
  • How to resolve Cros Error while fetching API in LWC lightning How to resolve Cros Error while fetching API in LWC lightning | Trailhead, the fun way to learn Salesforce
  • Getting a 403 when doing a POST to Jira Cloud API using proxy ... Getting a 403 when doing a POST to Jira Cloud API using proxy ... | Hi everyone! Forgive me if this has been solved, Iā€™ve looked through every past related question I could find and was not able to get a working solution. Iā€™m building a small Figma plugin to allow users to create tickets in JIRA from Figma. Since Figma effectively runs as a browser-based application, following the advice of past questions on here I am doing the request through a proxy (Heroku), following the advice of the first answer in a stack overflow post (it wonā€™t let me post the link, ple...
  • API access control issue - help - Meteor.js forums API access control issue - help - Meteor.js forums | Hello everyone I need to retrieve data from a remote server, through an API whose URL I have. If I use my browser (chrome or firefox) I get the expected result in the form of a JSON file. If I use the following code fetch(URL) .then(function(res) { if (res.ok) { return res.json(); } }) .then(function(value) { console.log(value); }) .catch(function(err) { }); I have the error: Access to fetch at ā€˜https://www. ā€¦ā€™ from origin ...

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait