Skip to main content

basic_http_interceptor 0.2.1 copy "basic_http_interceptor: ^0.2.1" to clipboard
basic_http_interceptor: ^0.2.1 copied to clipboard

Pluggable HTTP interceptors for logging, headers, timeouts, hooks, and proxies, plus dynamic routing, RFC 7234 URL file caching, and LRU disk quota utilities.

basic_http_interceptor #

pub package License: MIT

A lightweight, pluggable, and batteries-included HTTP interceptor toolkit for Dart and Flutter applications.


Why basic_http_interceptor? #

  • 🧩 Modular Interceptors: Mix and match standalone interceptors for logging, headers, socket-level timeouts, and functional hooks β€” Interceptors at a Glance
  • ⚑ Zero-Boilerplate Client & Factory: Set up an InterceptedClient with interceptor chains, auth header normalization, and Multi-Protocol Proxies (HTTP, HTTPS, SOCKS5 across native platforms with Web fallback) in just a few lines β€” Quick Start Β· Reusable Client Factory
  • πŸ”€ Dynamic Request Routing: Route normal API calls through interceptors while bypassing them for SSE, AI streaming, or large uploads via MethodSwitchingClient β€” Dynamic Request Routing
  • πŸ’Ύ URL File Cache & Disk Quota: Decoupled, RFC 7234-compliant UrlFileCache and LRU DirectoryQuotaManager utilities that work independently or pair seamlessly with interceptedClient β€” Standalone Utilities
  • πŸ“¦ Clean Sub-Libraries: Dedicated entrypoints (http.dart, http_interceptor.dart, io_client.dart, testing.dart) keep the root namespace clean while providing raw HTTP primitives, interceptor contracts, native IO clients, and unit testing mocks without extra dependencies β€” Dedicated Sub-Libraries

Interceptors at a Glance #

Interceptor Description Key Features
InterceptorTimeout Physical connection timeout Backed by Abortable; cuts underlying TCP/socket connections, logs warnings, and triggers callbacks.
InterceptorLogger High-performance logger Single-record buffering to minimize disk I/O, protects streamed/binary bodies, supports X-Debug-Body.
InterceptorHeader Request header injector Injects default headers (JWT Bearer tokens, API keys, content types).
InterceptorHook Functional middleware Transforms requests and responses using simple closures without creating custom classes.

Getting Started #

Add the package to your pubspec.yaml:

dart pub add basic_http_interceptor

Or for Flutter projects:

flutter pub add basic_http_interceptor

Quick Start #

Easily configure and build an intercepted HTTP client:

import 'package:basic_http_interceptor/basic_http_interceptor.dart';
import 'package:logging/logging.dart';

void main() async {
  final logger = Logger('HTTP');

  final client = interceptedClient(
    interceptors: [
      // 1. Inject default headers
      InterceptorHeader(requestHeader: {
        'Authorization': 'Bearer YOUR_JWT_TOKEN',
        'Accept': 'application/json',
      }),
      // 2. Abort connection on 60s timeout
      InterceptorTimeout(
        Duration(seconds: 60),
        logger: logger,
      ),
      // 3. Log request & response
      InterceptorLogger(logger, true),
    ],
    proxy: {
      'https_proxy': 'https://127.0.0.1:7890/',
      'http_proxy': 'http://127.0.0.1:7890/',
      'all_proxy': 'socks5://127.0.0.1:7891/',
      'no_proxy': 'localhost,127.0.0.1',
    },
  );

  final url = buildUrlString(
    'https://api.example.com/data',
    {'query': 'dart'},
  );

  final response = await client.get(Uri.parse(url));
  print('Status: ${response.statusCode}');
}

Reusable Client Factory #

proxyClient is a versatile and extensible convenience factory for applications that want a standard interceptor pipeline while retaining full control over application-level configuration.

All parameters are optional, allowing you to provide only what you need (e.g., custom interceptors, request headers, timeouts, or proxy settings) as needed for your use case. Authorization values without an explicit scheme are automatically recognized as JWT Bearer tokens or Base64 Basic credentials.

final client = proxyClient(
  interceptors: customInterceptors, // Optional: custom interceptors
  headers: {'Authorization': token}, // Optional: default headers
  timeout: loadTimeoutFromApplicationSettings(), // Optional: timeout duration
  proxy: loadProxyFromApplicationSettings(), // Optional: proxy configurations
  logger: logger, // Optional: logger instance
);

The package does not read UI state or application persistence directly. A host application can provide separate resolver methods for values manually entered by users, stored in preferences, or discovered from the system environment, then pass their results to proxyClient. The helper methods normalizeAuthorizationHeaders, inferAuthorizationHeaderValue, isJwt, and isBase64Credentials are also available independently when an application only needs header or token processing.


Modular Recipes #

1. Connection Timeout & Hard Socket Termination (InterceptorTimeout) #

Unlike standard Future.timeout which only stops waiting in Dart while leaving the network socket open in the background, InterceptorTimeout leverages Dart's Abortable mechanism to physically terminate the underlying socket/TCP connection.

