GraphQL With Mercurius

Schema-First, Fast, Subscriptions Built-In

GraphQL With Mercurius

Mercurius is the official GraphQL plugin for Fastify. It uses graphql-jit for compiled query execution and has first-class subscription support.

5 min read Level 3/5 #fastify#graphql#mercurius
What you'll learn
  • Install mercurius
  • Register with a schema and resolvers
  • Enable GraphiQL and subscriptions

Mercurius is the GraphQL plugin for Fastify, maintained by the core team. It uses graphql-jit to compile queries to JS functions — typically 3x faster than reference execution.

Install & Register

npm install mercurius graphql
import mercurius from 'mercurius'

const schema = `
  type User { id: ID!, email: String! }
  type Query { user(id: ID!): User }
`

const resolvers = {
  Query: {
    user: async (_: unknown, args: { id: string }) => {
      return app.db.user.findUnique({ where: { id: args.id } })
    },
  },
}

await app.register(mercurius, {
  schema,
  resolvers,
  graphiql: true,
})

GraphiQL is served at /graphiql; the GraphQL endpoint at /graphql. Disable GraphiQL in production with graphiql: false.

Subscriptions

const subscriptions = {
  Subscription: {
    userCreated: {
      subscribe: async (_: unknown, __: unknown, { pubsub }: any) => {
        return pubsub.subscribe('USER_CREATED')
      },
    },
  },
}

await app.register(mercurius, {
  schema,
  resolvers: { ...resolvers, ...subscriptions },
  subscription: true,
})

When a user is created elsewhere, publish via app.graphql.pubsub.publish({ topic: 'USER_CREATED', payload: { userCreated: user } }).

Federation & Loaders

Mercurius supports Apollo Federation, DataLoader-style batching via the loaders option, and persisted queries. Reach for those once a single graph is too coarse to scale.

GraphQL Codegen →