AI Workshop: learn to build apps with AI →
Fetch: Request headers

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Being able to set HTTP request headers is essential, and fetch lets us do this using the Headers object:

const headers = new Headers()
headers.append('Content-Type', 'application/json')

or:

const headers = new Headers({
  'Content-Type': 'application/json'
})

To attach the headers to the request, we use the Request object and pass it to fetch() instead of the URL.

Instead of:

fetch('./file.json')

we do

const request = new Request('./file.json', {
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
fetch(request)

The Headers object is not limited to setting values; we can also query it:

headers.has('Content-Type')
headers.get('Content-Type')

and we can delete a header that was previously set:

headers.delete('X-My-Custom-Header')

Lessons in this unit:

0: Introduction
1: How to use Fetch
2: Catching errors in network requests
3: The Response object
4: Getting the body content
5: The Request object
6: ▶︎ Request headers
7: POST requests