fetch()
Sends an HTTP request and returns a promise with the server’s response (a Response object).
- Returns
- A promise fulfilled with a
Responseobject.
Example
#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}`)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
#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, includingmethod,headers,body,signal, andcredentials.
More examples
#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)
}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.
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){ 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.
try {
const response = await fetch('/api/ranking', { signal: AbortSignal.timeout(3000) })
console.log(response.status)
} catch (error) {
console.log(error.name)
}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 byfetch(). - When sending JSON, set the
Content-Type: application/jsonheader and convert the data to text withJSON.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
#- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- Promise.prototype.then()Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.
- JSON.parse()Converts a string in JSON format into a JavaScript value, such as an object or array.
- JSON.stringify()Converts a JavaScript value, such as an object or array, into a string in JSON format.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
Spotted a mistake or missing an example? Write to us.