Today I've decided to integrate Apollo GraphQL with the Next.js API, instead of using the existing one in REST.
To begin our new project, let's start by creating a new Next.js project
npx create-next-app --typescript
after selecting the project name, which is the folder where your project is going to be created.
Need to install the following packages: create-next-app Ok to proceed? (y) y ✔ What is your project named? … my-app Creating a new Next.js app in /Users/pedroresende/Projects/next-graphql/my-app. Using npm. Installing dependencies: - react - react-dom - next added 269 packages, and audited 270 packages in 5s 45 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Installing devDependencies: - typescript - @types/react added 5 packages, and audited 275 packages in 1s 45 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created my-app at /Users/pedroresende/Projects/next-graphql/my-app Inside that directory, you can run several commands: npm run dev Starts the development server. npm run build Builds the app for production. npm start Runs the built app in production mode. We suggest that you begin by typing: cd my-app npm run dev
I decided to use the default project name, which is `my-app`.
Now, let install the apollo GraphQL server, by running
$ cd my-app $ npm install apollo-server-micro --save
Now, let's add the file graphql.ts under pages/api/ with the following content
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" }) export const config = { api: { bodyParser: false, }, } export default handler
let's start next.js, by running
$ npm run dev
Now, open in a browser and you'll see the apollo GraphQL explorer.
Let's give it a try, to see if everything is working fine. On the query add the following GraphQL query
query { book { name author } }
press the play button and you should see the following response
{ "data": { "book": { "name": "The Hungarian Sausage", "author": "Ben Grunfeld" } } }
Now, let's try a mutation (update), on the query section, add
mutation { updateBook(name:"Test-Driven Development by Example", author:"Kent Beck" ) { name author } }
Press once again on the play button and the response should be
{ "data": { "updateBook": { "name": "Test-Driven Development by Example", "author": "Kent Beck" } } }
That's it.
The tutorial is available on Github.
What do you think about this tutorial?