Catch the highlights of GraphQLConf 2023!Click for recordings.Or check out our recap blog post.
v5 (latest)
Integrations
Hapi

Integration with Hapi

Hapi (opens in a new tab) 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

npm i @hapi/hapi graphql-yoga graphql

Example

import http from 'node:http'
import { Readable } from 'node:stream'
import { createSchema, createYoga } from 'graphql-yoga'
import Hapi from '@hapi/hapi'
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(req.raw.req, { req, h })
 
    const res = h.response(
      Readable.from(body, {
        // hapi needs the stream not to be in object mode
        objectMode: false
      })
    )
 
    for (const [key, val] of headers) {
      res.header(key, val)
    }
 
    return res.code(status)
  }
})
 
server.start()

The GraphQL Yoga server should now be available at http://localhost:4000/graphql (opens in a new tab).

You can also check a full example on our GitHub repository here (opens in a new tab).