Skip to content
Development
Skill

/api-graphql-mercurius

GraphQL server for Fastify with Mercurius — loaders, subscriptions, federation, JIT compilation

From plugin
skills
26200 skills

Claude Code

$ npx -y skills add agents-inc/skills --skill api-graphql-mercurius --agent claude-code

SKILL.md

api-graphql-mercurius.SKILL.md
name: api-graphql-mercurius
description: GraphQL server for Fastify with Mercurius — loaders, subscriptions, federation, JIT compilation

GraphQL with Mercurius

> **Quick Guide:** Use Mercurius as a Fastify plugin for GraphQL APIs with built-in loader batching (solves N+1), JIT query compilation, subscriptions via WebSocket, and federation support. Register with `app.register(mercurius, { schema, resolvers, loaders })`. Loaders are Mercurius's killer feature: define them per-type to batch field resolution automatically. Use `jit: 1` to enable query compilation for production performance.

---

<critical_requirements>

CRITICAL: Before Using This Skill

**(You MUST define loaders for any field that fetches related data — loaders solve the N+1 problem automatically through batching)**

**(You MUST use named constants for all numeric values — JIT thresholds, query depth limits, port numbers)**

**(You MUST return an array from loaders matching the exact length and order of the `queries` parameter)**

**(You MUST use `fastify.graphql.pubsub.publish()` inside mutations to trigger subscriptions — not external pubsub directly)**

</critical_requirements>

---

**Auto-detection:** Mercurius, mercurius, app.graphql, fastify.graphql, mercurius loaders, mercurius subscription, pubsub.publish, pubsub.subscribe, @mercuriusjs/federation, @mercuriusjs/gateway, mercurius-codegen, MercuriusContext, graphql-jit, withFilter, preParsing, preValidation, preExecution, onResolution

**When to use:**

  • Building GraphQL APIs on Fastify (Mercurius is Fastify-native)
  • Need automatic batching/caching for N+1 query prevention (loader system)
  • Want JIT query compilation for production performance
  • Building federated GraphQL services with `@mercuriusjs/federation`
  • Need real-time subscriptions via WebSocket with built-in pubsub
  • Want GraphQL lifecycle hooks (preParsing, preValidation, preExecution, onResolution)

**When NOT to use:**

  • Not using Fastify (Mercurius is Fastify-only)
  • Need a framework-agnostic GraphQL server
  • Building a standalone schema-first design tool (use the schema library directly)
  • Simple REST endpoints without GraphQL requirements

**Key patterns covered:**

  • Plugin registration with schema, resolvers, and loaders
  • Loader system for batched data fetching (the core differentiator)
  • JIT compilation configuration for production performance
  • Subscriptions with built-in pubsub and `withFilter`
  • Federation services and gateway composition
  • TypeScript context typing with `MercuriusContext` augmentation
  • GraphQL lifecycle hooks for cross-cutting concerns

---

**Detailed Resources:**

  • [examples/core.md](examples/core.md) - Registration, resolvers, loaders, context, error handling, testing
  • [examples/subscriptions.md](examples/subscriptions.md) - Pubsub, subscription resolvers, withFilter, WebSocket config
  • [examples/federation.md](examples/federation.md) - Federated services, gateway, \_\_resolveReference as loader
  • [reference.md](reference.md) - Decision frameworks, hook lifecycle, plugin options, anti-patterns

---

<philosophy>

Philosophy

**Fastify-native GraphQL.** Mercurius is not a standalone server bolted onto Fastify — it is a Fastify plugin that deeply integrates with Fastify's lifecycle, encapsulation model, and plugin system. This means your GraphQL API inherits Fastify's performance characteristics and plugin architecture naturally.

**Loaders over DataLoader.** Instead of requiring a separate DataLoader library, Mercurius provides a built-in loader system. Loaders are defined per-type/per-field and receive batched queries automatically. This is simpler than manually instantiating DataLoader instances per-request and is the primary mechanism for solving the N+1 problem.

**JIT for production.** Mercurius uses graphql-jit to compile frequently-executed queries into optimized V8 functions. After a configurable threshold of executions, subsequent runs of the same query bypass the GraphQL execution engine entirely — delivering significant performance gains for repeated queries.

**Federation as a plugin.** Federation support is split into separate packages (`@mercuriusjs/federation` for services, `@mercuriusjs/gateway` for composition), keeping the core library lean for non-federated use cases.

</philosophy>

---

<patterns>

Core Patterns

Pattern 1: Plugin Registration

Register Mercurius as a Fastify plugin with schema (SDL string), resolvers, and optional loaders.

import Fastify from "fastify";
import mercurius from "mercurius";

const JIT_THRESHOLD = 1;
const SERVER_PORT = 3000;

const app = Fastify({ logger: true });

const schema = `
  type Query {
    user(id: ID!): User
    users: [User!]!
  }

  type User {
    id: ID!
    name: String!
    posts: [Post!]!
  }

  type Post {
    id: ID!
    title: String!
  }
`;

app.register(mercurius, {
  schema,
  resolvers,
  loaders,
  jit: JIT_THRESHOLD,
  graphiql: process.env.NODE_ENV !== "production",
});

**Why good:** JIT threshold as named constant, GraphiQL disabled in production, loaders passed at registration level alongside resolvers

> Full registration with context, error handling, and all options: [examples/core.md](examples/core.md)

---

Pattern 2: Loaders (N+1 Prevention)

Loaders are Mercurius's primary mechanism for batch data fetching. Define them per-type per-field. Each loader receives an array of `queries` (batched requests) and must return an array of results in the same order.

const loaders = {
  User: {
    async posts(
      queries: Array<{ obj: User; params: Record<string, unknown> }>,
      context: MercuriusContext,
    ) {
      const userIds = queries.map(({ obj }) => obj.id);
      const allPosts = await fetchPostsByUserIds(userIds);
      // Return array matching queries order
      return queries.map(({ obj }) =>
        allPosts.filter((post) => post.authorId === obj.id),
      );
    },
  },
};

**Why good:** Single bulk

Read more
@agents-inc
Ships withskills

The official skills marketplace for Agents Inc. 230+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?

Stars on GitHub

Momentum

stars in total
26
Star history of agents-inc/skills on GitHub, a chart by star-history.com

Other skills on skills.

ai-infrastructure-litellm

ai-infrastructure-lite…

LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking,…

@agents-inc@agents-incInstall Skill
ai-infrastructure-modal

ai-infrastructure-moda…

Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client…

@agents-inc@agents-incInstall Skill
ai-infrastructure-ollama

ai-infrastructure-olla…

Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output,…

@agents-inc@agents-incInstall Skill

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills10d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc12d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react1d252k
@facebook@facebookInstall Skill

Questions about api-graphql-mercurius.

Which coding agents can use api-graphql-mercurius?
api-graphql-mercurius installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.