fetch() global function - Web APIs | MDN (2024)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

Note: This feature is available in Web Workers.

The global fetch() method starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.

The promise resolves to the Response object representing the response to your request.

A fetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error. A fetch() promise does not reject if the server responds with HTTP status codes that indicate errors (404, 504, etc.). Instead, a then() handler must check the Response.ok and/or Response.status properties.

The fetch() method is controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving.

Note: The fetch() method's parameters are identical to those of the Request() constructor.

Syntax

js

fetch(resource)fetch(resource, options)

Parameters

resource

This defines the resource that you wish to fetch. This can either be:

  • A string or any other object with a stringifier — including a URL object — that provides the URL of the resource you want to fetch.
  • A Request object.
options Optional

An object containing any custom settings you want to apply to the request. The possible options are:

body

Any body that you want to add to your request: this can be a Blob, an ArrayBuffer, a TypedArray, a DataView, a FormData, a URLSearchParams, string object or literal, or a ReadableStream object. This latest possibility is still experimental; check the compatibility information to verify you can use it. Note that a request using the GET or HEAD method cannot have a body.

browsingTopics Experimental

A boolean specifying that the selected topics for the current user should be sent in a Sec-Browsing-Topics header with the associated request. See Using the Topics API for more details.

cache

A string indicating how the request will interact with the browser's HTTP cache. The possible values, default, no-store, reload, no-cache, force-cache, and only-if-cached, are documented in the article for the cache property of the Request object.

credentials

Controls what browsers do with credentials (cookies, HTTP authentication entries, and TLS client certificates). Must be one of the following strings:

  • omit: Tells browsers to exclude credentials from the request, and ignore any credentials sent back in the response (e.g., any Set-Cookie header).
  • same-origin: Tells browsers to include credentials with requests to same-origin URLs, and use any credentials sent back in responses from same-origin URLs. This is the default value.
  • include: Tells browsers to include credentials in both same- and cross-origin requests, and always use any credentials sent back in responses.

    Note: Credentials may be included in simple and "final" cross-origin requests, but should not be included in CORS preflight requests.

headers

Any headers you want to add to your request, contained within a Headers object or an object literal with String values. Note that some names are forbidden.

Note: The Authorization HTTP header may be added to a request, but will be removed if the request is redirected cross-origin.

integrity

Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).

keepalive

The keepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon() API.

method

The request method, e.g., "GET", "POST". The default is "GET". Note that the Origin header is not set on Fetch requests with a method of HEAD or GET. (This behavior was corrected in Firefox 65 — see Firefox bug 1508661.) Any string which is a case-insensitive match for one of the methods in RFC 9110 will be uppercased automatically. If you want to use a custom method (like PATCH), you should uppercase it yourself.

mode

The mode you want to use for the request, e.g., cors, no-cors, or same-origin.

priority

Specifies the priority of the fetch request relative to other requests of the same type. Must be one of the following strings:

high

A high priority fetch request relative to other requests of the same type.

low

A low priority fetch request relative to other requests of the same type.

auto

Automatically determine the priority of the fetch request relative to other requests of the same type (default).

redirect

How to handle a redirect response:

follow

Automatically follow redirects. Unless otherwise stated the redirect mode is set to follow.

error

Abort with an error if a redirect occurs.

manual

Caller intends to process the response in another context. See WHATWG fetch standard for more information.

referrer

A string specifying the referrer of the request. This can be a same-origin URL, about:client, or an empty string.

referrerPolicy

Specifies the referrer policy to use for the request. May be one of no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url.

signal

An AbortSignal object instance; allows you to communicate with a fetch request and abort it if desired via an AbortController.

Return value

A Promise that resolves to a Response object.

Exceptions

AbortError DOMException

The request was aborted due to a call to the AbortController abort() method.

NotAllowedError DOMException

Usage of the Topics API is specifically disallowed by a browsing-topics Permissions Policy, and a fetch() request was made with browsingTopics: true.

TypeError

Can occur for the following reasons:

Reason Failing examples
Invalid header name.
// space in "C ontent-Type"const headers = { 'C ontent-Type': 'text/xml', 'Breaking-Bad': '<3',};fetch('https://example.com/', { headers }); 
Invalid header value. The header object must contain exactly two elements.
const headers = [ ['Content-Type', 'text/html', 'extra'], ['Accept'],];fetch('https://example.com/', { headers }); 
Invalid URL or scheme, or using a scheme that fetch does not support, or using a scheme that is not supported for a particular request mode.
fetch('blob://example.com/', { mode: 'cors' }); 
URL includes credentials.
fetch('https://user:password@example.com/'); 
Invalid referrer URL.
fetch('https://example.com/', { referrer: './abc\u0000df' }); 
Invalid modes (navigate and websocket).
fetch('https://example.com/', { mode: 'navigate' }); 
If the request cache mode is "only-if-cached" and the request mode is other than "same-origin".
fetch('https://example.com/', { cache: 'only-if-cached', mode: 'no-cors',}); 
If the request method is an invalid name token or one of the forbidden headers ('CONNECT', 'TRACE' or 'TRACK').
fetch('https://example.com/', { method: 'CONNECT' }); 
If the request mode is "no-cors" and the request method is not a CORS-safe-listed method ('GET', 'HEAD', or 'POST').
fetch('https://example.com/', { method: 'CONNECT', mode: 'no-cors',}); 
If the request method is 'GET' or 'HEAD' and the body is non-null or not undefined.
fetch('https://example.com/', { method: 'GET', body: new FormData(),}); 
If fetch throws a network error.

Examples

In our Fetch Request example (see Fetch Request live) we create a new Request object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run Response.blob() on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element.

js

