Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add customised header on http request for authentication when using flutter graphql library?

I am using this library https://pub.dev/packages/graphql_flutter for graphql in a flutter web application. Below code can be used to get authentication token:

import 'package:graphql_flutter/graphql_flutter.dart';
final HttpLink httpLink = HttpLink(
    'https://api.github.com/graphql',
  );

  final AuthLink authLink = AuthLink(
    getToken: () async => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
    // OR
    // getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
  );

but how can I put the token in the http header like x-api-key: xxxx when sending requests?

I have tried:

HttpLink link = HttpLink(
    uri: 'https://api.github.com/graphql',
    headers: <String, String>{
      'x-api-key': 'xxxx',
    },
  );

but it gives me the error: The named parameter 'uri' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'uri'.

like image 821
Joey Yi Zhao Avatar asked Oct 30 '25 01:10

Joey Yi Zhao


1 Answers

Base on the answer from @moaid-alrazhy and after checking how AuthLink is working

class CustomAuthLink extends Link {
  CustomAuthLink();

  @override
  Stream<Response> request(Request request, [NextLink? forward]) async* {
    // Some logic here
    final AuthService authService = GetIt.I.get<AuthService>();

    final String? token = authService.token;
    final String deviceID = await DeviceInformation.deviceIMEINumber;

    // TIP: do not forget getting new Request instance!
    final Request req = request.updateContextEntry<HttpLinkHeaders>(
      (HttpLinkHeaders? headers) => HttpLinkHeaders(
        headers: <String, String>{
          // put oldest headers
          ...headers?.headers ?? <String, String>{},
          // and add a new headers
          'Authorization': 'Bearer $token',
          'x-device-id': deviceID,
        },
      ),
    );

    // and "return" new Request with updated headers
    yield* forward!(req);
  }
}
like image 67
WiRight Avatar answered Nov 01 '25 20:11

WiRight