Persisting cookies keeps session material beyond one request. This older Dio example also copied a decoded XSRF-TOKEN cookie into an X-XSRF-TOKEN header.
dio: ^3.0.10
dio_cookie_manager: ^1.0.0
path_provider: ^1.6.27
cookie_jar: ^1.0.1
final Dio dio = Dio();
PersistCookieJar cookieJar;
Api() {
if (!kReleaseMode) {
dio.interceptors
.add(LogInterceptor(responseBody: true, requestBody: true));
}
getApplicationDocumentsDirectory().then((Directory appDocDir) async {
final String appDocPath = appDocDir.path;
final String cookiePath = '$appDocPath/cookies';
final Directory dir = Directory(cookiePath);
await dir.create();
cookieJar = PersistCookieJar(dir: cookiePath);
dio.interceptors.add(CookieManager(cookieJar));
dio.interceptors
.add(InterceptorsWrapper(onResponse: (Response<dynamic> response) {
final String urlPath = response.request.path;
final List<Cookie> cookies =
cookieJar.loadForRequest(Uri.parse(urlPath));
final String xsrfToken = cookies
.firstWhere((Cookie c) => c.name == 'XSRF-TOKEN',
orElse: () => null)
?.value;
// Set dio auth header token once time
if (xsrfToken != null) {
/// The XSRF-TOKEN got from cookie requires decoded before add to header
dio.options.headers['X-XSRF-TOKEN'] = Uri.decodeComponent(xsrfToken);
dio.options.headers['X-Requested-With'] = 'XMLHttpRequest';
String cookieStr = '';
for (int i = 0; i < cookies.length; i++) {
final Cookie c = cookies[i];
cookieStr += '${c.name}=${c.value}; ';
}
dio.options.headers['Cookie'] = cookieStr;
}
return response;
}));
});
}
Keep initialization and origin scope visible
The constructor starts asynchronous directory setup without returning a readiness result. Requests issued before that setup completes can follow a different path from later requests.
The example also assigns Cookie and XSRF headers globally on the client. Reusing that client for another origin needs deliberate scoping; persisted cookies, manual headers, expiry, and logout cleanup cannot be assumed equivalent.
The debug interceptor records request and response bodies, which may expose session or personal data. This is a historical integration sketch, not a validated session-security implementation. No cookie files, credentials, or requests were imported or created.