Client Awareness and Enforcement

Require client details and operation names to help monitor schema usage


Metrics about GraphQL schema usage are more insightful when information about clients using the schema is available. Understanding client usage can help you reshape your schema to serve clients more efficiently. As part of GraphOS Studio metrics reporting, servers can tag reported operations with the requesting client's name and version. This client awareness helps graph maintainers understand which clients are using which fields in the schema.

Apollo's GraphOS Router and Apollo Server can enable client awareness by requiring metadata about requesting clients. The router supports client awareness by default. If the client sets its name and version with the headers apollographql-client-name and apollographql-client-version in its HTTP requests, GraphOS Studio can separate the metrics and operations per client.

note
The client name is also used by the persisted queries feature.

Clients should name their GraphQL operations to provide more context around how and where data is being used.

Why enforce client reporting?

Client metadata enables better insights into schema usage, such as:

  • Identifying which clients use which fields: This facilitates usage monitoring and safe deprecation of fields.

  • Understanding traffic patterns: This helps optimize schema design based on real-world client behavior.

  • Improving operation-level observability: This provides details for debugging and performance improvements.

Apollo strongly recommends requiring client name, client version, and operation names in all incoming GraphQL requests.

Enforcing in GraphOS Router

The GraphOS Router supports client awareness by default if the client sets the apollographql-client-name and apollographql-client-id in their requests. These values can be overridden using the router configuration file directly. You can use a Rhai script to enforce that clients include metadata.

Customizing client awareness headers

If headers with customized names need to be sent by a browser, they must be allowed in the CORS (Cross Origin Resource Sharing) configuration, as follows:

YAML
router.yaml
1telemetry:
2  apollo:
3    # defaults to apollographql-client-name
4    client_name_header: MyClientHeaderName
5    # defaults to apollographql-client-version
6    client_version_header: MyClientHeaderVersion
7cors:
8  # The headers to allow.
9  # (Defaults to [ Content-Type ], which is required for GraphOS Studio)
10  allow_headers: [ Content-Type, MyClientHeaderName, MyClientHeaderVersion]

Enforcing via Rhai script

Client headers can be enforced using a Rhai script on every incoming request.

Rhai
client-id.rhai
1fn supergraph_service(service) {
2    const request_callback = Fn("process_request");
3    service.map_request(request_callback);
4  }
5
6fn process_request(request) {
7  log_info("processing request");
8  let valid_clients = ["1", "2"];
9  let valid_client_names = ["apollo-client"];
10
11  if ("apollographql-client-version" in request.headers && "apollographql-client-name" in request.headers) {
12    let client_header = request.headers["apollographql-client-version"];
13    let name_header = request.headers["apollographql-client-name"];
14
15    if !valid_clients.contains(client_header) {
16      log_error("Invalid client ID provided");
17      throw #{
18        status: 401,
19        message: "Invalid client ID provided"
20      };
21    }
22    if !valid_client_names.contains(name_header) {
23      log_error("Invalid client name provided");
24      throw #{
25        status: 401,
26        message: "Invalid client name provided"
27      };
28    }
29  }
30  else {
31    log_error("No client headers set");
32    throw #{
33      status: 401,
34      message: "No client headers set"
35    };
36  }
37}

See a runnable example Rhai script in the Apollo Solutions repository.

note
The code in this repository is experimental and has been provided for reference purposes only.
tip
If you're an enterprise customer looking for more material on this topic, try the Enterprise best practices: Router extensibility course on Odyssey.Not an enterprise customer? Learn about GraphOS for Enterprise.

Enforcing in Apollo Server

If you're using Apollo Server for your gateway, you can require client metadata in every incoming request with a custom plugin:

tip
The header names used below are the default headers sent by Apollo Client, but you can change them to whatever names your client uses. Additionally, these changes must be reflected in the usage reporting plugin to report client headers to GraphOS. For an example, see using custom client id headers.
TypeScript
index.ts
1function clientEnforcementPlugin(): ApolloServerPlugin<BaseContext> {
2  return {
3    async requestDidStart() {
4      return {
5        async didResolveOperation(requestContext) {
6          const clientName = requestContext.request.http.headers.get("apollographql-client-name");
7          const clientVersion = requestContext.request.http.headers.get("apollographql-client-version");
8
9          if (!clientName) {
10            const logString = `Execution Denied: Operation has no identified client`;
11            requestContext.logger.debug(logString);
12            throw new GraphQLError(logString);
13          }
14
15          if (!clientVersion) {
16            const logString = `Execution Denied: Client ${clientName} has no identified version`;
17            requestContext.logger.debug(logString);
18            throw new GraphQLError(logString);
19          }
20
21          if (!requestContext.operationName) {
22            const logString = `Unnamed Operation: ${requestContext.queryHash}. All operations must be named`;
23            requestContext.logger.debug(logString);
24
25            throw new GraphQLError(logString);
26          }
27        },
28      };
29    },
30  };
31}
32const server = new ApolloServer({
33  typeDefs,
34  resolvers,
35  plugins: [clientEnforcementPlugin()],
36});

Adding enforcement for existing clients

If clients are already consuming your graph and are not providing client metadata, adding universal enforcement will break those clients. To resolve this you should take the following steps:

Use other headers

If you have other existing headers in your HTTP requests that can be parsed to extract some client info, you can extract the info from there.

GraphOS Router

Client awareness headers should be overridden using the router configuration file to use the appropriate header names.

Apollo Server

If you do change the identifying headers, also update the Usage Reporting Plugin to use the new headers so that the proper client info is also sent to Studio.

Ask clients to update their requests

The long-term fix will require that clients start sending the required headers needed to extract client info. While clients are working on updating their requests you can add the plugin code to your gateway, but instead of throwing an error you can log a warning so that the gateway team can track when all requests have been updated.

Feedback

Edit on GitHub

Forums