const myImage = document.querySelector("img");const myRequest = new Request("flowers.jpg");fetch(myRequest) .then((response) => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.blob(); }) .then((response) => { myImage.src = URL.createObjectURL(response); });

In our Fetch Request with init example (see Fetch Request init live) we do the same thing except that we pass in an options object when we invoke fetch(). In this case, we can set a Cache-Control value to indicate what kind of cached responses we're okay with:

js

const myImage = document.querySelector("img");const reqHeaders = new Headers();// A cached response is okay unless it's more than a week oldreqHeaders.set("Cache-Control", "max-age=604800");const options = { headers: reqHeaders,};// Pass init as an "options" object with our headers.const req = new Request("flowers.jpg", options);fetch(req).then((response) => { // ...});

You could also pass the init object in with the Request constructor to get the same effect:

js

const req = new Request("flowers.jpg", options);

You can also use an object literal as headers in init:

js

const options = { headers: { "Cache-Control": "max-age=60480", },};const req = new Request("flowers.jpg", options);

Specifications

Specification
Fetch Standard
# fetch-method

Browser compatibility

BCD tables only load in the browser

See also

  • Fetch API
  • ServiceWorker API
  • HTTP access control (CORS)
  • HTTP
fetch() global function - Web APIs | MDN (2024)

FAQs

What is fetch in Web API? ›

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.

How to use fetch for Apis? ›

In this example, we define the API endpoint for user data ( https://api.example.com/users/123 ). The fetch function is used to make the GET request, and we handle the response by checking if it's okay using the response. ok property. If the response is okay, we convert it to JSON and process the user data.

What is global fetch? ›

The global fetch() method starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.

How to fetch data using an API? ›

To Get data using the Fetch API in JavaScript, we use the fetch() function with the URL of the resource we want to fetch. By default, the fetch method makes the Get request.

Is Fetch API a RESTful API? ›

Fetch API allows us to get data from a local or remote server via a RESTful API. It is a promise-based asynchronous API where we can either await it or use promise chaining to get the response. This is where XMLHttpRequest and the Fetch API differ.

Is fetch part of REST API? ›

The Fetch API and REST API are two different concepts. The Fetch API is a browser built-in interface that allows JavaScript to make network requests similar to XMLHttpRequest (XHR). It is used to fetch resources (data) asynchronously across the network.

What is the fetch function? ›

fetch() is a mechanism that lets a user make simple AJAX (Asynchronous JavaScript and XML) calls with JavaScript. This means you can use this function to make a call without interrupting the execution of other operations.

What is the difference between GET and fetch API? ›

When comparing the syntax of GET and FETCH operations, it's essential to understand their context within HTTP requests. GET is a method used to retrieve data from a specified resource, while FETCH is a modern API in JavaScript that provides a more powerful and flexible feature set for making HTTP requests.

How to fetch API using json? ›

The Fetch API is used to make requests to servers and receive responses in a format such as JSON, XML, or HTML. Here is an example of how to use the Fetch API to POST JSON data: fetch('https://example.com/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.

Which browsers support Fetch? ›

Fetch
  • Chrome. 4 - 39 supported. See notes: ...
  • Edge * 12 - 13 supported. 14 - 123 Supported.
  • Safari. 3.1 - 10 supported. 10.1 - 17.3 Supported. ...
  • Firefox. 2 - 33 supported. 34 - 38. ...
  • Opera. 10 - 26 supported. See notes: ...
  • IE. 6 - 10 supported. 11 supported.
  • Chrome for Android. 124 Supported.
  • Safari on iOS * 3.2 - 10.2 supported.

What is the difference between Axios and fetch? ›

Axios automatically transforms the data to and from JSON, while fetch() requires you to call response. json() to parse the data to a JavaScript object. Axios provides the data in the response object, while fetch() provides the response object itself, which contains other information such as status, headers, and url.

Is Fetch built into JavaScript? ›

Fetch is a promise based HTTP request API built into JavaScript.

Why use Fetch API? ›

Simply put, the Fetch API makes it easy to get information from a website and do something with that data in your browser (or whatever environment you're using). For example, you can use the Fetch API to request an HTML document from a website and then parse it to get certain elements out.

How many ways can you fetch data from API? ›

Different ways to fetch data using API in React
  • Fetch Data from API using fetch method:
  • Fetch data using API using Axios Package:
  • Fetch data using API with Async-Await:
  • Using Custom hook:
Feb 28, 2024

How many ways to fetch API in JavaScript? ›

Different Ways to Fetch Data in React
  • Use the stale-while-revalidate (SWR) method. This method is used to fetch data from a server and is used in React. ...
  • Use the JavaScript Fetch() method. ...
  • Use the React Query library. ...
  • Use the Axios Library. ...
  • Use the useFetch custom hook from react-fetch-hook.
Dec 14, 2023

What is the difference between fetch and rest API? ›

Some of the differences include: Fetch is a function which takes a REST API url in its call. REST APIs can accept headers like for Authentication but Fetch call be called by any javascript in the browser and in fact passes these headers while calling the REST APIs.

What is the difference between API and fetch? ›

FETCH API: The FETCH API is a modern way to make HTTP requests in JavaScript. It provides a more powerful and flexible way to interact with APIs. Unlike the GET method, FETCH can be used to make various types of HTTP requests, including POST, PUT, DELETE, and more.

What is the advantage of using the Fetch API? ›

Fetch API features and pros:

supports streaming, response. body is ReadableStream, you can read data chunk by chunk without buffering, available for binary data. Can access partial content while response is being received. has cache control support (default, no-store, reload, no-cache, force-cache, only-if-cached)

What is the difference between fetch and promise? ›

Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

References

Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6392

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.