Every Network Request Must Obey the Same Laws#
In a production mobile app processing thousands of daily transactions across bill payments, phone top-ups, trains, buses, and maritime passenger ships, network communication is your most vulnerable perimeter. If every feature module constructs its own HTTP requests independently, chaotic entropy is inevitable:
One developer forgets to attach the bearer authorization token; another omits device language headers; a third catches network timeouts with an empty try-catch block; and an obscure 502 Bad Gateway response blows through unhandled, causing the entire UI widget tree to crash into a blank white screen.
When our team audited Holigo's legacy codebase, we discovered duplicate network configurations, inconsistent retry rules, and plain-text storage of user authentication tokens. As part of our clean architecture migration, we established a strict architectural rule:
No feature is permitted to speak directly to raw HTTP libraries or write sensitive tokens into unsecured storage. Every single byte entering or leaving the application must flow through a centralized, hardened Data Layer in core.
In Part 5, I will walk you through how we designed our centralized Dio client, standardized failure handling with functional Either boundaries, and strictly segregated ephemeral cache from hardware-backed credential vaults.
Feature Service
Data SourceFeature service calls its endpoint without worrying about base URLs, auth tokens, or headers.
Core Dio Interceptor
Security & HeadersAutomatically injects Bearer Token, App Version, active Locale, Timeout, and Debug Logger.
Network Transport
HTTPS TLSSecure transport to backend cluster with TLS verification and deterministic timeouts.
Functional Mapping
Either<Exception, T>Network errors mapped to structured AppException; successful JSON parsed to typed Models.
A single centralized network wrapper guarantees uniform security standards, token injections, and logging across all modules.
One Unified Pipeline on Top of Dio#
Instead of allowing feature services to instantiate HTTP clients, our core layer provides a single, hardened DioClient wrapper registered as a singleton in get_it. Every outgoing request automatically passes through an ordered sequence of interceptors:
- Deterministic Base URLs and Timeouts: Endpoint base URLs are bound strictly to the active environment configuration (
developorproduction), enforcing aggressive connection and receive timeouts to prevent thread hanging on flaky 3G networks. - Context-Aware Header Injection: Interceptors automatically inject the user's active session JWT
Bearertoken if authenticated, the active app locale (idoren), the semantic version of the installed app binary, and standardized JSON content headers. - Structured Network Logging: In debug and staging builds, full curl commands and JSON payloads are cleanly formatted for developer inspection, but automatically stripped from production builds to safeguard sensitive customer data.
- Resilient Token Refresh Interceptors: When a request encounters a 401 Unauthorized status, the interceptor pauses outgoing traffic, triggers a background refresh token exchange, updates the secure vault, and replays the original failed request without the user ever noticing.
Because these behaviors execute inside the core pipeline, individual feature developers can focus 100% of their bandwidth on their business domain: defining endpoints, query parameters, and model deserialization.
Storage Architecture: Fast Ephemeral Cache vs Encrypted Vaults#
A major security flaw in many mobile applications is storing authentication credentials, user identifiers, and PIN codes in plain-text key-value files. If an Android device is rooted or an iOS backup is inspected, unencrypted tokens are easy to extract.
To balance banking-grade security with maximum UI rendering performance, Holigo enforces a strict Dual-Storage Architecture:
- 01Characteristics: Unencrypted high-speed key-value cache ideal for app preferences and UI states.
- 02Stored Data: Theme mode, language code, onboarding completion flag, and recent search route queries.
- 03Exposure Impact: Zero financial or security threat to user privacy if device is compromised.
- 01Characteristics: Hardware-backed AES encryption powered by iOS Keychain & Android KeyStore.
- 02Stored Data: JWT Access/Refresh tokens, user PIN hash, biometric keys, and session identifiers.
- 03Exposure Impact: Severe risk of account takeover and financial fraud; non-negotiable encryption.
Segregating storage by sensitivity delivers lightning UI responsiveness for preferences while guarding user credentials in hardware vaults.
1. shared_preferences (High-Speed Ephemeral Cache)
Reserved exclusively for non-sensitive UI configuration data:
- Active dark/light theme mode preference
- Selected language code (
id/en) - Onboarding walkthrough flags
- Recent search queries for harbour routes and train stations
Because this data carries zero financial or privacy risk if exposed, storing it in unencrypted key-value pairs gives the UI blazing-fast synchronous reads without cryptographic overhead.
2. flutter_secure_storage (Hardware-Backed Encrypted Vault)
Mandatory for all sensitive credentials:
- JWT Access and Refresh tokens
- User PIN verification hashes
- Biometric authentication flags
- Encrypted device fingerprints
Under the hood, this storage delegates to the iOS Keychain and Android KeyStore, using hardware-backed AES-256 encryption. Tokens never touch disk in plain text.
Fault-Tolerant Resilience: Functional Either vs Try-Catch Sprawl#
In our legacy app, failure handling was a messy guessing game. Developers scattered try-catch blocks across screens, controllers, and services. If an unexpected SocketException or parsing error slipped past an inner block, it leaked directly into UI widgets, presenting users with cryptic error stack traces or frozen buttons.
To permanently eradicate leaky exceptions, we instituted a functional programming result pattern across all repository contracts using Either<AppException, T>:
All repository contracts return an Either type: Left carries structured AppException, Right holds successful data payload.
- ✕Exceptions Leak to UI: Raw socket or HTTP timeouts burst into UI widgets, triggering white crash screens.
- ✕Repetitive Catch Blocks: Every widget duplicates error-parsing logic with inconsistent error copies.
- ✓Trapped in Data Layer: All HTTP faults, parsing flaws, and timeouts transformed into clean AppException.
- ✓Clean Enum-Based State: BLoC state tracks request lifecycle via clean enums without scattered booleans.
The functional result pattern transforms unexpected exceptions into predictable values that developers must consciously handle.
- The Data Layer as a Shield: The Data layer catches all low-level Dio errors, DNS failures, connection drops, and JSON parsing flaws. It transforms them into structured
AppExceptionsubclasses (NetworkException,ServerException,AuthException,ValidationException). - Deterministic Return Contracts: Repositories never throw exceptions. They return an
Eitherinstance: the Left side carries the typedAppException, while the Right side carries the successfully parsed domain data payload. - Clean Enum States in BLoC: The BLoC folds the
Eitherresult into a deterministic state update. By tracking operation progress through a cleanRequestStatusenum (initial,loading,success,failure), UI screens simply observe the status and render friendly user-facing banners without a single line of try-catch code.
The Real-World Price: Single Point of Risk and Pipeline Visibility#
While centralizing our data infrastructure eliminated hundreds of edge-case bugs, it introduced architectural trade-offs that require deliberate engineering discipline:
First, The Wrapper is a High-Impact Blast Radius: Because every feature shares the exact same Dio client and interceptor pipeline, a regression introduced in the core wrapper can simultaneously disrupt every service in the app. Modifying network interceptors requires exhaustive integration testing.
Second, Hidden Magic for Junior Developers: When headers, auth tokens, and refresh logic are applied automatically by interceptors, developers who are new to the codebase may not realize what happens to their outgoing requests. Comprehensive internal documentation is vital to ensure engineers understand what the core pipeline does on their behalf.
Third, The Overhead of Either Ceremony: Handling Either requires explicit pattern matching (fold(), map()) on every repository call. While this guarantees safety, it requires more lines of code than an optimistic shortcut. For our team, the guarantee of zero production crashes was well worth the extra typing.
What You Can Take from This Story#
If you are standardizing the data layer of your own mobile application, here are key practices to implement:
- Centralize Your Network Client Early: Build a single HTTP wrapper in your core layer to handle base URLs, token injection, localization headers, and timeouts consistently across all features.
- Segregate Local Storage by Sensitivity: Never store JWTs or credentials in unencrypted preferences. Use hardware-backed secure storage for sensitive data, and reserve fast preferences for UI settings.
- Adopt Functional Results Over Leaky Exceptions: Replace scattered try-catch blocks with
Either<AppException, T>. Intercept raw exceptions at the data boundary so your UI only handles clean, predictable states. - Automate Token Refresh in Interceptors: Shield your screens from expired session logic by handling silent token refreshes inside network interceptors.
Closing#
A resilient data layer is the invisible foundation that keeps a complex mobile application dependable. By channeling all network requests through a unified Dio pipeline, guarding user credentials behind encrypted vaults, and enforcing functional error boundaries, Holigo guarantees that network turbulence never compromises application stability.
In Part 6 of this series, we will examine our Ship (Pelni) Feature as an end-to-end case study: how later travel modules reused this exact blueprint, how dynamic backend-driven configuration powers holiday themes, and how we streamlined multilingual localization using modular ARB pipelines.
Thanks for reading :)
P.S. This series is written at the level of software design decisions and mobile system architecture, without disclosing proprietary code, internal endpoints, or company data. If you have questions about Dio interceptor design, functional error handling, or secure storage patterns, let's connect and discuss!