final client = interceptedClient(
  interceptors: [
    InterceptorTimeout(
      Duration(seconds: 60),
      logger: logger, // Automatically writes a warning when timed out
      onTimeout: (request) {
        print('Aborted timed out request: ${request.method} ${request.url}');
      },
    ),
  ],
);

2. High-Performance Logging (InterceptorLogger) #

InterceptorLogger formats and logs requests and responses with production-ready safeguards:

  • I/O Optimization: Buffers multi-line metadata into single log records to avoid excessive file write operations.
  • Stream Protection: Skips logging or limits buffer size on compressed (gzip, br, zstd) and binary/streamed responses (e.g., SSE, video/audio) to avoid blocking memory.
  • Selective Body Logging: Set logBody = false globally and pass X-Debug-Body: true in specific request headers to debug individual endpoints.
final client = interceptedClient(
  interceptors: [
    InterceptorLogger(
      logger,
      false, // logBody: false by default
      2 * 1024 * 1024, // logBodyMax: maximum 2MB buffer for stream inspection
    ),
  ],
);

3. Header Injection (InterceptorHeader) #

Attach global headers such as authentication tokens, custom user-agents, or tracking IDs:

final client = interceptedClient(
  interceptors: [
    InterceptorHeader(requestHeader: {
      'Authorization': 'Bearer $jwtToken',
      'X-App-Version': '1.0.0',
    }),
  ],
);

4. Functional Request & Response Hooks (InterceptorHook) #

Inspect or transform requests/responses on the fly without subclassing:

final client = interceptedClient(
  interceptors: [
    InterceptorHook(
      requestHook: (request) {
        // Dynamically append query parameters or headers
        final updatedUrl = request.url.addParameters({
          'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
        });
        return request.copyWith(url: updatedUrl);
      },
      responseHook: (response) {
        // Inspect or transform response data
        return response;
      },
    ),
  ],
);

5. Multi-Protocol Proxies #

Easily route traffic through HTTP, HTTPS, or SOCKS5 proxies:

final client = interceptedClient(
  interceptors: [...],
  proxy: {
    'http_proxy': 'http://127.0.0.1:7890/',
    'https_proxy': 'https://127.0.0.1:7890/',
    'all_proxy': 'socks5://127.0.0.1:7891/',
    'no_proxy': 'localhost,127.0.0.1,::1',
  },
);

Advanced: Dynamic Request Routing (MethodSwitchingClient) #

MethodSwitchingClient provides a centralized routing point to dispatch requests between an interceptor client and a default/raw HTTP client dynamically.

This is particularly useful when:

  • Normal API requests should go through logging and header interceptors.
  • AI Streaming requests (OpenAI, Anthropic, Gemini), SSE, or large file uploads need to bypass interceptors for performance.
import 'package:basic_http_interceptor/basic_http_interceptor.dart';
import 'package:basic_http_interceptor/http.dart';
import 'package:logging/logging.dart';

final logger = Logger('Network');

// 1. Client with full interceptor suite
final httpClient = interceptedClient(
  interceptors: [
    InterceptorLogger(logger, true),
    InterceptorHeader(requestHeader: {'Authorization': 'Bearer $token'}),
  ],
);

// 2. Plain default client (platform-agnostic: IOClient on native, BrowserClient on Web)
final defaultClient = Client();

// 3. Dynamic switching client with custom routing
final client = MethodSwitchingClient(
  httpClient,
  defaultClient,
  useDefaultClientWhen: (request) {
    // Bypass interceptors for streaming endpoints or file uploads
    final isStreaming = request.url.path.contains('/stream') ||
        request.headers['accept'] == 'text/event-stream';
    return isStreaming || request is StreamedRequest;
  },
);

Standalone Utilities: File Cache and Disk Quota #

UrlFileCache and DirectoryQuotaManager are decoupled from HTTP interceptors and can be used completely standalone. When needed, UrlFileCache can also accept an interceptedClient or proxyClient to inherit proxies, auth headers, and logging.

1. Quick Start (UrlFileCache) #

Cache remote files locally with built-in HTTP 304 validation (ETag / Last-Modified), in-flight request deduplication, atomic writes, and offline fallback:

import 'dart:io';
import 'package:basic_http_interceptor/basic_http_interceptor.dart';

void main() async {
  final cache = UrlFileCache(Directory('/path/to/cache'));

  // Downloads once, then revalidates via HTTP 304 or falls back offline
  final file = await cache.getFile('https://example.com/readme.md');
  if (file != null) {
    print(await file.readAsString());
  }

  cache.close();
}

