All skills
apollographql avatar

/apollo-router

@f13ff34 official
by Apollo GraphQLapollographql/skills115 stars
13

Version-aware guide for configuring and running Apollo Router for federated GraphQL supergraphs. Generates correct YAML for both Router v1.x and v2.x. Use this skill when: (1) setting up Apollo Router to run a supergraph, (2) configuring routing, headers, or CORS, (3) implementing custom plugins (Rhai scripts or coprocessors), (4) configuring telemetry (tracing, metrics, logging), (5) troubleshooting Router performance or connectivity issues, (6) securing the graph with JWT, declarative field-level authorization directives, or persisted-query safelisting, (7) managing router.yaml as version-controlled config with CI/CD validation.

Use this Skill: https://skilld.dev/gh/apollographql/skills/apollo-router

This session only. Nothing lands on disk.

referencesplugins.md

≈1.4k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Router Customization

Extend Apollo Router functionality with Rhai scripts or external coprocessors.

Customization Options

Option Language Use Case
Rhai Scripts Rhai (embedded) Simple transformations, header manipulation
Coprocessors Any (HTTP service) Complex logic, external service calls
Native Plugins Rust Maximum performance, deep integration

Rhai Scripts

Rhai is an embedded scripting language for lightweight customizations that run inside the Router.

Enable Rhai

# router.yaml
rhai:
  scripts: ./rhai
  main: main.rhai

Script Location

project/
├── router.yaml
└── rhai/
    ├── main.rhai        # Entry point
    └── helpers.rhai     # Optional modules

Basic Script Structure

// main.rhai

// Called for each incoming request
fn supergraph_service(service) {
    service.map_request(|request| {
        // Modify request
        print(`Received request: ${request.uri.path}`);
    });
}

// Called for each subgraph request
fn subgraph_service(service, subgraph) {
    service.map_request(|request| {
        // Add header for specific subgraph
        if subgraph == "products" {
            request.subgraph.headers["x-products-version"] = "v2";
        }
    });
}

Common Rhai Patterns

Add Request Headers:

fn supergraph_service(service) {
    service.map_request(|request| {
        request.headers["x-custom-header"] = "value";
    });
}

Access JWT Claims:

fn supergraph_service(service) {
    service.map_request(|request| {
        let claims = request.context["apollo_authentication::JWT::claims"];
        if claims != () {
            request.headers["x-user-id"] = claims["sub"];
        }
    });
}

Modify Response:

fn supergraph_service(service) {
    service.map_response(|response| {
        response.headers["x-served-by"] = "apollo-router";
    });
}

Early Return (Reject Request):

fn supergraph_service(service) {
    service.map_request(|request| {
        if request.headers["x-api-key"] == () {
            throw #{
                status: 401,
                message: "API key required"
            };
        }
    });
}

Rhai Hooks

Hook Description
supergraph_service Entry point for all requests
execution_service After query planning
subgraph_service Before each subgraph request

Coprocessors

External HTTP services that process requests/responses at various stages.

Enable Coprocessor

# router.yaml
coprocessor:
  url: http://localhost:8080
  timeout: 2s
  router:
    request:
      headers: true
      body: true
    response:
      headers: true
      body: true

Coprocessor Stages

coprocessor:
  url: http://localhost:8080
  
  # Router-level (full request)
  router:
    request:
      headers: true
      body: true
    response:
      headers: true
      body: false
  
  # Subgraph-level (per subgraph)
  subgraph:
    all:
      request:
        headers: true
        body: false

Coprocessor Request Format

The Router sends POST requests with this structure:

{
  "version": 1,
  "stage": "RouterRequest",
  "control": "continue",
  "id": "request-uuid",
  "headers": {
    "authorization": ["Bearer token"],
    "content-type": ["application/json"]
  },
  "body": "{\"query\": \"{ users { id } }\"}"
}

Coprocessor Response Format

Return JSON to modify the request/response:

{
  "version": 1,
  "stage": "RouterRequest",
  "control": "continue",
  "headers": {
    "x-user-id": ["123"]
  }
}

To reject a request:

