Start a graphql-yoga server in the NextJS api folder

Viewed 278

Could anyone please explain to me how I can start a GraphQL-Yoga server in the NextJS /api/ folder?

So far I have a graphql.js file inside of the pages/api folder and the code looks like this.

import { GraphQLServer } from 'graphql-yoga';

const typeDefs = `
  type Query {
    hello(name: String): String!
  }
`;

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}`,
  },
};

const server = new GraphQLServer({ typeDefs, resolvers });
server.start(() => console.log('Server is running on localhost:4000'));

My expectation was that I could enter localhost:4000 and enter the graphql-yoga playground where I can test my queries after starting it just like when I run this code in a Node JS project. NextJS runs as normal after I initiate npm run dev, but the graphql-yoga code doesn't seem to run. All advice is appreciated - thanks.

1 Answers

If you update your code to use @graphql-yoga/node and define the endpoint in server options you can access the Yoga GraphiQL playground at localhost:3000/api/graphql (or whatever port you Next.JS server is using). See the graphql.js file below or full Codesandbox example.

// pages/api/graphql.js
import { createServer } from "@graphql-yoga/node";

const typeDefs = `
  type Query {
    hello(name: String): String!
  }
`;

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || "World"}`
  }
};

const server = createServer({
  schema: { typeDefs, resolvers, endpoint: "/api/graphql" }
});

export default server;
Related