Package selection guidance compiled from public package information, community data, and project usage.
http_interceptor is a lightweight Flutter plugin that enables developers to intercept HTTP requests and responses, allowing for modifications such as adding headers, logging, or handling errors globally. It simplifies common tasks like authentication token injection, request/response logging, and error handling across an app. The package integrates seamlessly with the built-in http client and supports all major platforms including Android, iOS, Web, macOS, Windows, and Linux. Designed for simplicity and flexibility, it provides a clean API for middleware-style interception without requiring complex setup.
Use cases
Global request header modification
Authentication token injection
Request/response logging
Error handling across the app
API request monitoring
Debugging HTTP traffic
Key features
Simple middleware-style interception
Supports both requests and responses
Cross-platform compatibility
Easy integration with http client
Minimal boilerplate
Extensible interceptor chains
Suitable for
Apps needing centralized HTTP logic
Developers implementing auth flows
Teams requiring debug-friendly HTTP tracking
Projects with frequent API interactions
Those seeking lightweight HTTP utilities
Considerations
Requires understanding of HTTP lifecycle
May impact performance if overused
Interceptors run synchronously by default
Limited built-in error recovery
Not designed for complex routing or caching
Original README
Original README snapshot from the linked source repository. Visit the repository for the latest content.
http_interceptor
This is a plugin that lets you intercept the different requests and responses from Dart's http package. You can use to add headers, modify query params, or print a log of the response.
Now that you actually have your interceptor implemented, now you need to use it. There are two general ways in which you can use them: by using the InterceptedHttp to do separate connections for different requests or using a InterceptedClient for keeping a connection alive while making the different http calls. The ideal place to use them is in the service/provider class or the repository class (if you are not using services or providers); if you don't know about the repository pattern you can just google it and you'll know what I'm talking about. 😉
Using interceptors with Client
Normally, this approach is taken because of its ability to be tested and mocked.
Here is an example with a repository using the InterceptedClient class.
The ResponseBodyDecoding extension adds a few lightweight helpers on Response for common JSON use cases:
final response = await client.get(
'$baseUrl/weather'.toUri(),
params: {'id': '$id'},
);
// Dynamically-typed JSON value (Map/List/primitive or null on empty body).finalObject? json = response.jsonBody;
// JSON object as a map (throws if body is empty or not a JSON object).finalMap<String, dynamic> data = response.jsonMap;
// JSON array as a list (throws if body is empty or not a JSON array).finalList<dynamic> items = response.jsonList;
Decoding responses into models
The ResponseBodyDecoding extension provides helpers to turn JSON responses into strongly-typed models with minimal boilerplate.
Sometimes you need to retry a request due to different circumstances, an expired token is a really good example. Here's how you could potentially implement an expired token retry policy with http_interceptor.
classExpiredTokenRetryPolicyextendsRetryPolicy{
@overrideintget maxRetryAttempts => 2;
@overrideboolshouldAttemptRetryOnException(Exception reason, BaseRequest request) {
// Log the exception for debuggingprint('Request failed: ${reason.toString()}');
print('Request URL: ${request.url}');
// Retry on network exceptions, but not on client errorsreturn reason isSocketException || reason isTimeoutException;
}
@overrideFuture<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
if (response.statusCode == 401) {
// Perform your token refresh here.print('Token expired, refreshing...');
returntrue;
}
returnfalse;
}
}
You can also set the maximum amount of retry attempts with maxRetryAttempts property or override the shouldAttemptRetryOnException if you want to retry the request after it failed with an exception.
RetryPolicy Interface
The RetryPolicy abstract class provides the following methods that you can override:
shouldAttemptRetryOnException(Exception reason, BaseRequest request): Called when an exception occurs during the request. Return true to retry, false to fail immediately.
shouldAttemptRetryOnResponse(BaseResponse response): Called after receiving a response. Return true to retry, false to accept the response.
maxRetryAttempts: The maximum number of retry attempts (default: 1).
delayRetryAttemptOnException({required int retryAttempt}): Delay before retrying after an exception (default: no delay).
delayRetryAttemptOnResponse({required int retryAttempt}): Delay before retrying after a response (default: no delay).
Using Retry Policies
To use a retry policy, pass it to the InterceptedClient or InterceptedHttp:
final client = InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
retryPolicy: ExpiredTokenRetryPolicy(),
);
Sometimes it is helpful to have a cool-down phase between multiple requests. This delay could for example also differ between the first and the second retry attempt as shown in the following example.
You can achieve support for self-signed certificates by providing InterceptedHttp or InterceptedClient with the client parameter when using the build method on either of those, it should look something like this:
Note: It is important to know that since both HttpClient and IOClient are part of dart:io package, this will not be a feature that you can perform on Flutter Web (due to BrowserClient and browser limitations).
We migrated our roadmap to better suit the needs for development since we use ClickUp as our task management tool.
Troubleshooting
Open an issue and tell me, I will be happy to help you out as soon as I can.
Contributions
Contributions are always welcomed and encouraged, we will always give you credit for your work on this section. If you are interested in maintaining the project on a regular basis drop me a line at [me@codingale.dev](mailto:me@codingale.dev).
Contributors
Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!