Skip to Content
SWR 2.0 is out! Read more →
remotegraphql-yogaintegrationsintegration-with-nextjs

Integration with Next.js

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

Example

pages/aрi/graphql.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { createServer } from '@graphql-yoga/node'
import type { NextApiRequest, NextApiResponse } from 'next'
 
export const config = {
  api: {
    // Disable body parsing (required for file uploads)
    bodyParser: false
  }
}
 
export default createServer<{
  req: NextApiRequest
  res: NextApiResponse
}>()
💡

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

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 { createServer } from '@graphql-yoga/node'
import type { NextApiRequest, NextApiResponse } from 'next'
import type { Session } from 'next-auth'
import { getSession } from 'next-auth/react'
 
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 })
    }
  }
})
💡

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