Headers & Authentication in JavaScript
From the Fetch API cheat sheet ยท Request Configuration ยท verified Jul 2026
Headers & Authentication
Working with headers and authentication tokens
javascript
// Headers object
const headers = new Headers()
headers.append('Content-Type', 'application/json')
headers.set('Authorization', 'Bearer token123')
headers.get('Content-Type') // 'application/json'
headers.has('Authorization') // true
headers.delete('X-Custom')
// Headers in request
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'X-API-Key': 'secret-key',
'Accept-Language': 'en-US',
'User-Agent': 'MyApp/1.0'
}
})
// Headers from response
const contentType = response.headers.get('content-type')
const lastModified = response.headers.get('last-modified')
const customHeader = response.headers.get('x-custom-header')
// Iterate over headers
for (const [key, value] of response.headers.entries()) {
console.log(\`\${key}: \${value}\`)
}๐ Store tokens securely, never in code or URLs
๐ก Headers object provides better API than plain objects
โก Implement token refresh for seamless authentication
๐ Some headers are forbidden and cannot be set