2. Common Patterns: TTL, Sync Lookup, and Text #

  • Skip network when fresh (ttl) / bypass cache (forceRefresh):
    final fresh = await cache.getFile(url, ttl: const Duration(minutes: 15));
    final latest = await cache.getFile(url, forceRefresh: true);
    final text = await cache.getText(Uri.parse(url), ttl: const Duration(hours: 1));
    
    (Helper loadUriText is also available for one-off file:// or http(s):// text reads.)
  • Synchronous disk-only check (getCachedFile): Useful for instant first-frame UI rendering or strict offline checks without triggering network I/O:
    final cached = cache.getCachedFile(url); // Returns File? synchronously, never hits network
    

3. Pairing with DirectoryQuotaManager and Interceptors #

DirectoryQuotaManager enforces an LRU byte ceiling on any directory (such as logs, temp media, or a UrlFileCache folder with .meta.json sidecars):

final quota = DirectoryQuotaManager(
  cache.cacheDir,
  maxBytes: 50 * 1024 * 1024, // 50 MB limit
  companionResolver: (file) => [File('${file.path}.meta.json')],
);

await quota.trim(); // Evicts oldest entries + sidecars when over budget

To route UrlFileCache downloads through your interceptor chain or proxy, pass a custom client:

final cache = UrlFileCache(
  Directory('/path/to/cache'),
  client: proxyClient(proxy: {'https_proxy': 'http://127.0.0.1:7890/'}),
);

Explore Further: Both utilities ship with detailed inline documentation and advanced options (trimRatio, LruSortStrategy, customTimestampResolver, minAgeForEviction, etc.) in lib/utils/url_file_cache.dart and lib/utils/directory_quota_manager.dart.


Dedicated Sub-Libraries #

To prevent global namespace pollution (such as package:http's top-level functions get(), post() or common class names like Response/Request conflicting with Flutter widgets or local methods), basic_http_interceptor encapsulates underlying packages into dedicated sub-libraries:

1. package:basic_http_interceptor/http.dart #

Re-exports package:http. Downstream applications can access standard HTTP classes without declaring a direct dependency in pubspec.yaml:

import 'package:basic_http_interceptor/http.dart' as http;

Future<void> fetch() async {
  final http.Response res = await http.get(Uri.parse('https://api.example.com'));
}

2. package:basic_http_interceptor/http_interceptor.dart #

Re-exports package:http_interceptor for advanced custom interceptor contracts (InterceptorContract, RetryPolicy, etc.):

import 'package:basic_http_interceptor/http_interceptor.dart';

3. package:basic_http_interceptor/io_client.dart #

Re-exports package:http/io_client.dart (IOClient) and provides proxyIoClient for raw, non-intercepted native IO clients. Keeps dart:io platform code isolated so Flutter Web / WASM projects remain 100% compatible.

import 'package:basic_http_interceptor/io_client.dart';

// Create a raw IOClient preconfigured with proxies (no interceptor overhead)
final rawClient = proxyIoClient(
  proxy: {
    'https_proxy': 'https://127.0.0.1:7890/',
    'http_proxy': 'http://127.0.0.1:7890/',
    'all_proxy': 'socks5://127.0.0.1:7891/',
    'no_proxy': 'localhost,127.0.0.1',
  },
  // Optional: bypass self-signed certificates in local development
  badCertificateCallback: (cert, host, port) => true,
);

4. package:basic_http_interceptor/testing.dart #

Re-exports package:http/testing.dart (MockClient) for unit testing. Enables downstream projects to mock HTTP requests directly in their test suites without declaring an extra dependency on package:http in pubspec.yaml:

import 'dart:convert';
import 'package:basic_http_interceptor/basic_http_interceptor.dart';
import 'package:basic_http_interceptor/testing.dart';
import 'package:test/test.dart';

void main() {
  test('mocks HTTP request with interceptor', () async {
    final mockClient = MockClient((request) async {
      return Response(jsonEncode({'status': 'ok'}), 200);
    });

    final client = InterceptedClient.build(
      client: mockClient,
      interceptors: [
        InterceptorHeader(requestHeader: {'Accept': 'application/json'}),
      ],
    );

    final response = await client.get(Uri.parse('https://example.com'));
    expect(response.statusCode, 200);
  });
}

License #

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ’– Support the Project #

If you find this tool helpful and would like to see it continue to improve and evolve, please consider showing your support.

  • ⭐ Star the Repo: It helps more developers discover the project and is greatly appreciated.
  • β˜• Support the Developer (Global): Any contribution, however small, goes a long way toward supporting ongoing maintenance. You can support via GitHub Sponsors or Buy Me a Coffee.
  • 🐼 Support via Ifdian (Mainland China): Users in China can also show support via Ifdian.

Thank you for your supportβ€”it keeps this project actively maintained and helps bring improvements to more developers faster.

0
likes
150
points
1.18k
downloads

Documentation

API reference

Publisher

verified publisheriche2.com

Weekly Downloads

Pluggable HTTP interceptors for logging, headers, timeouts, hooks, and proxies, plus dynamic routing, RFC 7234 URL file caching, and LRU disk quota utilities.

Repository (GitHub)
View/report issues

Topics

#http #network #interceptor #cache #proxy

Funding

Consider supporting this project:

github.com
buymeacoffee.com

License

MIT (license)

Dependencies

http, http_interceptor, logging

More

Packages that depend on basic_http_interceptor