Customizations for the Apollo Router
Extend your router with custom functionality
You can write customizations for the Apollo Router to add functionality that isn't provided by default. For example, you can make an external call to fetch authentication data for each incoming request.
Customization types
The Apollo Router supports two types of customizations:
- Rhai scripts (recommended)
- The Rhai scripting language enables you to add functionality to the stock router binary, which means you don't need to compile a custom binary or write any native Rust code.
- Native Rust plugins
- Native Rust plugins require building the Apollo Router binary from source, which in turn requires familiarity with building Rust projects.
- If you need to build a native Rust plugin, see examples provided in the Apollo Router repo, including a hello world.
Use Rhai scripts if you can. Use a native rust plugin only if your customization needs to do any of the following:
- Access Rust crates
- Read or write to disk
- Make network requests
How customizations work
Before you build a customization, it helps to understand how the Apollo Router handles each incoming GraphQL request. During each request's execution, three services in the router communicate with each other as shown:
As execution proceeds "left to right" from the RouterService
to individual SubgraphService
s, each service passes the client's original request along to the next service. Similarly, as execution continues "right to left" from SubgraphService
s to the RouterService
, each service passes the generated response for the client.
Apollo Router customizations can hook into any combination of these services and modify the request, response, and/or related metadata as they're passed along.
Service descriptions
Each Apollo Router service has a corresponding function that a customization can define to hook into that service:
Service / Function | Description |
---|---|
| Runs at the very beginning and very end of the request lifecycle. Define |
| Runs at the very beginning and very end of the GraphQL request lifecycle. Define |
| Handles initiating the execution of a query plan after it's been generated. Define |
| Handles communication between the Apollo Router and your subgraphs. Define Whereas other services are called once per client request, this service is called once per subgraph that's required to resolve the client's request. Each call is passed a |
Each service has a request and response data-structure that holds:
- A context object that was created at the start of the request and is propagated throughout the entire request lifecycle. It holds:
- The original request from the client
- A bag of data that can be populated by plugins for communication across the request lifecycle
- Any other specific data to that service (e.g., query plans and downstream requests/responses)
Next, see the documentation for your preferred customization type.