npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ngx-smart-interceptor

v1.2.1

Published

Smart, resilient, enterprise-grade HTTP Interceptor for Angular applications featuring Circuit Breaker, Deduplication, SWR, Offline Queue, Adaptive Loading, Profiler and Token Refresh.

Readme

⚡ ngx-smart-interceptor

NPM Version License: MIT CI Coverage Angular

Interceptor HTTP inteligente, resiliente e de nível corporativo para aplicações Angular modernas.


🌟 Por que usar o ngx-smart-interceptor?

Em aplicações corporativas, a camada HTTP precisa de muito mais do que apenas repassar chamadas. Redes instáveis, requisições duplicadas, travamentos por falhas em cascata de microsserviços e lentidões degradam a experiência do usuário.

O ngx-smart-interceptor centraliza resiliência, performance e observabilidade em um único interceptor funcional, sem sobrecarregar sua base de código com lógica repetitiva de infraestrutura.


🚀 Recursos Principais

  • 🛡️ Circuit Breaker: Bloqueia temporariamente chamadas a endpoints com falhas repetidas.
  • Deduplicação de GETs: Compartilha requisições em voo entre múltiplos chamadores concorrentes.
  • 🔄 Stale-While-Revalidate (SWR): Entrega dados em cache instantaneamente com revalidação em segundo plano.
  • 📶 Adaptive Network Loading: Detecta redes lentas (2G/3G) e adiciona headers adaptativos.
  • Fila Offline: Enfileira requisições mutantes na queda da conexão e reexecuta no retorno online.
  • 🔑 Auth Refresh (Pause & Resume): Pausa chamadas concorrentes ao receber 401, atualiza o token e retoma o fluxo.
  • 📈 Performance Profiler: Notifica e loga requisições com tempo de resposta acima do limite.
  • 🆔 Correlation IDs: Adiciona identificadores rastreáveis (X-Correlation-ID) automaticamente.
  • 🛑 Cancelamento por Rota: Cancela streams pendentes em transições de navegação.
  • 🪝 Global Error Hooks: Tratamento unificado de erros com normalização amigável.
  • 🧪 Modo Mock: Simula respostas mockadas com atraso configurável no cliente.
  • 🔓 Context Bypass: Permite contornar o interceptor via HttpContext.

📦 Instalação

npm install ngx-smart-interceptor

⚙️ Configuração Rápida

No seu app.config.ts (ou 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('Erro global:', err.userFriendlyMessage),
        statusActions: {
          401: () => console.warn('Sessão expirada. Redirecionando para login...'),
        },
      },
    }),
  ],
};

🏛️ Arquitetura Modular (Handlers)

A biblioteca aplica Clean Architecture e o Princípio da Responsabilidade Única (SRP):

  • smartInterceptor: Orquestrador central do fluxo RxJS.
  • CircuitBreakerHandler: Monitora taxas de falha e controla a abertura/fechamento do circuito.
  • DeduplicationHandler: Rastreia chamadas GET em voo evitando processamento concorrente redundante.
  • AuthRefreshHandler: Enfileira e sincroniza a renovação de tokens com RxJS BehaviorSubject.
  • OfflineQueueHandler: Mantém as requisições em memória e escuta o evento online do navegador.
  • SwrCacheHandler: Gerencia o cache efêmero e o cancelamento de streams via NavigationStart.

📄 Licença

Distribuído sob a licença MIT.