v3 (latest)
Integrations
Next.js

Integration with Next.js

Next.js (opens in a new tab) 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 (opens in a new tab).

Installation

Terminal
yarn add graphql
yarn add graphql-yoga

Example

pages/api/graphql.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { createYoga, createSchema } from 'graphql-yoga'
import type { NextApiRequest, NextApiResponse } from 'next'
 
export const config = {
  api: {
    // Disable body parsing (required for file uploads)
    bodyParser: false
  }
}
 
const schema = createSchema({
  typeDefs: /* GraphQL */ `
    type Query {
      greetings: String
    }
  `,
  resolvers: {
    Query: {
      greetings: () => 'This is the `greetings` field of the root `Query` type'
    }
  }
})
 
export default createYoga<{
  req: NextApiRequest
  res: NextApiResponse
}>({
  schema,
  // Needed to be defined explicitly because our endpoint lives at a different path other than `/graphql`
  graphqlEndpoint: '/api/graphql'
})

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