• v2
  • Integrations
  • Next.js

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

yarn add @graphql-yoga/node graphql

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.

Last updated on September 19, 2022