Sub topic 2
Setting Up HttpClient with provideHttpClient
This chapter covers how HttpClient gets into a standalone Angular application. You will see what provideHttpClient registers, which feature functions it accepts, and which setup mistakes cause most "No provider" errors and missing interceptors.
It assumes you know TypeScript, standalone bootstrapping with bootstrapApplication, and how Angular's dependency injection resolves providers. Writing interceptors and using HttpClient inside services are covered in later chapters. Here the focus is on wiring.
What provideHttpClient registers
HttpClient is a service, so it needs a provider before you can inject it. provideHttpClient() returns a set of environment providers that register several things together:
HttpClientitself, the class your services inject.- An
HttpHandlerchain that runs each request through the configured interceptors. - An
HttpBackend, the object that actually sends the request over the network, using eitherfetchorXMLHttpRequest. - XSRF protection, which reads a token cookie and attaches it as a header on mutating requests.
You pass feature functions as arguments to change this setup. Each feature is a small object that adds or replaces providers. This pattern replaces the older HttpClientModule, which bundled a fixed set of providers and needed extra modules to change them.
The minimal setup
A standalone application keeps its root providers in an ApplicationConfig object, usually in app.config.ts:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]
};The config is passed to bootstrapApplication in main.ts:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));If you don't need any features yet, provideHttpClient() with no arguments is a complete setup. The authInterceptor above is a functional interceptor. Its body is explained in the interceptors chapter. For now, note that this is where it gets registered.
The feature functions
Every feature is imported from @angular/common/http and passed to provideHttpClient in any order.
| Feature | What it does | When to use it |
|---|---|---|
| `withInterceptors([...])` | Registers functional interceptors, run in array order | Auth headers, logging, error mapping |
| `withInterceptorsFromDi()` | Includes class-based interceptors registered with the `HTTP_INTERCEPTORS` token | Migrating older code or using libraries that still ship class interceptors |
| `withFetch()` | Uses the `fetch` API as the backend | Server-side rendering, or older versions where XHR is the default |
| `withXhr()` | Uses `XMLHttpRequest` as the backend (Angular 21+) | You need upload progress events |
| `withXsrfConfiguration({...})` | Changes the XSRF cookie and header names | Your backend uses names other than `XSRF-TOKEN` / `X-XSRF-TOKEN` |
| `withNoXsrfProtection()` | Turns off the built-in XSRF interceptor | Token-based APIs that don't use cookies |
| `withJsonpSupport()` | Enables `http.jsonp()` | Legacy third-party APIs without CORS |
| `withRequestsMadeViaParent()` | Sends requests on to the parent injector's HttpClient after local interceptors run | A child injector that adds interceptors without discarding the parent's |
A fuller production configuration might look like this:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import {
provideHttpClient,
withFetch,
withInterceptors,
withXsrfConfiguration
} from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
import { loggingInterceptor } from './logging.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withFetch(),
withInterceptors([loggingInterceptor, authInterceptor]),
withXsrfConfiguration({
cookieName: 'CSRF-TOKEN',
headerName: 'X-CSRF-TOKEN'
})
)
]
};Choosing a backend: fetch or XMLHttpRequest
The backend is the lowest layer, so the choice affects behavior you can observe:
- fetch works in server-side rendering and edge runtimes without extra polyfills. If you use SSR with the XHR backend, Angular logs a warning recommending
withFetch(). - XMLHttpRequest reports upload progress events. The fetch backend can report download progress but cannot report upload progress, because
fetchhas no upload progress API.
From Angular 21, fetch is the default and withXhr() opts back into XMLHttpRequest. On earlier versions, XHR is the default and withFetch() opts into fetch. Passing withFetch() explicitly does no harm on newer versions and makes your intent clear.
Mixing functional and class-based interceptors
If you migrate an NgModule app, you may have classes that implement HttpInterceptor and are registered with HTTP_INTERCEPTORS. Those classes are ignored unless you add withInterceptorsFromDi():
import { ApplicationConfig } from '@angular/core';
import {
HTTP_INTERCEPTORS,
provideHttpClient,
withInterceptors,
withInterceptorsFromDi
} from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
import { LegacyLoggingInterceptor } from './legacy-logging.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([authInterceptor]),
withInterceptorsFromDi()
),
{ provide: HTTP_INTERCEPTORS, useClass: LegacyLoggingInterceptor, multi: true }
]
};Functional interceptors run first, then the DI-based ones. Angular's documentation recommends functional interceptors for new code because their ordering is predictable.
Where to call provideHttpClient
provideHttpClient returns environment providers. You can use it in ApplicationConfig.providers, in a route's providers array, or in an environment injector you create with createEnvironmentInjector. You cannot use it in a component's providers array. Angular throws an error if you try.
The child injector trap
When a lazy route calls provideHttpClient again, that route gets a separate HttpClient with its own interceptor chain. The root interceptors don't run for requests made inside that route. Developers usually find this when their auth header disappears on one feature's pages.
To add interceptors for one route and keep the root chain, add withRequestsMadeViaParent():
// app.routes.ts
import { Routes } from '@angular/router';
import {
HttpInterceptorFn,
provideHttpClient,
withInterceptors,
withRequestsMadeViaParent
} from '@angular/common/http';
const adminHeaderInterceptor: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { 'X-Admin-Area': 'true' } }));
export const routes: Routes = [
{
path: 'admin',
loadComponent: () =>
import('./admin/admin.component').then(m => m.AdminComponent),
providers: [
provideHttpClient(
withInterceptors([adminHeaderInterceptor]),
withRequestsMadeViaParent()
)
]
}
];Requests from the admin area now run through adminHeaderInterceptor first, then through every root interceptor, then reach the root backend.
Migrating from HttpClientModule
HttpClientModule, HttpClientJsonpModule and HttpClientXsrfModule are deprecated as of Angular 18. Each one maps to a provider form:
| Old NgModule API | Provider equivalent |
|---|---|
| `HttpClientModule` | `provideHttpClient(withInterceptorsFromDi())` |
| `HttpClientJsonpModule` | `withJsonpSupport()` |
| `HttpClientXsrfModule.withOptions({...})` | `withXsrfConfiguration({...})` |
| `HttpClientXsrfModule.disable()` | `withNoXsrfProtection()` |
| `HttpClientTestingModule` | `provideHttpClient(), provideHttpClientTesting()` |
The migration includes withInterceptorsFromDi() because HttpClientModule always honored HTTP_INTERCEPTORS. Leaving it out removes your class-based interceptors without any error. Angular ships a schematic that applies this mapping: ng generate @angular/core:http-providers. Older CLI versions ran it automatically during ng update to v18.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for HttpClient!` | Angular 20 or earlier with no `provideHttpClient()` in the config, or a test bed without it | Add `provideHttpClient()` to the providers |
| Class-based interceptor never runs | `withInterceptorsFromDi()` is missing | Add it to `provideHttpClient` |
| Interceptor runs on most pages but not one feature | That route provides its own HttpClient | Remove the duplicate, or add `withRequestsMadeViaParent()` |
| Error about providers in a component | `provideHttpClient` placed in `@Component({ providers })` | Move it to app config or route providers |
| SSR warning about fetch | XHR backend used with server rendering | Add `withFetch()` |
| Upload progress never reports | fetch backend in use | Use `withXhr()` (v21+) or drop `withFetch()` |
| Mock requests hit the network in tests | `provideHttpClientTesting()` listed before `provideHttpClient()` | List `provideHttpClient()` first |
The last row is easy to get wrong. provideHttpClientTesting() replaces the backend that provideHttpClient() registers, so it must come after it in the providers array. The testing chapter covers the rest of test setup.
Exercise
Your app registers authInterceptor in app.config.ts with provideHttpClient(withInterceptors([authInterceptor])). A lazy reports route adds providers: [provideHttpClient(withInterceptors([reportCacheInterceptor]))]. Report requests now arrive at the server without an Authorization header. Explain why and give the one-line fix.
Show answer
The route's provideHttpClient call creates a second HttpClient in the route's environment injector, with its own interceptor chain and backend. Requests made inside the route use that client, so only reportCacheInterceptor runs and the root authInterceptor is skipped. Add withRequestsMadeViaParent() to the route's call: provideHttpClient(withInterceptors([reportCacheInterceptor]), withRequestsMadeViaParent()). Requests then pass through the local interceptor and on to the root client's chain.
Exercise
You are migrating an NgModule app whose AppModule imports HttpClientModule and registers two classes with HTTP_INTERCEPTORS. The app uses server-side rendering and has no file uploads. Write the provideHttpClient call for the new app.config.ts.
Show answer
provideHttpClient(withInterceptorsFromDi(), withFetch()). withInterceptorsFromDi() keeps the two class-based interceptors working, because they are registered through the HTTP_INTERCEPTORS token. withFetch() selects the fetch backend, which suits SSR. Since the app has no uploads, losing upload progress events costs nothing. The HTTP_INTERCEPTORS provider objects move unchanged into the same providers array.
Exercise
Why does Angular reject provideHttpClient() inside a component's providers array, while it accepts the call inside a route's providers array?
Show answer
provideHttpClient returns environment providers, which can only be installed in an environment injector. Routes with providers get their own environment injector, as does the application root. Components create element injectors, which are a different kind of injector, so Angular raises an error instead of building an HttpClient there.