fetch() (JavaScript)

fetch() is the built-in browser function for making HTTP requests to a server. It returns a promise that resolves to the response.

JavaScript

fetch() is the modern replacement for XMLHttpRequest. You typically await the response, then call response.json() to read JSON data.

Note that fetch only rejects on network failure — an HTTP error like 404 still resolves, so check response.ok yourself.

Syntax

fetch(url, options).then(response => ...)

Examples

JavaScript

async function getUser() {
  const res = await fetch("/api/user");
  const user = await res.json();
  console.log(user.name);
}

Output:

(logs the user's name once the request finishes)

Learn it in a lesson

See also

Back to the Dictionary