dio Interceptors: Middleware for Network Requests
dio Interceptors are middleware for network requests, letting you inspect and modify them before they're sent or after a response is received. Use them to globally add auth tokens, log activity, or handle token refreshes.
WHY IT EXISTS In any app with authentication or complex logging, you'll find yourself repeating code before and after every API call. Interceptors were created to solve this by providing a single, centralized place to handle logic that applies to many or all network requests, adhering to the DRY (Don't Repeat Yourself) principle.
THE MENTAL MODEL An Interceptor is like a toll booth on the highway of a network request. You can set up multiple booths (onRequest, onResponse, onError) that every request must pass through. At each booth, you can inspect the "vehicle" (the request/response), modify it (add a header), or even turn it around (reject it with an error). This creates a predictable, manageable pipeline for all network traffic.
HOW IT WORKS You create a custom class that extends Interceptor and add it to your Dio instance's interceptors list. Inside this class, you override one or more of its three main methods: onRequest(options, handler), onResponse(response, handler), and onError(error, handler). Within each method, you perform your logic. Crucially, you must then call a method on the handler object—like handler.next()—to allow the request to proceed to the next interceptor or be sent. If you don't, the request will hang indefinitely.
WHEN TO USE IT Use interceptors for any logic that needs to run on most or all of your API calls. Common use cases include: first, adding authentication tokens to request headers; second, logging request and response data for debugging; third, handling API errors globally, like redirecting to a login screen on a 401 Unauthorized status; and fourth, implementing automatic request retries or token refresh logic.
WHEN NOT TO USE IT Avoid using interceptors for logic that is highly specific to a single API call. If you only need to add a special header or handle a unique error for one endpoint, it's cleaner to handle that logic directly at the call site rather than adding conditional complexity to a global interceptor.
ONE CANONICAL EXAMPLE A classic use case is adding a bearer token to every request. You'd create an AuthInterceptor that overrides onRequest. Inside, it would read a token from secure storage and add it to the request's headers via options.headers['Authorization'] = 'Bearer $token'. Finally, it would call handler.next(options) to send the modified request on its way. This ensures every API call is authenticated without repeating code.
Read the original → pub.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.