v3
Features
Plugins
⚠️
This is the documentation for the old GraphQL Yoga version 3. We recommend upgrading to the latest GraphQL Yoga version 5.

Migrate to GraphQL Yoga v5

Plugins

Yoga builds upon the GraphQL plugin system envelop and adds additional HTTP specific hooks for customizing both the GraphQL execution and HTTP layer. Many of the additional features of Yoga are added via plugins. If you need to customize your GraphQL API you can also write your own plugins.

Using Plugins

You can both use Yoga or Envelop plugins with GraphQL Yoga.

💡

When there is both a Envelop and Yoga specific plugin available, you should always opt-in for the Yoga variant as this one allows certain optimizations compared to just an Envelop plugin. As envelop plugins have only control over the GraphQL execution for example a plugin such as the response-cache, can never act on the HTTP level. However, the yoga response-cache, Persisted Operations or Defer/Stream plugin utilizes the HTTP level hooks, and thus can completly skip all of the expensive GraphQL execution steps for serving cached results.

Envelop Plugin Example

The following example adds GraphQL JIT to our GraphQL Server using Envelop GraphQL JIT Plugin

import { useGraphQlJit } from '@envelop/graphql-jit'
import { createYoga, createSchema } from 'graphql-yoga'
 
// Provide your schema
const yoga = createYoga({
  schema: createSchema({
    typeDefs: /* GraphQL */ `
      type Query {
        greetings: String!
      }
    `,
    resolvers: {
      Query: {
        greetings: () => 'Hello World!'
      }
    }
  }),
  plugins: [useGraphQlJit()]
})
 
// Start the server and explore http://localhost:4000/graphql
const server = createServer(yoga)
server.listen(4000, () => {
  console.info('Server is running on http://localhost:4000/graphql')
})

Yoga Plugin Example

Please refer to the corresponding feature documentation pages. E.g. Response Cache, Persisted Operations or Defer/Stream.

Yoga Defer Stream Plugin Usage Example
import { createYoga } from 'graphql-yoga'
import { createServer } from 'node:http'
import { useDeferStream } from '@graphql-yoga/plugin-defer-stream'
 
const yoga = createYoga({
  plugins: [useDeferStream()]
})
 
const server = createServer(yoga)
 
server.listen(4000, () => {
  console.info('Server is running on http://localhost:4000/graphql')
})

Writing Plugins

Sometimes you might want to build your own plugins. You can write your own Yoga plugin and even share it with other people by publishing it to npm.

💡

A good entry-point for discovering how to write Yoga plugins is to look at the source code of the existing plugins maintained by us.

The most hooks for Yoga origin from the envelop plugin system. Please refer to the Envelop Plugin Lifecycle documentation for more information.

In addition, Yoga adds more HTTP specific hooks.

💡

The HTTP hooks are still not 100% stable and we advise using them on your own risk. For the next Yoga major version these hooks will be finalized and marked as stable.

onRequest

This hook is invoked for any incoming HTTP request. Here you can manipulate the request, create a short circuit before Yoga handles the request or apply security measures such as checking for access tokens etc.

API

Example

import { Plugin } from 'graphql-yoga'
 
function useAuth(): Plugin {
 return {
  onRequest({ request, fetchAPI, endResponse }) {
    if (!request.headers.get('authorization')) {
      endResponse(
        new fetchAPI.Response(
          null,
          {
            status: 401,
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );
      )
    }
  }
 }
}

onRequestParse

This hook is invoked for any incoming HTTP request. Here you can manipulate the request, set a custom request parser or apply security measures such as checking for access tokens etc.

onParams

This hook is invoked for an incoming GraphQL request after the GraphQL parameters (query, variables, extensions and operationName) have been ATTEMPTED to be parsed. Within this hook you can manipulate and customize the parameters or even implement a whole new way of parsing the parameters (if you wish to diverge from the GraphQL over HTTP specification).

In addition to that you could also short-circuit and skip the GraphQL execution. E.g. you might want to serve a result from the cache instead.

Example use cases:

  • Response Cache: Short-circuit GraphQL execution if response can be served from the cache.
  • Persisted Operations: Load the query document string from the persisted operations store before running the execution.
  • APQ: Load/persist the query document string on the persisted operations store.

onResultProcess

This hook is invoked after a GraphQL request has been processed and before the response is forwarded to the client. Here you can customize what transport/response processor format should be used for sending the result over the wire.

onResponse

This hook is invoked after a GraphQL request has been processed and after the response has been forwarded to the client. Here you can perform any cleanup or logging operations, or you can manipulate the outgoing response object.

API

Example

import { Plugin } from 'graphql-yoga'
 
function useYogaSignature(): Plugin {
  return {
    onResponse({ request, response }) {
      response.headers.set('X-GraphQL-Server', 'Yoga')
    }
  }
}