extending graphql-yoga server with express middleware

2020-05-18

 | 

~2 min read

 | 

287 words

One of the benefits of using GraphQL-Yoga’s Server is its extensibility via Express middleware. Despite this being listed as one of the features, I didn’t really appreciate it until I had a need to use it.

For example, if you have a standard Express server and you want to add some middleware (need a refresher on middleware? I wrote some basics here), you might do something like:

server/index.js
const express = require('express')
const cookieParser = require('cookie-parser')
const customMiddleware = require('./customMiddleware')
const PORT = 3000;

const server = express()
server.use(cookieParser())
server.use(customMiddleware())
...
server.listen(PORT, () => console.log(`We're live on port: ${PORT}`)

With GraphQL-Yoga, it’s actually not that different thanks to the Prisma team’s implementation:

graphql-yoga/src/index.ts
export class GraphQLServer {
  express: express.Application  //...
}

The result is - if you want to use the same middleware we used above, but in the context of a GraphQL server, you could implement it as follows:

src/index.js
const { GraphQLServer } = require("graphql-yoga");
const cookieParser = require('cookie-parser')
require("dotenv").config();
const customMiddleware = require('./customMiddleware')
const Mutation = require("./resolvers/Mutation");
const Query = require("./resolvers/Query");
const db = require("./db");

// Create the GraphQL Yoga Server
function createServer() {
  return new GraphQLServer({
    typeDefs: "src/schema.graphql",
    resolvers: { Mutation, Query },
    resolverValidationOptions: {
      requireResolversForResolveType: false
    },
    context: req => ({ ...req, db })
  });
}
const server = createServer()
server.express.use(cookieParser())server.express.use(customMiddleware())...
server.start(res => console.log(`We're live on port ${res.port})

(For more on configuring the GraphQL Server itself, see here.)

(NB: The use of dotenv brings into scope any environment variables for use by the server. In this case, it’s presumed that a port number is included in the .env file)

And just like that, our GraphQL server (powered by GraphQL-Yoga) is using Express middleware! Nice!



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!