Next.js Route Handler with Yoga

22 May 2023

Next.js and GraphQL Yoga have worked together inside API routes seamlessly over the last few years but now with Next.js 13 and the App Router, we have a new way to do things.

We'll be using Route Handlers to create a GraphQL Yoga route.

If you haven't already, install graphql and graphql-yoga:

npm i graphql graphql-yoga

Then create the file app/graphql/route.ts with the following:

import { createSchema, createYoga } from "graphql-yoga";

const { handleRequest } = createYoga({
  graphqlEndpoint: "/graphql",
  schema,
  fetchAPI: {
    Request: Request,
    Response: Response,
  },
});

export { handleRequest as GET, handleRequest as POST };

Now all that's left to do is add your own schema. You can use createSchema from Yoga to do this:

import { createSchema, createYoga } from "graphql-yoga";

const schema = createSchema({
  typeDefs: /* GraphQL */ `
    type Query {
      cart(id: ID!): Cart!
    }

    type Cart {
      id: ID!
      totalItems: Int!
      items: [CartItem]
    }

    type CartItem {
      id: ID!
      name: String!
    }
  `,
  resolvers: {
    Query: {
      cart: (_, { id }) => ({
        id,
        totalItems: 1,
        items: [{ id: "item-1", name: "Stickers" }],
      }),
    },
  },
});

const { handleRequest } = createYoga({
  graphqlEndpoint: "/graphql",
  schema,
  fetchAPI: {
    Request: Request,
    Response: Response,
  },
});

export { handleRequest as GET, handleRequest as POST };