📋 Headers = Request Metadata
API needs authentication, content type, custom data. Request headers send additional info. Essential for API integration.
📝 Sending Headers
// Fetch with headers
const response = await fetch('/api/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token',
'X-API-Key': 'your-api-key',
'Accept': 'application/json'
}
});
// With authentication
const token = 'jwt-token-here';
await fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
});
// Multiple custom headers
await fetch('/api/custom', {
headers: {
'X-Request-ID': crypto.randomUUID(),
'X-Client-Version': '1.0.0',
'X-Environment': 'production'
}
});
// Using Headers constructor
const headers = new Headers();
headers.append('Authorization', `Bearer ${token}`);
headers.append('Content-Type', 'application/json');
const response = await fetch('/api/data', { headers });
🎯 Common Headers
// Authentication Authorization: BearerX-API-Key: // Content Content-Type: application/json Content-Type: application/x-www-form-urlencoded Accept: application/json // Caching Cache-Control: no-cache If-Modified-Since: Mon, 15 Jan 2024 12:00:00 GMT // Client info User-Agent: MyApp/1.0.0 Accept-Language: en-US // Custom X-Request-ID: unique-id X-Client-Version: 1.0.0 X-Environment: production
💡 Best Practices
- Set Content-Type for POST/PUT requests
- Send Authorization token for protected APIs
- Use X-Request-ID for tracing
- Don’t send sensitive data in headers
- Check API documentation for required headers
“API requires auth header. Added Authorization: Bearer token. Request works. Headers are essential for secure APIs.”
