On this page

Integration with Next.js

GraphQL Yoga v2 documentation (superseded by v5): Next.js) is a web framework that allows you to build websites very quickly and GraphQL Yoga can be integrated with Next.js easily as an API Route.

Next.js is a web framework that allows you to build websites very quickly and GraphQL Yoga can be integrated with Next.js easily as an API Route.

Installation

npm i @graphql-yoga/node graphql

Example

pages/aрi/graphql.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import { createServer } from '@graphql-yoga/node'

export const config = {
  api: {
    // Disable body parsing (required for file uploads)
    bodyParser: false
  }
}

export default createServer<{
  req: NextApiRequest
  res: NextApiResponse
}>()

NextAuth.js

NextAuth.js is a popular solution for doing authentication within a Next.js application.

You can easily type and add the session to the GraphQL context by adjusting your GraphQL router handler to the following.

pages/aрi/graphql.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import type { Session } from 'next-auth'
import { getSession } from 'next-auth/react'
import { createServer } from '@graphql-yoga/node'

export const config = {
  api: {
    // Disable body parsing (required for file uploads)
    bodyParser: false
  }
}

export default createServer<
  {
    req: NextApiRequest
    res: NextApiResponse
  },
  {
    session: Session
  }
>({
  context: async ({ req }) => {
    return {
      session: await getSession({ req })
    }
  }
})