How To Get Response Headers on A Fetch Request

Posted By: Proper Noun Staff Posted On: January 27, 2022 Share:

Unlike a typical JSON response, the headers aren't immediately available on the response, which may trip you up if you're new to the Fetch API. Let's say your Fetch request looks like this:


fetch('//www.website.com/wp-json/wp/v2/posts?per_page=10&page=1')
.then(res => {
// do something
})

In order to access the response header 'X-WP-TotalPages' you would handle the response like this:


fetch('//www.website.com/wp-json/wp/v2/posts?per_page=10&page=1')
.then(res => {
// do something
totalPages = parseFloat(res.headers.get('X-WP-TotalPages'))
})

Instead of trying to access the name of the header right on the "headers" object, you have to use the get function to pull the header data.

This can be used in a variety of ways, for example making requests to any number of API's in frontend react applications.

You can read more about request and response headers at Mozilla.org

Other Good Resources

Proper Noun Staff

Proper Noun Staff

In-House Writing Team

Read informative articles, insights, and other resources right from the experts on the Proper Noun team.

Copyright © Proper Noun 2024