logo My Digital Garden

NextJS 13 series - Adding GraphQL

By James Kolean on Nov 26, 2023
Source repository: https://gitlab.com/jameskolean/next-explore
Demo: https://next-explore-liart.vercel.app/
JavaScriptNext
banner

Today, we’re embarking on a journey to enhance your Next.js application with the magic of GraphQL.

  • GraphQL: A powerful query language for APIs that allows you to request exactly the data you need.

  • Yoga: A fully-featured GraphQL server library that makes it easy to set up a GraphQL server with minimal boilerplate.

Get Started

We will pick up where we left our Next.js app with Prisma set up.

  1. Install Dependencies: Begin by installing the necessary packages:
pnpm add graphql-yoga graphql
  • graphql: The JavaScript reference implementation for GraphQL.
  • yoga: The Yoga GraphQL server library.
  1. Create Yoga Server:

Add a graphQl API endpoint to our app.

// src/app/api/graphql/route.ts
// Next.js Custom Route Handler: https://nextjs.org/docs/app/building-your-application/routing/router-handlers
import {
    createSchema,
    createYoga
} from "graphql-yoga";
import {
    typeDefs
} from "@/graphql/schema";
import {
    resolvers
} from "@/graphql/resolvers";
const {
    handleRequest
} = createYoga({
    schema: createSchema({
        typeDefs,
        resolvers,
    }),

    // While using Next.js file convention for routing, we need to configure Yoga to use the correct endpoint
    graphqlEndpoint: "/api/graphql",

    // Yoga needs to know how to create a valid Next response
    fetchAPI: {
        Response
    },
});

export {
    handleRequest as GET,
    handleRequest as POST,
    handleRequest as OPTIONS,
};

This sets up a basic GraphQL server using Yoga.

  1. Create GraphQL Schema: In the src/graphql folder, create a file named schema.ts to define your GraphQL schema:
// src/graphql/schema.ts
export const typeDefs = `
  type Book {
    id: ID
    title: String
    genre: String
    author: Author
  }

  type Author {
    id: ID
    name: String
    books: [Book]
  }

  type Query {
    books: [Book]!
    authors: [Author]!
  }
`;

This schema defines a Book type, an Author type, and a Query type. The Query type is required and references our other custom types.

  1. Create GraphQL resolvers: In the src/graphql folder, create a file named resolvers.ts to tell GraphQL how to get the data:
// src/graphql/resolvers.ts
import prisma from "@/lib/prisma";

export const resolvers = {
    Query: {
        books: async () => {
            return await prisma.book.findMany({
                include: {
                    author: true, // All posts where authorId == 20
                },
            });
        },
        authors: async () => {
            return await prisma.author.findMany({
                include: {
                    books: true, // All posts where authorId == 20
                },
            });
        },
    },
};

Note that this uses a utility function:

// /src/lib/prisma.ts
import {
    PrismaClient
} from "@prisma/client";

let prisma: PrismaClient;

declare global {
    var prisma: PrismaClient;
}

if (process.env.NODE_ENV === "production") {
    prisma = new PrismaClient();
} else {
    if (!global.prisma) {
        global.prisma = new PrismaClient();
    }
    prisma = global.prisma;
}
export default prisma;
  1. Now you can run your GraphQL server with pnpm dev .

Open http://localhost:3000/api/graphql

Summary

That’s it! We’ve successfully integrated GraphQL with Prisma in your Next.js app using Yoga. The application can now benefit from the flexibility of GraphQL queries and the seamless database interactions provided by Prisma.

© Copyright 2024 Digital Garden cultivated by James Kolean.