Sending Headers with Fetch API

To send HTTP headers to the server using the JavaScript Fetch API, you can pass these headers with the "options" parameter to the fetch(URL, options) method. The headers are passed in the "key: value" format and may override some standard HTTP headers or pass new ones. Not all default HTTP headers can be overridden for Fetch API requests; for example, you can override the Content-Type header, but you cannot override the Content-Length header. In this JavaScript Fetch API Headers example, we send a request with a Content-Type header to the ReqBin echo URL using the fetch() method. Click Execute to run the JavaScript Fetch Headers example online and see the result.
Sending Headers with Fetch API Execute
fetch('https://reqbin.com/echo/get/json', {
  headers: {
    'Content-Type': 'application/json',
  }
})
	.then(response => response.json())
	.then(data => console.log(JSON.stringify(data)))
Updated: Viewed: 10643 times

What is Fetch API?

The Fetch API is a modern, efficient, and flexible way to fetch network resources in JavaScript, that replaces XMLHttpRequest (XHR) object. The Fetch API is based on Promises, has a simpler syntax, supports streams, and has built-in support for Blobs (Binary large objects) and FormData. Promises make it easier to make asynchronous requests and avoid nested callbacks.

What are HTTP headers?

Each HTTP request and response consists of a request/status line, HTTP headers, and an HTTP body. An HTTP header is a "key: value" pair containing information about the request being sent to a server. Request Headers pass information about the client (such as User-Agent, Accept-Encoding, Authorization, etc.). The request headers contain information that the server needs to process the client request. Response headers provide clients with important information for correctly interpreting, processing, or displaying the server's response. Server response headers include such metadata as Content-Type, Content-Length, server type, and more.

How to send an HTTP request using Fetch API?

The Fetch API is a relatively new API for sending requests from a browser or Node.js. The following is an example of making POST a request to the ReqBin echo URL with Fetch API:

JavaScript POST request with Fetch API
fetch('https://reqbin.com/echo/post/json', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ "name": "Leo" })
})
  .then(response => response.json())
  .then(response => console.log(JSON.stringify(response)))

How to send an HTTP header using Fetch API?

The Fetch API in JavaScript supports two ways of sending HTTP headers:

  1. Directly in the options object: You can pass HTTP headers with the second parameter of the fetch() method. The headers are passed in the "key: value" format.

    Sending HTTP header using Fetch
    fetch('https://reqbin.com/echo/get/json', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }})
      .then(response => response.text())
      .then(text => console.log(text))

  2. Using the Headers object: the Headers object stores HTTP header information. You can create a Headers object using the new Headers() constructor and append headers to it using the append() method. The Headers object is then passed as an argument in the "headers" option of the fetch() method.

    Sending Header with Headers Object using Fetch
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
              
    fetch('https://reqbin.com/echo/get/json', {
      method: 'GET',
      headers: headers
    })
      .then(response => response.json())
      .then(data => console.log(JSON.stringify(data)))

What headers cannot be overridden in the Fetch API?

Some standard HTTP headers are designed to provide security, maintain predictable behavior, and enforce protocol restrictions. These headers cannot be overridden when sending requests using the Fetch API:

  • Security: security headers such as Origin cannot be overridden for security purposes
  • Protocol constraints: headers, such as Connection and Content-Length, control the underlying protocol, and the HTTP specification already defines their behavior

JavaScript Fetch Headers Examples

The following are examples of using the fetch() method with headers in JavaScript:

Sending HTTP header using the Fetch API

The following is an example of sending a Fetch API request. The fetch() uses GET by default if no HTTP method is passed:

Fetch API Request with HTTP header
fetch('https://reqbin.com/echo/get/json', {
   headers: {
    'Accept': 'application/json'
   }})
  .then(response => response.text())
  .then(text => console.log(text))

Sending Multiple Headers with Fetch API

The following is an example of sending multiple headers to the server in a fetch() request:

Fetch API Request with Multiple Headers
fetch('https://reqbin.com/echo/get/json', {
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {token}',
  }
})
   .then(response => response.json())
   .then(data => console.log(JSON.stringify(data)))

Sending Authorization Header with Fetch API

To send a Bearer Token Authorization Header to the server, you need to call the fetch() method with the «headers: {Authentication: 'Bearer Token'}»:

Fetch API Request with Bearer Token Authorization Header
fetch('https://reqbin.com/echo/get/json', {
  headers: {
    'Authorization': 'Bearer Token'
  }
})
   .then(response => response.json())
   .then(data => console.log(JSON.stringify(data)))

Sending Custom Header with Fetch API

The following is an example of sending a custom header to the server in a fetch() request:

Fetch API Request with Custom-Header
fetch('https://reqbin.com/echo/get/json', {
  headers: {
    'X-Custom-Header': 'header value'
  }
}) 
   .then(resp => resp.json())
   .then(data => console.log(JSON.stringify(data)))

See also