How to Set Headers in Fetch in JavaScript: Simple Guide
To set headers in
fetch in JavaScript, pass a headers object inside the options parameter of fetch. Use new Headers() or a plain object to specify key-value pairs for headers like Content-Type or Authorization.Syntax
The fetch function accepts two arguments: the URL and an options object. To set headers, include a headers property inside the options. This headers can be a Headers object or a plain JavaScript object with key-value pairs representing header names and values.
- url: The address you want to request.
- options: An object to configure the request.
- headers: Inside options, an object or
Headersinstance specifying HTTP headers.
javascript
fetch(url, { method: 'GET', // or 'POST', 'PUT', etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token123' } })
Example
This example shows how to send a POST request with JSON data and custom headers using fetch. It sets the Content-Type header to tell the server the data format and an Authorization header for access control.
javascript
const url = 'https://jsonplaceholder.typicode.com/posts'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer my-secret-token' }, body: JSON.stringify({ title: 'Hello', body: 'World', userId: 1 }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Output
{
id: 101,
title: "Hello",
body: "World",
userId: 1
}
Common Pitfalls
Common mistakes when setting headers in fetch include:
- Not passing headers inside the options object.
- Using incorrect header names or casing (header names are case-insensitive but best to use standard casing).
- Forgetting to stringify the body when sending JSON data.
- Trying to set headers after the request is sent (headers must be set before calling
fetch).
Here is a wrong and right way example:
javascript
// Wrong way: headers outside options fetch('https://example.com/api', { method: 'GET' }, { headers: { 'Authorization': 'token' } }); // Right way: headers inside options fetch('https://example.com/api', { method: 'GET', headers: { 'Authorization': 'token' } });
Quick Reference
Here is a quick cheat sheet for setting headers in fetch:
| Concept | Example |
|---|---|
| Set headers as object | { 'Content-Type': 'application/json' } |
| Use Headers instance | new Headers({ 'Authorization': 'Bearer token' }) |
| Include headers in options | fetch(url, { headers: { ... } }) |
| Set method | fetch(url, { method: 'POST' }) |
| Send JSON body | body: JSON.stringify(data) |
Key Takeaways
Always include headers inside the options object passed to fetch.
Use plain objects or Headers instances to set header key-value pairs.
Remember to stringify JSON data when sending it in the request body.
Set headers before calling fetch; you cannot modify them afterward.
Common headers include Content-Type and Authorization for APIs.