⚑ ngx-smart-interceptor

NPM Version License: MIT CI Coverage Angular

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


🌟 Why ngx-smart-interceptor?

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.


πŸš€ Key Features

FeatureDescription
πŸ›‘οΈ Circuit BreakerTemporarily trips and prevents requests to failing endpoints, protecting your server and network from cascade failures.
⚑ GET DeduplicationShares 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 LoadingDetects slow network conditions (2G/3G/Data-Saver) and injects adaptive headers for backend payload compression.
⏳ Offline Mutation QueueQueues 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 ProfilerMeasures HTTP round-trip latency and warns/logs requests exceeding configurable thresholds.
πŸ†” Correlation IDsGenerates and attaches traceable UUID headers (X-Correlation-ID) for distributed end-to-end tracing.
πŸ›‘ Route CancellationAutomatically cancels pending HTTP requests on route transitions to prevent orphaned background tasks.
πŸͺ Global Error HooksInversion-of-control hooks for centralized error handling and per-HTTP-status custom triggers (toasts, redirects).
πŸ§ͺ Integrated Mock ModeSimulate client-side mocked API responses with configurable artificial delays for rapid local development.
πŸ”“ Context BypassSelectively bypass the interceptor for specific requests using Angular's native HttpContext.

πŸ“¦ Installation

Example :
npm install ngx-smart-interceptor

βš™οΈ Quick Start

In your app.config.ts (or main.ts):

Example :
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...'),
        },
      },
    }),
  ],
};

πŸ’‘ Advanced Examples

1. Token Refresh Queue (Pause & Resume)

Example :
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>
    },
  },
});

2. Selective Interception Bypass

Example :
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),
    });
  }
}

πŸ›οΈ Modular Architecture (Handlers)

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.

🀝 Contributing

Contributions are welcome! Please check out our Contributing Guide and Code of Conduct.


πŸ”’ Security

Please review our Security Policy to report vulnerabilities responsibly.


πŸ“„ License

Distributed under the MIT License. See LICENSE for more details.

results matching ""

    No results matching ""