loading...

GraphQL on Next.js + Zeit Serverless Functions

ianh profile image ian h ・1 min read

I was a bit surprised that there wasn't a library dedicated to running GraphQL on Next.js. It's not terribly hard to do, but I just found myself copying code from project to project enough that it warrants its own library.

Announcing next-graphql, a drop-in solution for running GraphQL on Next.js (and Zeit Serverless Functions): https://github.com/ian/next-graphql

If you're unfamiliar with how Zeit Serverless Functions work, here's the announcement: https://zeit.co/docs/v2/serverless-functions/introduction

In it's simplest form it's a 1-page implementation by adding a api/graphql.js (or pages/api/graphql.js for next.js).

Example:

import { createHandler } from "next-graphql"

let ITEMS = [
  { name: "First" }
]

const typeDefs = `
  type Item {
    name: String! 
  }

  type Query {
    getItems: [Item]!
  }

  type Mutation {
    createItem(name:String!): Item!
  }
`

const resolvers = {
  Query: {
    getItems: async () => {
      return db
    },
  },
  Mutation: {
    createItem: async (obj, { name }) => {
      const item = { name }
      ITEMS.push(item)
      return item
    }
  }
}

export default createHandler({
  typeDefs,
  resolvers,
})

Discussion

markdown guide