How to add headers to requests in Angular
Adding custom headers to HTTP requests is essential for authentication, content type specification, and API communication in Angular applications.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented custom headers in numerous Angular enterprise applications and admin dashboards.
From my 25 years of experience in web development and 11 years with Angular, the most effective approach is to use the HttpHeaders class with HttpClient methods.
This pattern provides type-safe header management and flexible request configuration.
Use HttpHeaders class to create and add custom headers to your HTTP requests.
import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
getData() {
const headers = new HttpHeaders({
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type': 'application/json',
'X-Custom-Header': 'custom-value'
})
return this.http.get('/api/data', { headers })
}
postData(data: any) {
const headers = new HttpHeaders()
.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
.set('Content-Type', 'application/json')
return this.http.post('/api/data', data, { headers })
}
}
The HttpHeaders class creates immutable header objects that can be passed to any HttpClient method. You can create headers using object syntax or the fluent set() method for chaining. Headers are included in the options object as the second parameter for GET requests or third parameter for POST/PUT requests. The HttpHeaders class ensures type safety and prevents common header-related errors.
This is the same header management approach we use in CoreUI Angular admin templates for secure API communication and authentication. For global headers like authentication tokens, consider using HTTP interceptors to automatically add headers to all requests without repeating code.



