← Back

GraphQL: Schema First vs Code First approaches

There are 2 main approaches to build a GraphQL Server (Schema First and Code First). Both options are good, but they have pros and cons that we will cover in this post.

My review will be based on a GraphQL server using Node.JS.

Schema First

The Schema First indicates that we first define the GraphQL Schema, and then we implement the code.

GraphQL Schema -> Resolvers

# schema.gql
type Query {
    hello: String!
}
// resolvers.js
const resolvers = {
  Query: {
    hello: () => "Hello World!"
  }
}

Pros

  • Schema and implementation are separated
  • Good DX when working with Javascript

Cons

Code First

In the code-first approach, we start by coding the resolvers, and then, from the code as a single source of truth, we generate the schema.

Resolvers -> GraphQL Schema (Generated)

// resolvers.js
const resolvers = {
  Query: {
    hello: () => "Hello World!"
  }
}
# generated.schema.gql
type Query {
    hello: String!
}

Pros

Cons

  • Schema and Implementation are together (you could separate it by adding the business logic outside the resolvers)
  • It adds an extra complexity in your code.

Conclusion

If you plan to use Typescript, then a Code First approach will be a better fit. Otherwise, a Schema First approach is the easiest way to go.

There is one condition for using a Code First approach, this one requires you to understand well how GraphQL works and what you can do with it, because the Schema will be generated automatically.

If you are a beginner with GraphQL, I will recommend you to see the concepts about GraphQL from the official website: https://graphql.org/learn/ And then try to implement then using just Javascript and Apollo-Server. Once you master the basic concepts, you will be ready to move to a Code First approach.