GraphQL Yoga 3 and ExpressJS

14 Nov 2022

GraphQL Yoga 3 no longer comes bloated with various packages for different runtimes. Instead Yoga now ships with all the necessary functions to generate a schema, server, plugins, and leaves it to you to handle how to serve it.

This project already has Express.js running and serving on port 4000:

import express from "express";

const app = express();

app.listen(4000);

Let's first install the new graphql-yoga package and create a schema inside of our project:

npm install graphql-yoga

Now inside of our server.ts file we can import createSchema and createYoga:

import { createSchema, createYoga } from "graphql-yoga";

Similar to how we did before we can provide the typeDefs and resolvers to the new function createSchema. This function uses @graphql-tools/schema under the hood.

The schema here could be generated by Pothos, Nexus, GraphQL.js or any other library that generates an executable schema.

const schema = createSchema({
  typeDefs: /* GraphQL */ `
    type Query {
      hello: String!
    }
  `,
  resolvers: {
    Query: {
      hello: () => "world!",
    },
  },
});

Now using createYoga we can pass it that schema:

const yoga = createYoga({
  schema,
});

Finally we can pass the yoga instance to our Express.js app:

app.use("/graphql", yoga);

That's it! We now have a production-ready GraphQL server running at /graphql thanks to Express.js.