{
  "version": 1,
  "stage": "RouterRequest",
  "control": {
    "break": 403
  },
  "body": "{\"errors\": [{\"message\": \"Forbidden\"}]}"
}

Example Coprocessor (Node.js)

const express = require('express');
const app = express();
app.use(express.json());

app.post('/', (req, res) => {
  const { stage, headers, body } = req.body;
  
  // Authentication check
  if (stage === 'RouterRequest') {
    if (!headers.authorization) {
      return res.json({
        version: 1,
        stage,
        control: { break: 401 },
        body: JSON.stringify({
          errors: [{ message: 'Unauthorized' }]
        })
      });
    }
  }
  
  // Continue with optional modifications
  res.json({
    version: 1,
    stage,
    control: 'continue',
    headers: {
      'x-processed-by': ['coprocessor']
    }
  });
});

app.listen(8080);

Choosing Between Rhai and Coprocessors

Criteria Rhai Coprocessor
Latency ~1-5ms ~10-50ms (network)
Language Rhai only Any language
Complexity Simple logic Complex business logic
External calls Not supported Supported
Deployment Bundled with Router Separate service

When to Use Rhai

  • Header manipulation
  • Simple request/response transformations
  • Logging and debugging
  • Context value extraction

When to Use Coprocessors

  • External API calls (validation, enrichment)
  • Complex business logic
  • Database lookups
  • Integration with existing services
  • Team uses a specific language

Native Plugins (Advanced)

For maximum performance, build custom Router binaries with Rust plugins.

# Clone Router
git clone https://github.com/apollographql/router.git

# Create custom plugin in apollo-router/src/plugins/

# Build with custom plugins
cargo build --release

Native plugins require Rust knowledge and a custom build pipeline.

Source: SKILL.md on GitHub

2 warnings16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    The skill is a configuration generator and guide for Apollo Router. It implements robust security best practices by default, including environment variable interpolation for sensitive data, disabling developmental features (introspection/sandbox) in production, and providing a validation checklist. No malicious patterns, data exfiltration, or unauthorized command execution risks were found.

  • Socket16d

    1 alert: gptAnomaly

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    26/26 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at f13ff34. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 4 months ago
What it can do
Runs commands
metadata
{
  "author": "apollographql",
  "version": "2.5.0"
}
All 1 allowed tools
Bash(router:*) Bash(./router:*) Bash(rover:*) Bash(curl:*) Bash(docker:*) Read Write Edit Glob Grep
Other metadata
compatibility
Linux/macOS/Windows. Requires a composed supergraph schema from Rover or GraphOS.
  • apollo-router
  • graphql
  • federation
  • routing
  • yaml
  • telemetry
  • authentication
  • cors

README badge

README badge for apollographql/skills/apollo-router

Generates version-aware Apollo Router configuration (v1.x or v2.x) for federated GraphQL supergraphs, handling routing, authentication, CORS, telemetry, and connectors. Use this skill to set up Router with JWT auth, traffic shaping, operation limits, or to troubleshoot connectivity and performance issues.

Generated from the current SKILL.md.

Does this skill support both Router v1 and v2?
Yes. The skill generates version-correct YAML for both v1.x and v2.x, which have incompatible config schemas. You must select your target version before generating any config.
Can I use this skill to configure Connectors?
Yes, but only for Router v2. Connectors (REST API integration) are a v2-only feature available in GA. The skill will not offer Connectors as an option if you select v1.
What do I need before I can run the generated config?
You need either a composed `supergraph.graphql` file from Rover or GraphOS access via `APOLLO_KEY` and `APOLLO_GRAPH_REF`. The skill assumes you have reachable subgraphs and will validate the config against the Router binary if available.
Does this skill help with response caching?
Yes, but only for Router v2.6.0 and later. The skill requires you to identify which subgraphs serve user-specific data and how you identify users before generating cache config, to prevent data leakage.
Will the skill validate my generated config?
Yes. After generating or editing config, the skill runs a checklist and attempts to validate against `router config validate` if the Router CLI is available. It will report pass/fail for each checklist item.

Generated from the current SKILL.md. These answers refresh after source changes.