fetch()

Sends an HTTP request and returns a promise with the server’s response (a Response object).

Returns
A promise fulfilled with a Response object.
On this page

Example

#
JavaScript
const response = await fetch('data:application/json,{"name":"Emma","level":7}')
console.log(response.ok, response.status)

const user = await response.json()
console.log(`${user.name} is level ${user.level}`)
Console
true 200
Emma is level 7

The data: address contains the response directly in the address, so it works without a connection to a server. In a real application, you’d have an API address there instead, such as "/api/users/7".

Definition and usage

#

The fetch() function retrieves data from the network. It takes a resource address and an optional settings object, and returns a promise that fulfills with a Response object as soon as the response headers arrive. You read the body separately, with methods like response.json() or response.text(), which also return promises.

An important pitfall: fetch() rejects its promise only on a network error, such as no connection or a blocked request. Responses with a 404 or 500 status code count as a success for it. That’s why you should always check response.ok (it’s true for status codes from 200 to 299) or response.status.

The second argument lets you change the method (POST, PUT, DELETE), add headers, and send a body in the body field, usually as JSON prepared with JSON.stringify(). The signal option lets you abort the request, for example after a timeout.

The examples on this page have no network access, so the first one fetches a data: address, where the data is written directly into the address. With a real API the code looks exactly the same, only the address changes.

Syntax

#
Syntax
fetch(resource)
fetch(resource, options)

Parameters

#
  • resource

    a string, URL, or Request

    The resource address, e.g. "/api/courses" or a full URL.
  • options

    optional object

    Request settings, including method, headers, body, signal, and credentials.

More examples

#
Checking response.ok
JavaScript
async function loadCourses() {
  const response = await fetch('/api/courses')

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`)
  }

  return response.json()
}

try {
  const courses = await loadCourses()
  console.log(courses.length)
} catch (error) {
  console.log(error.message)
}
Result
HTTP error: 404

This example needs a real server, so it doesn’t run in the preview. The output shows what happens when the server responds with a 404 status code.

Sending data with POST
JavaScript
const response = await fetch('/api/progress', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ lessonId: 12, score: 95 })
})

const result = await response.json()
console.log(result)
Result
{ saved: true, points: 150 }

This example needs a real server, so it doesn’t run in the preview. The output is a sample API response.

A timeout for the request
JavaScript
try {
  const response = await fetch('/api/ranking', { signal: AbortSignal.timeout(3000) })
  console.log(response.status)
} catch (error) {
  console.log(error.name)
}
Result
TimeoutError

The output shows what happens when the server doesn’t respond within 3 seconds. The request is then aborted, and fetch() rejects its promise.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Always check response.ok. Status codes like 404 and 500 don’t reject the promise returned by fetch().
  • When sending JSON, set the Content-Type: application/json header and convert the data to text with JSON.stringify().
  • You can read the response body only once. A second call to response.json() on the same response will throw an error.

Related entries

#

Spotted a mistake or missing an example? Write to us.