This is the third and final part of my series which explores implementing GraphQL using Apollo and NextJS.

Part 1 dealt with the app setup, and Part 2 dealt with the Client-Side in depth. I would highly recommend reading them first before getting into this article, unless you are already comfortable with Client-Side GraphQL using Apollo.

If you are completely new to GraphQL, please read my beginners tutorial here.

This article discusses the Server-Side implementation of Apollo. Let’s being!

A quick refresher/reminder: We leverage NextJS’ internal API Routes system to accept a GraphQL query, and by using apollo-server-micro (not apollo-server!), we are able to return GraphQL compliant results.

This is the Server-Side code for the app, and you can find it in the full project here.

import { ApolloServer, gql } from "apollo-server-micro";

	let book = {
	  name: "The Hungarian Sausage",
	  author: "Ben Grunfeld",
	};

	const typeDefs = gql`
	  type Book {
	    name: String
	    author: String
	  }

	  type Query {
	    book: Book
	  }

	  type Mutation {
	    updateBook(name: String!, author: String!): Book
	  }
	`;

	const resolvers = {
	  Query: {
	    book: () => book,
	  },

	  Mutation: {
	    updateBook: (root, args) => {
	      book.name = args.name;
	      book.author = args.author;
	      return book;
	    },
	  },
	};

	const server = new ApolloServer({ typeDefs, resolvers });

	const handler = server.createHandler({ path: "/api/graphql-data" });

	export const config = {
	  api: {
	    bodyParser: false,
	  },
	};

	export default handler;

#graphql #apollo-server #apollo #nextjs

Full-Stack GraphQL With Apollo & NextJS — Part 3: Server-Side
23.15 GEEK