Enterprise-grade, resilient, and intelligent HTTP Interceptor for modern Angular applications.
πΊπΈ English β’ π§π· PortuguΓͺs
Features β’ Why Use? β’ Installation β’ Quick Start β’ Advanced Examples β’ Architecture β’ Contributing β’ License
In enterprise applications, the HTTP layer needs to do much more than simply relay API requests. Flaky networks, duplicate concurrent requests, cascading microservice outages, and slow connections severely degrade the user experience.
ngx-smart-interceptor centralizes resilience, performance, and observability into a single functional interceptor, without cluttering your codebase with repetitive boilerplate infrastructure logic.
| Feature | Description |
|---|---|
| π‘οΈ Circuit Breaker | Temporarily trips and prevents requests to failing endpoints, protecting your server and network from cascade failures. |
| β‘ GET Deduplication | Shares a single in-flight request among concurrent components querying the same endpoint at the same time. |
| π Stale-While-Revalidate (SWR) | Serves cached data immediately while revalidating and refreshing the cache in the background. |
| πΆ Adaptive Network Loading | Detects slow network conditions (2G/3G/Data-Saver) and injects adaptive headers for backend payload compression. |
| β³ Offline Mutation Queue | Queues state-mutating requests (POST, PUT, PATCH, DELETE) during network disconnects and auto-replays on reconnect. |
| π Auth Refresh (Pause & Resume) | Catches 401 Unauthorized errors, pauses concurrent requests, refreshes tokens, and transparently replays queued calls. |
| π Performance Profiler | Measures HTTP round-trip latency and warns/logs requests exceeding configurable thresholds. |
| π Correlation IDs | Generates and attaches traceable UUID headers (X-Correlation-ID) for distributed end-to-end tracing. |
| π Route Cancellation | Automatically cancels pending HTTP requests on route transitions to prevent orphaned background tasks. |
| πͺ Global Error Hooks | Inversion-of-control hooks for centralized error handling and per-HTTP-status custom triggers (toasts, redirects). |
| π§ͺ Integrated Mock Mode | Simulate client-side mocked API responses with configurable artificial delays for rapid local development. |
| π Context Bypass | Selectively bypass the interceptor for specific requests using Angular's native HttpContext. |
npm install ngx-smart-interceptorIn your app.config.ts (or main.ts):
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSmartInterceptor, smartInterceptor } from 'ngx-smart-interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([smartInterceptor])),
provideSmartInterceptor({
enableDeduplication: true,
generateCorrelationIds: true,
enableAdaptiveLoading: true,
enableOfflineQueue: true,
cancelOnRouteChange: true,
enableStaleWhileRevalidate: true,
circuitBreaker: {
failureThreshold: 3,
resetTimeoutMs: 10000,
},
retry: {
maxAttempts: 3,
backoffBaseMs: 1000,
allowedStatusCodes: [503, 504, 0],
},
performance: {
slowRequestThresholdMs: 2000,
logToConsole: true,
},
hooks: {
onGlobalError: (err) => console.error('Global error caught:', err.userFriendlyMessage),
statusActions: {
401: () => console.warn('Session expired. Redirecting to login...'),
},
},
}),
],
};import { inject } from '@angular/core';
import { provideSmartInterceptor } from 'ngx-smart-interceptor';
import { AuthService } from './auth.service';
export const smartInterceptorProvider = provideSmartInterceptor({
authRefresh: {
unauthorizedStatusCode: 401,
refreshTokenCallback: () => {
const auth = inject(AuthService);
return auth.refreshToken(); // Must return Observable<boolean>
},
},
});import { HttpClient, HttpContext } from '@angular/common/http';
import { inject } from '@angular/core';
import { BYPASS_SMART_INTERCEPTOR } from 'ngx-smart-interceptor';
export class DataService {
private http = inject(HttpClient);
getRawData() {
return this.http.get('/api/raw-stream', {
context: new HttpContext().set(BYPASS_SMART_INTERCEPTOR, true),
});
}
}ngx-smart-interceptor is built following the Single Responsibility Principle (SRP) and Clean Architecture:
smartInterceptor: Acts strictly as the RxJS Pipeline Orchestrator.CircuitBreakerHandler: Manages circuit breaker states per URL in memory.DeduplicationHandler: Tracks and shares active in-flight GET observables.AuthRefreshHandler: Coordinates request queuing, token renewal, and transparent replay.OfflineQueueHandler: Buffers mutating requests in memory and synchronizes with browser online events.SwrCacheHandler: Manages ephemeral memory cache and handles route navigation cancellations via NavigationStart.Contributions are welcome! Please check out our Contributing Guide and Code of Conduct.
Please review our Security Policy to report vulnerabilities responsibly.
Distributed under the MIT License. See LICENSE for more details.