How to set request headers in fetch?

Tue Oct 11 2022

2 min read

Fetch is a web API that can make an API request to API endpoints to perform CRUD operations. It often takes a request header that contains additional information for the server to process the request.

In this piece, we will learn how to set the request header in the fetch API. So without any further ado, let’s jump in!

HTTP Request Headers

HTTP headers allow clients and servers to talk to each other and pass extra bits of information or instructions. Request headers include additional information sent by the client to the server. They usually contain instructions about the required data and information about the client. The server can use these headers to customize the response. Some examples of request headers include:

  • Content-Type
  • Authentication and Authorization.
  • Encoding.

Set Request headers

Let’s do it in steps to learn how to set request headers using fetch.

→ STEP #1

We need an API that we can call to learn how to use the fetch API in Next.js. For this, we will use RapidAPI Hub, which provides over 35,000+ APIs.

We will use the Famous Quotes API from RapidAPI Hub, so please go ahead and subscribe to it.

→ STEP #2

Go ahead and create a simple HTML file with a script tag. This will contain all the JavaScript code of your application.

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learn to set request header in Fetch API</title>
</head>
<body>
<script></script>
</body>
</html>

→ STEP #3

To set the request header for an API request in fetch, pass an object as a second parameter to the fetch method. The object will need a headers key whose value will be an object. This object will hold all the request headers for the API request.

js
fetch(`API-ENDPOINT`, {
headers: {}
})

Let’s integrate the Famous Quotes API.

html
<script>
fetch('https://famous-quotes4.p.rapidapi.com/random?category=all&count=2', {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com',
},
})
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
</script>

You can see that I have provided a headers object to the API request. This object contains two keys, i.e., X-RapidAPI-Key and 'X-RapidAPI-Host.

Wrap Up

That’s all, folks! I hope this piece helped you learn how to set request headers using fetch. If you want to learn more about the fetch API, I recommend you read this piece.