
Functional Auth Interceptor.
Angular Auth Interceptor
An Angular Auth Interceptor is a service that can be used to intercept HTTP requests and responses. It can be used to add custom headers, modify the request body, or handle errors.
// auth-interceptor.ts
import {
HttpHandlerFn,
HttpInterceptorFn,
HttpRequest,
} from "@angular/common/http";
import { inject } from "@angular/core";
import { AuthService } from "../services/auth.service";
export const AuthInterceptor: HttpInterceptorFn = (
req: HttpRequest<unknown>,
next: HttpHandlerFn
) => {
const authService = inject(AuthService);
if (req.url.includes("/api/")) {
const accessToken = authService.getToken()?.accessToken;
let requestHeaders = req.headers;
if (accessToken) {
requestHeaders = requestHeaders.set(
"Authorization",
`Bearer ${accessToken}`
);
if (!requestHeaders.has("Accept")) {
requestHeaders = requestHeaders.set("Accept", "application/json");
}
if (!requestHeaders.has("Content-Type")) {
requestHeaders = requestHeaders.set("Content-Type", "application/json");
}
}
const authReq = req.clone({ headers: requestHeaders });
return next(authReq);
}
return next(req);
};
Usage
// app.config.ts
import { provideHttpClient, withInterceptors } from "@angular/common/http";
import { ApplicationConfig } from "@angular/core";
import { provideAnimations } from "@angular/platform-browser/animations";
import {
provideRouter,
withEnabledBlockingInitialNavigation,
} from "@angular/router";
import { appRoutes } from "./app.routes";
import { AuthInterceptor } from "./interceptors/fun-auth.interceptor";
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(appRoutes, withEnabledBlockingInitialNavigation()),
provideAnimations(),
provideHttpClient(withInterceptors([AuthInterceptor])),
],
};
Note
appConfig is used in main.ts
import { bootstrapApplication } from "@angular/platform-browser";
import { appConfig } from "./app/app.config";
import { AppComponent } from "./app/app.component";
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);