HTTP Interceptors: Base URL, Tokens and Logging
What Is an Interceptor?
An interceptor sits between your code and the network. Every request passes through it on the way out and every response on the way back. It is perfect for work you would otherwise repeat everywhere.
- Add the API base URL
- Attach an auth token
- Show a loading bar
- Log requests
- Handle errors in one place
A Functional Interceptor
typescript
import { HttpInterceptorFn } from '@angular/common/http';
import { environment } from '../../environments/environment';
export const baseUrlInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.startsWith('/api')) {
const apiReq = req.clone({ url: environment.apiUrl + req.url }); // requests are immutable: clone
return next(apiReq);
}
return next(req);
};
Why clone?
HttpRequest objects are immutable. To change a request, create a modified copy with clone() and pass that to next.
Register Interceptors
typescript
provideHttpClient(
withFetch(),
withInterceptors([baseUrlInterceptor, authInterceptor, loggingInterceptor, errorInterceptor]),
)
Request order: first to last. Response order: last to first.
Auth Token Interceptor
typescript
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token(); // inject() works inside an interceptor
if (!token) return next(req);
return next(req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
}));
};
Logging Interceptor with Timing
typescript
import { tap } from 'rxjs';
import { HttpResponse } from '@angular/common/http';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
return next(req).pipe(
tap({
next: event => {
if (event instanceof HttpResponse) {
const ms = Math.round(performance.now() - started);
console.log(`${req.method} ${req.urlWithParams} -> ${event.status} (${ms} ms)`);
}
},
error: err => console.warn(`${req.method} ${req.urlWithParams} failed`, err.status),
}));
};
Global Error Interceptor
typescript
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
const toast = inject(ToastService);
return next(req).pipe(
catchError((err: HttpErrorResponse) => {
switch (err.status) {
case 0: toast.error('Network problem. Check your connection.'); break;
case 401: router.navigate(['/login']); break;
case 403: toast.error('You do not have permission.'); break;
case 404: break; // let the caller decide
default: if (err.status >= 500) toast.error('Server error. Try again later.');
}
return throwError(() => err); // always re-throw
}));
};
Skip an Interceptor for One Request
typescript
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(SKIP_AUTH)) return next(req);
// ...add token
};
// usage: a public API that must not get our token
this.http.get(url, { context: new HttpContext().set(SKIP_AUTH, true) });
A Simple Loading Counter
typescript
@Injectable({ providedIn: 'root' })
export class LoadingService {
private active = signal(0);
loading = computed(() => this.active() > 0);
start() { this.active.update(n => n + 1); }
stop() { this.active.update(n => Math.max(0, n - 1)); }
}
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
const loading = inject(LoadingService);
loading.start();
return next(req).pipe(finalize(() => loading.stop()));
};
Keep interceptors small: One job per interceptor makes them easy to test and reorder.
Conclusion
Functional interceptors are plain functions registered with withInterceptors. Clone requests to change them, use inject() for services and always re-throw errors you only observe.
Quick Summary: HttpInterceptorFn(req, next) + req.clone() + withInterceptors([...]).

