v3
Integrations
Hapi
⚠️
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

Integration with Hapi

Hapi allows you to build powerful, scalable applications, with minimal overhead and full out-of-the-box functionality - your code, your way.

It continues to be the proven choice for enterprise-grade backend needs.

Installation

Terminal
yarn add @hapi/hapi
yarn add graphql
yarn add graphql-yoga

Example

import Hapi from '@hapi/hapi'
import http from 'node:http'
import { Readable } from 'node:stream'
import { createYoga, createSchema } from 'graphql-yoga'
import { schema } from './my-graphql-schema'
 
interface ServerContext {
  req: Hapi.Request
  h: Hapi.ResponseToolkit
}
 
const yoga = createYoga<ServerContext>({ schema })
 
const server = Hapi.server({ port: 4000 })
 
server.route({
  method: '*',
  path: yoga.graphqlEndpoint,
  options: {
    payload: {
      // let yoga handle the parsing
      output: 'stream'
    }
  },
  handler: async (req, h) => {
    const { status, headers, body } = await yoga.handleNodeRequest(
      // will be an incoming message because the payload output option is stream
      req.payload as http.IncomingMessage,
      { req, h }
    )
 
    const res = h.response().code(status)
    for (const [key, val] of headers) {
      res.header(key, val)
    }
 
    return Readable.from(body, {
      // stream cannot be in object mode
      objectMode: false
    })
  }
})
 
server.start()

The GraphQL Yoga server should now be available at http://localhost:4000/graphql.

You can also check a full example on our GitHub repository here.