flutterdartgraphql

Add headers to request using Ferry with Flutter


it's my first time using Ferry to make GraphQL requests. My GraphQL Server has some queries that need an HTTP header for authorization.

I need to be able to add the header after initializing the client.

client.dart:

Future<Client> initClient() async {
  await Hive.initFlutter();

  final box = await Hive.openBox<Map<String, dynamic>>("graphql");

  await box.clear();

  final store = HiveStore(box);

  final cache = Cache(store: store);

  final link = HttpLink("example.com/");

  final client = Client(
    link: link,
    cache: cache,
  );

  return client;
}

main.dart:

void main() async{
  final client = await initClient();
  GetIt.I.registerLazySingleton<Client>(() => client);
  runApp(MyApp());
}

request file:

    client.request(Req).listen((response) {
      print(response.graphqlErrors); // It will return an error because theres no header with the token
      print(response.data);
    });

Solution

  • Here is a simple example for adding headers to the Ferry GraphQL client requests. In this example, we add an Authorization Bearer Token to the request.

    The headers are added by adding an object to the defaultHeaders parameter on creation of the HttpLink object.

    graphql_service.dart

    import 'package:ferry/ferry.dart';
    import 'package:gql_http_link/gql_http_link.dart';
    
    Client initGqlClient(String url) {
      final link = HttpLink(
        url,
        defaultHeaders: {
          'Authorization':
              'Bearer eyJ0eXAiOi...',
        },
      );
    
      final client = Client(link: link);
    
      return client;
    }