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.
We will pick up where we left our Next.js app with Prisma set up.
pnpm add graphql-yoga graphql
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.
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.
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;
pnpm dev
.Open http://localhost:3000/api/graphql
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.