graphql-codegen
GraphQL Code Generator for TypeScript. Generates typed operations, hooks, and document nodes from GraphQL schemas. Use for type-safe GraphQL in frontend. USE WHEN: user mentions "GraphQL Codegen", "generate GraphQL types", "GraphQL TypeScript", "typed GraphQL", "client preset", "React Query GraphQL", asks about "GraphQL code generation", "type-safe GraphQL client", "fragment masking" DO NOT USE FOR: REST API types - use `openapi-codegen` instead; tRPC - use `trpc` instead; GraphQL schema design - use `graphql` instead; Manual GraphQL queries without codegen
What this skill does
# GraphQL Code Generator Core Knowledge
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `graphql-codegen` for comprehensive documentation.
## Installation
```bash
npm install -D @graphql-codegen/cli @graphql-codegen/typescript \
@graphql-codegen/typescript-operations @graphql-codegen/client-preset
```
## Basic Configuration
```typescript
// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql',
documents: ['src/**/*.tsx', 'src/**/*.ts'],
ignoreNoDocuments: true,
generates: {
'./src/gql/': {
preset: 'client',
config: {
documentMode: 'string',
},
},
},
};
export default config;
```
## Run Generation
```bash
npx graphql-codegen
npx graphql-codegen --watch # Watch mode
```
## Client Preset (Recommended)
The client preset generates everything needed for type-safe GraphQL.
```typescript
// codegen.ts
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql',
documents: ['src/**/*.tsx'],
generates: {
'./src/gql/': {
preset: 'client',
plugins: [],
presetConfig: {
gqlTagName: 'gql',
fragmentMasking: { unmaskFunctionName: 'getFragmentData' },
},
},
},
};
```
### Usage
```typescript
import { gql } from '../gql';
import { useQuery } from '@apollo/client';
const GET_USER = gql(`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`);
function UserProfile({ id }: { id: string }) {
const { data, loading } = useQuery(GET_USER, {
variables: { id },
});
if (loading) return <Spinner />;
// data.user is fully typed
return <div>{data?.user?.name}</div>;
}
```
---
## TanStack Query Integration
```bash
npm install -D @graphql-codegen/typescript-react-query
```
```typescript
// codegen.ts
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql',
documents: ['src/**/*.graphql'],
generates: {
'./src/gql/index.ts': {
plugins: [
'typescript',
'typescript-operations',
'typescript-react-query',
],
config: {
fetcher: {
func: './fetcher#fetcher',
isReactHook: false,
},
reactQueryVersion: 5,
addInfiniteQuery: true,
},
},
},
};
```
### Fetcher
```typescript
// src/gql/fetcher.ts
export const fetcher = <TData, TVariables>(
query: string,
variables?: TVariables
): (() => Promise<TData>) => {
return async () => {
const response = await fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
body: JSON.stringify({ query, variables }),
});
const json = await response.json();
if (json.errors) {
throw new Error(json.errors[0].message);
}
return json.data;
};
};
```
### Generated Hooks Usage
```typescript
import { useGetUserQuery, useCreateUserMutation } from './gql';
function UserProfile({ id }: { id: string }) {
const { data, isLoading } = useGetUserQuery({ id });
const createMutation = useCreateUserMutation();
const handleCreate = () => {
createMutation.mutate({
input: { name: 'John', email: '[email protected]' },
});
};
if (isLoading) return <Spinner />;
return <div>{data?.user?.name}</div>;
}
```
---
## Fragment Colocation
```typescript
// components/UserAvatar.tsx
import { gql, FragmentType, getFragmentData } from '../gql';
export const USER_AVATAR_FRAGMENT = gql(`
fragment UserAvatar on User {
id
name
avatarUrl
}
`);
interface Props {
user: FragmentType<typeof USER_AVATAR_FRAGMENT>;
}
export function UserAvatar({ user }: Props) {
const data = getFragmentData(USER_AVATAR_FRAGMENT, user);
return <img src={data.avatarUrl} alt={data.name} />;
}
// Usage in parent query
const GET_USER = gql(`
query GetUser($id: ID!) {
user(id: $id) {
id
...UserAvatar
}
}
`);
```
---
## Production Readiness
### Schema Polling
```typescript
// codegen.ts
const config: CodegenConfig = {
schema: [
{
'http://localhost:4000/graphql': {
headers: {
Authorization: `Bearer ${process.env.GRAPHQL_TOKEN}`,
},
},
},
],
// ...
};
```
### Multiple Schemas
```typescript
const config: CodegenConfig = {
generates: {
'./src/gql/user-api/': {
schema: 'http://user-api:4000/graphql',
documents: ['src/features/user/**/*.tsx'],
preset: 'client',
},
'./src/gql/product-api/': {
schema: 'http://product-api:4001/graphql',
documents: ['src/features/product/**/*.tsx'],
preset: 'client',
},
},
};
```
### CI/CD Integration
```yaml
# .github/workflows/codegen.yml
name: GraphQL Codegen
on:
push:
paths:
- 'src/**/*.graphql'
- 'src/**/*.tsx'
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx graphql-codegen
- name: Check for changes
run: |
if [[ -n $(git status --porcelain src/gql) ]]; then
echo "Generated files changed"
exit 1
fi
```
### Package Scripts
```json
{
"scripts": {
"codegen": "graphql-codegen",
"codegen:watch": "graphql-codegen --watch"
}
}
```
### Checklist
- [ ] Schema source configured (URL or local)
- [ ] Documents path matches source files
- [ ] Client preset for optimal output
- [ ] Fetcher configured with auth
- [ ] Fragment colocation pattern
- [ ] Watch mode for development
- [ ] CI validation of generated code
- [ ] TypeScript strict mode compatible
## When NOT to Use This Skill
- REST API type generation (use `openapi-codegen` skill)
- tRPC type-safe APIs (use `trpc` skill)
- GraphQL schema design (use `graphql` skill)
- Non-TypeScript projects
- Simple GraphQL queries without type generation needs
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Solution |
|--------------|--------------|----------|
| Committing generated files to git | Merge conflicts, outdated types | Add to .gitignore, generate in CI |
| Not using client preset | Verbose configuration | Use client preset for modern setup |
| Ignoring schema changes | Type mismatches at runtime | Run codegen in watch mode during dev |
| Missing operationId or query names | Poor generated hook names | Name all queries/mutations |
| Not using fragments | Code duplication | Use fragments for reusable fields |
| Generating types only | Missing runtime validation | Combine with schema validation |
| Hardcoding schema URL | Environment coupling | Use env variables for schema source |
| Not versioning generator packages | Inconsistent output across team | Pin generator versions |
## Quick Troubleshooting
| Issue | Possible Cause | Solution |
|-------|----------------|----------|
| Generation fails | Invalid schema or documents | Validate schema, check GraphQL syntax |
| Type errors after generation | Schema/code mismatch | Regenerate types, check schema changes |
| Missing types | Documents path not matching files | Check documents glob pattern |
| Duplicate operation names | Same query name in multiple files | Use unique operation names |
| Fragment not found | Fragment not in documents | Include fragment file in documents |
| Hook not generated | Not using React Query plugin | Add typescript-react-query plugin |
| "Cannot find module './gql'" | Generation didn't run | Run `npm run codegen` |
| Slow generation | Too many documents | Optimize glob patterns, use ignoreNoDocuments |
| Type inference not working | Wrong import path | Import from generated gql folder |
## Reference Documentation
- [Client Preset](quick-ref/client-preset.md)
- [React Query Plugin](quick-ref/react-query.md)
- [Typed Document Node](quick-ref/typed-document-node.md)
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.