HTTP

Dio

Attach tokens to requests and recover from 401 with a single shared refresh.
flutter pub add authyra_dio
final api = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
api.interceptors.add(
  AuthyraInterceptor(
    authyra: authyra,
    dio: api,
    // Never send your tokens to another host.
    shouldAttach: (request) => request.uri.host == 'api.example.com',
  ),
);

What it does

  1. Before each request, it asks authyra.accessToken() for a valid token. A token about to expire is refreshed first. The request records which session it was sent for.
  2. On a 401, it asks for a new token for that same session, passing the rejected token, and retries the request once. Concurrent 401s share one refresh: twenty failing requests cause one refresh call.
  3. When the refresh token is rejected, the session ends (the app sees AuthSignedOut, or the next account) and the original 401 is passed on.
  4. When the refresh fails for a transient reason and the token has expired, the request fails with a DioException whose error is a TokenRefreshException, without being sent. The session is kept.

Without a session, requests go out without a token.

It is a plain Interceptor, not a QueuedInterceptor: requests are not serialized behind each other, Authyra already coordinates the refresh.

Options

OptionDefaultPurpose
shouldAttachevery requestDecide per request whether to attach the token. Use it when the same Dio calls third-party hosts.
headerNameAuthorizationThe header carrying the token.
tokenPrefixBearer Prefix before the token.

Per request

// A public endpoint: no token, no refresh.
await api.get('/health', options: Options(extra: {AuthyraInterceptor.skip: true}));

// On behalf of an account that is not the active one.
await api.get('/me', options: Options(extra: {AuthyraInterceptor.sessionKey: key}));

Use a separate client for auth calls

The Dio your provider uses for /auth/login and /auth/refresh must not carry this interceptor: a refresh call that triggers a refresh cannot finish. Keep two instances, as in the quick start.

Copyright © 2026