HTTP Interceptor
Package: @nauth-toolkit/client-angular
HTTP interceptor that handles authentication headers, CSRF tokens, and automatic token refresh.
Setup
- Standalone (Angular 17+)
- NgModule
// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from '@nauth-toolkit/client-angular';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
],
};
// app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptorClass } from '@nauth-toolkit/client-angular';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorClass, multi: true },
],
})
export class AppModule {}
Behavior
By Token Delivery Mode
| Mode | Headers | Credentials | CSRF |
|---|---|---|---|
cookies | None | withCredentials: true | Auto-attached |
json | Authorization: Bearer <token> | false | Not needed |
CSRF Token Handling
For cookies mode, the interceptor automatically:
- Reads the CSRF token from cookie (default:
nauth_csrf_token) - Attaches it to mutating requests (
POST,PUT,PATCH,DELETE) - Uses configured header name (default:
x-csrf-token)
// Configure CSRF in client config
{
provide: NAUTH_CLIENT_CONFIG,
useValue: {
baseUrl: 'https://api.example.com/auth',
tokenDelivery: 'cookies',
csrf: {
cookieName: 'nauth_csrf_token', // Default
headerName: 'x-csrf-token', // Default
},
onSessionExpired: () => {},
},
}
Automatic Token Refresh
On 401 response:
- Interceptor queues the failed request
- Calls
refreshTokens()on the client - Retries the original request with new tokens
- If refresh fails, calls
onSessionExpiredcallback
Request → 401 → Refresh Tokens → Retry Request → Response
↓ (fail)
onSessionExpired()
Concurrency Handling
Multiple simultaneous 401s trigger only ONE refresh:
Request A → 401 ─┐
Request B → 401 ──┼→ Single Refresh → Retry All
Request C → 401 ─┘
Exports
| Export | Type | Description |
|---|---|---|
authInterceptor | HttpInterceptorFn | Functional interceptor (Angular 17+) |
AuthInterceptorClass | class | Class-based interceptor (NgModule) |
Customization
Exclude Routes from Interception
The interceptor only adds auth to requests whose origin matches your baseUrl, and whose path sits at or below the baseUrl path. External APIs are not affected, and neither is a look-alike host such as https://api.example.com.attacker.test — the comparison parses both URLs rather than testing for a substring. A URL that cannot be parsed is never treated as your API.
For additional control, create a wrapper interceptor:
export const customAuthInterceptor: HttpInterceptorFn = (req, next) => {
// Skip auth for specific paths
if (req.url.includes('/public/')) {
return next(req);
}
return authInterceptor(req, next);
};
Custom Error Handling
Handle 401s differently:
export const customAuthInterceptor: HttpInterceptorFn = (req, next) => {
return authInterceptor(req, next).pipe(
catchError((error) => {
if (error.status === 401) {
// Custom handling
console.log('Authentication required');
}
return throwError(() => error);
}),
);
};
Related APIs
- AuthService - Main service
- Guards - Route protection
- Configuration - Config options