Skip to content
tezvyn:

dio Interceptors: Middleware for Network Requests

Source: pub.devHardHow cards are made

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.

Interview question

What is a crucial action required within an Interceptor's method (e.g., onRequest) to ensure the network request processing continues?

  • a.Calling handler.next() or handler.reject() to pass control to the next stage.Correct
  • b.Storing the modified request options in a global state manager.
  • c.Returning a Future<void> after completing the logic.
  • d.Ensuring the interceptor is registered before any Dio instance is created.
Why?

The card explicitly states that calling handler.next() or handler.reject() is crucial to prevent the request from hanging, allowing it to proceed through the pipeline. Failing to do so will cause the request to hang indefinitely.

Just read this? Test yourself on what you have been reading.

Read the original → pub.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on flutter — each one lists the topics its interview covers.

See open roles