Setup Graphql API in React Nextjs

How to setup a graphql API end point in Nextjs using Apollo Server Micro

Wed Jul 28 2021

Using the pages/api route we can add graphql end point in Nextjs. In order to achieve this we have to use *apollo-server-micro, express*. The API route will consume the server less function feature.

Problem

In most case, the methods that create the graphql server end up with errors. I have been tested those methods suggested by many youtubers, which end up with error, such as server can't access/located . I tried the cors , and it didn't make it.

Here is our full API for Nextjs route

//grphql.js
import { gql, ApolloServer } from "apollo-server-micro";
import { PrismaClient } from "@prisma/client";
import {
  ApolloServerPluginLandingPageGraphQLPlayground,
  ApolloServerPluginLandingPageDisabled,
} from "apollo-server-core";
const prisma = new PrismaClient(); 
 
 
const typeDefs = gql`
  type Contact {
    id: String
    name: String
    email: String
  }

  type Query {
    contacts: [Contact]
  }
`;

const resolvers = {
  Query: {
    contacts(_parent, _args, _context) {
      return prisma.contact.findMany();
    },
  },
};

let apolloServerHandler =(req, res) => Promise
async function startServer(req, res) {
   const server =   new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [
      ApolloServerPluginLandingPageGraphQLPlayground({
        // options
      }),
    ],
  }) ;
  await server.start();
  apolloServerHandler=   server.createHandler({path:'/api/graphql'}); 
  return apolloServerHandler;
}

export default async (req,res)=>{
    const apolloServerHandler = await startServer();
    return apolloServerHandler(req,res)
}
 
export const config = { api: { bodyParser: false } };

Prisma ORM

I also utilized the Prisma ORM for fetching real time data, if you wanna know, how to Prisma, check out the Next Prisma Guide.

Comments