Cross-Origin Requests with Fetch API

Fri Mar 31 2023

4 min read

If you're a developer, you've probably encountered Cross-Origin Requests (CORS) at some point.

It's a security feature implemented in web browsers that restricts web pages from making requests to a different domain than the one that served the web page.

While it's an essential security feature, it can be frustrating when you need to fetch data from a different domain.

With Fetch API, you can define the API call is a CORS request.

How to make a Fetch API request a CORS request?

The Fetch API is a modern interface for making network requests that automatically handles CORS smoothly. Fetch API includes an Origin header in every request to identify the domain the request is coming from, which is essential for CORS requests.

If the server allows the request, it responds with an Access-Control-Allow-Origin header that specifies which domains are allowed to make requests to the server. Fetch API also automatically handles the CORS preflight request, making it effortless to work with CORS requests.

You can read more about CORS here.

Basic Concepts

Before we see how to implement this in our applications, let's look at the key concepts.

Origin and Same-Origin Policy

The Origin header is a security feature implemented by web browsers to enforce the same-origin policy. This policy restricts web pages from making requests to a different domain than the one that served the page.

The same-origin policy prevents malicious scripts from stealing sensitive information, such as user credentials or session cookies.

CORS Preflight Request

CORS Preflight Request is an additional request the browser sends to the server before sending the actual CORS request. The purpose of the preflight request is to ask the server whether the actual request is allowed or not.

The preflight request uses the HTTP OPTIONS method and includes the Access-Control-Request-Method and Access-Control-Request-Headers headers to specify the method and headers of the actual request.

For example, suppose a web page loaded from "example.com" needs to make a POST request to api.example.org with a custom X-Auth-Token header. Before sending the actual request, the browser will send a preflight request to api.example.org with the following headers.

OPTIONS /data HTTP/1.1 Host: api.example.org Access-Control-Request-Method: POST Access-Control-Request-Headers: X-Auth-Token

If the server hosting "api.example.org" allows the request, it will respond with the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers in the response, indicating that the actual request is allowed.

How to use it

Let's explore this concept with a practical example using an API from Rapid API's Hub. We'll make a cross-origin Fetch request to the GeoDB Cities API.

Loading component...

GET request

To make a simple GET request with Fetch API and CORS, you can use the following code:

js
fetch('https://wft-geo-db.p.rapidapi.com/v1/geo/countries/US', {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'X-RapidAPI-Key': 'your-api-key'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, the web page is making a GET request to the GeoDB Cities API to fetch the details for US, including number of regions. The request is being sent through the Rapid API Hub, which acts as a proxy server and adds the "X-RapidAPI-Key" header to the request to authenticate the user. The mode option is set to cors to indicate this is a Cross-Origin request.

If the Rapid API Hub and the API both allow CORS requests from the web page's domain, the response will be accepted and be parsed as JSON data and logged to the console. Otherwise, a CORS error will be thrown and caught in the catch block.

Wrap up

Cross-Origin requests with Fetch API enable us to securely access resources from other domains or servers. Understanding the concept of CORS and how to use the Fetch API to handle CORS requests is essential for building modern web applications that consume APIs and services from different sources.