GraphQL-Yoga Documentation

repository·main·Indexed 27 days ago

https://github.com/graphql-hive/graphql-yoga

Documentation for the GraphQL-Yoga monorepo and the Envelop ecosystem. Includes guides on @envelop/core for building extensible GraphQL servers, built-in plugins for schema management and error handling, and specialized plugins for Apollo DataSources, Apollo Federation, Apollo Tracing, and Auth0 authentication. Also covers E2E testing across runtimes like CloudFlare Workers, AWS Lambda, and Vercel Functions.

Tokens
175.3K
Snippets
530
Records
708
Agent score
92%

What's inside GraphQL-Yoga

  1. Overview of GraphQL Yoga features

    main

    GraphQL Yoga is a fully-featured GraphQL server designed for ease of setup and high performance. Key features include:

    • Environment Agnostic: Uses the WHATWG Fetch API, allowing it to run on Node, Deno, Bun, Cloudflare Workers, and AWS Lambda.
    • Built-in Subscriptions: Supports GraphQL subscriptions via Server-Sent Events (SSE).
    • Spec Compliant: Follows the GraphQL over HTTP spec and the GraphQL Multipart Request spec for file uploads.
    • Developer Experience: Includes GraphiQL, is fully typed with TypeScript, and supports ESM.
    • Performance & Extensibility: Features automatic persisted queries, parsing/validation caching, and is compatible with all envelop plugins.
  2. Overview of Envelop

    main

    Envelop is a lightweight JavaScript/TypeScript library designed to customize the GraphQL execution layer. It allows developers to build, share, and compose plugins that enhance GraphQL server capabilities such as logging, monitoring, caching, rate-limiting, and error handling.

    Key characteristics:

    • Framework Agnostic: It does not dictate your GraphQL transport or framework and is HTTP server agnostic.
    • Zero Dependencies: The core of Envelop has zero dependencies and only alters the execution phases that your plugins explicitly use.
    • Flexible Environments: It can be used in Node.js or the browser, and for client/server, client-side, or server-to-server workflows.
    • No Vendor Lock-in: It is designed to let developers replace any part of their application without being blocked by upstream dependencies.
  3. Overview of GraphQL-Yoga E2E testing

    main

    The @graphql-yoga/e2e-testing package is used to ensure GraphQL-Yoga compatibility across various popular runtimes. It utilizes Pulumi (Infrastructure-as-Code) via the Pulumi Automation API to provision real resources in different environments, execute smoke tests, and subsequently destroy the resources.

    Smoke tests include:

    • GET -> GraphiQL
    • POST -> Execute GraphQL
  4. Overview of @envelop/generic-auth

    main

    The @envelop/generic-auth plugin enables custom authentication flows by allowing you to provide a custom user resolver that operates on the original HTTP request. Once a user is resolved, they are injected into the GraphQL execution context, making the user object available within your resolvers.

    Key features include:

    • Custom User Resolution: Resolve users based on HTTP request data.
    • Context Injection: Automatically makes the resolved user available in the GraphQL context.
    • Declarative Protection: Includes an optional @authenticated directive to protect specific parts of your GraphQL schema.
  5. Understand GraphQL Response Caching concepts

    main

    GraphQL response caching aims to skip the expensive execution phase for subsequent requests that use the same query operation and variables.

    Cache Key Construction

    A cache key is typically built by hashing the following inputs:

    • GraphQLOperationString: The raw query document.
    • GraphQLVariables: The stringified variables used in the operation.
    • RequestorId (Optional): A unique identifier (e.g., from an authorization token) to ensure users do not receive cached data belonging to others.

    Formula: OperationCacheKey = hash(GraphQLOperationString, Stringify(GraphQLVariables), [RequestorId])

  6. Understand Error Masking in GraphQL Yoga

    main
    GraphQL Yoga automatically masks unexpected errors (e.g., database connection failures or failed HTTP requests to remote services) to prevent leaking sensitive implementation details to clients. By default, these errors are replaced with a generic Unexpected error. message in the GraphQL response. This behavior is enabled by default and is a security feature to prevent targeted attacks.
  7. Understand the Default GraphQL Context in GraphQL Yoga

    main

    GraphQL Yoga constructs a context object for every incoming HTTP request. This object is injected into all GraphQL field resolver functions and is primarily used for dependency injection (e.g., accessing the current user or request headers).

    By default, the context contains:

    • request: A platform-independent Fetch API Request object. Use this to access headers for authentication.
    • params: An object containing GraphQL Request parameters:
      • query: The parsed DocumentNode.
      • operationName: The selected operation name.
      • variables: The variables defined in the query.
      • extensions: Extensions received from the client.
    import { createSchema, createYoga } from 'graphql-yoga'
    
    const yoga = createYoga({
      schema: createSchema({
        typeDefs: /* GraphQL */ `
          type Query {
            logHeader: Boolean
          }
        `,
        resolvers: {
          Query: {
            logHeader(_, _args, context) {
              // Accessing the default 'request' object
              console.log(context.request.headers.get('x-foo'))
            }
          }
        }
      })
    })