api-graphql-yoga

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GraphQL Yoga Patterns

GraphQL Yoga 模式

Quick Guide: Use
createYoga
+
createSchema
for a Fetch API-compatible GraphQL server that runs on any JS runtime. Yoga v5 uses Envelop for plugin composition, SSE for subscriptions by default, built-in error masking, and CORS out of the box. Import
GraphQLError
from
graphql
(not
graphql-yoga
) for intentional client-facing errors. Prefer Yoga-specific plugins over Envelop equivalents for HTTP-level optimizations.

<critical_requirements>
快速指南:使用
createYoga
+
createSchema
创建兼容Fetch API的GraphQL服务器,可在任意JS运行时运行。Yoga v5采用Envelop进行插件组合,默认使用SSE实现订阅功能,内置错误屏蔽,且开箱即支持CORS。如需向客户端暴露指定错误,请从
graphql
(而非
graphql-yoga
)导入
GraphQLError
。为实现HTTP层面的优化,优先选择Yoga专属插件而非Envelop等效插件。

<critical_requirements>

CRITICAL: Before Using This Skill

重要提示:使用本技能前须知

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type
, named constants)
(You MUST import
GraphQLError
from
'graphql'
, NOT from
'graphql-yoga'
-- it is the standard graphql-js export)
(You MUST prefer Yoga-specific plugins over Envelop equivalents -- Yoga plugins operate at the HTTP layer and can skip GraphQL execution entirely for cached/persisted results)
(You MUST use
createSchema
from
'graphql-yoga'
for schema-first -- passing raw
typeDefs
/
resolvers
objects directly to
createYoga
is not supported in v5)
(You MUST use named constants for all numeric values -- timeouts, TTLs, port numbers, limits)
</critical_requirements>

Auto-detection: GraphQL Yoga, graphql-yoga, createYoga, createSchema, createPubSub, Envelop, useResponseCache, useCSRFPrevention, usePersistedOperations, GraphQL subscriptions SSE, error masking, maskedErrors, graphql-ws, Yoga plugin hooks, onRequest, onParams
When to use:
  • Building a GraphQL server that needs to run on Node.js, Bun, Deno, or Cloudflare Workers
  • APIs requiring subscriptions via SSE (default) or WebSocket
  • Extending GraphQL execution with Envelop plugins (caching, auth, logging)
  • File uploads using the GraphQL Multipart Request spec
  • Production APIs needing error masking, CORS, and CSRF protection
When NOT to use:
  • REST-only APIs without GraphQL needs
  • Simple CRUD where a framework's built-in route handlers suffice
  • When you need a federated gateway (consider a dedicated gateway solution)
Key patterns covered:
  • Server setup with
    createYoga
    and
    createSchema
    (schema-first)
  • Type-safe context with generics on
    createYoga<ServerContext>
  • Envelop plugin system: lifecycle hooks, custom plugins, Yoga-specific plugins
  • Subscriptions: SSE (default), WebSocket via
    graphql-ws
    , built-in PubSub
  • Error masking and intentional
    GraphQLError
    exposure
  • File uploads with WHATWG
    File
    scalar
  • Production hardening: CORS, CSRF prevention, GraphQL Armor, logging
  • Cross-runtime deployment: Node.js, Bun, Deno, Cloudflare Workers
Detailed Resources:
  • examples/core.md - Server setup, schema, context, resolvers, cross-runtime deployment
  • examples/plugins.md - Envelop plugins, custom plugins, lifecycle hooks
  • examples/subscriptions.md - SSE, WebSocket, PubSub, filtering
  • examples/error-handling.md - Error masking, GraphQLError, custom masking
  • examples/production.md - CORS, CSRF, response caching, persisted operations, logging
  • reference.md - Decision frameworks, plugin reference, production checklist

<philosophy>
所有代码必须遵循CLAUDE.md中的项目规范(短横线命名法、命名导出、导入顺序、
import type
、命名常量)
(必须从
'graphql'
而非
'graphql-yoga'
导入
GraphQLError
——这是标准graphql-js导出)
(必须优先选择Yoga专属插件而非Envelop等效插件——Yoga插件在HTTP层运作,对于缓存/持久化结果可直接跳过GraphQL执行流程)
(对于Schema优先开发方式,必须使用
'graphql-yoga'
中的
createSchema
——在v5中不支持直接将原始
typeDefs
/
resolvers
对象传入
createYoga
)
(所有数值类型的值必须使用命名常量——超时时间、TTL、端口号、限制值等)
</critical_requirements>

自动检测关键词:GraphQL Yoga, graphql-yoga, createYoga, createSchema, createPubSub, Envelop, useResponseCache, useCSRFPrevention, usePersistedOperations, GraphQL subscriptions SSE, error masking, maskedErrors, graphql-ws, Yoga plugin hooks, onRequest, onParams
适用场景:
  • 构建可在Node.js、Bun、Deno或Cloudflare Workers上运行的GraphQL服务器
  • 需要通过SSE(默认)或WebSocket实现订阅功能的API
  • 使用Envelop插件扩展GraphQL执行流程(缓存、认证、日志)
  • 采用GraphQL Multipart Request规范实现文件上传
  • 需要错误屏蔽、CORS和CSRF保护的生产级API
不适用场景:
  • 仅需REST API而无需GraphQL的场景
  • 简单CRUD操作,使用框架内置路由处理器即可满足需求
  • 需要联邦网关的场景(请考虑专用网关解决方案)
涵盖的核心模式:
  • 使用
    createYoga
    和
    createSchema
    搭建服务器(Schema优先)
  • 通过
    createYoga<ServerContext>
    泛型实现类型安全的上下文
  • Envelop插件系统:生命周期钩子、自定义插件、Yoga专属插件
  • 订阅功能:SSE(默认)、基于
    graphql-ws
    的WebSocket、内置PubSub
  • 错误屏蔽与
    GraphQLError
    的定向暴露
  • 使用WHATWG
    File
    标量实现文件上传
  • 生产环境加固:CORS、CSRF防护、GraphQL Armor、日志记录
  • 跨运行时部署:Node.js、Bun、Deno、Cloudflare Workers
详细资源:
  • examples/core.md - 服务器搭建、Schema、上下文、解析器、跨运行时部署
  • examples/plugins.md - Envelop插件、自定义插件、生命周期钩子
  • examples/subscriptions.md - SSE、WebSocket、PubSub、过滤功能
  • examples/error-handling.md - 错误屏蔽、GraphQLError、自定义屏蔽规则
  • examples/production.md - CORS、CSRF、响应缓存、持久化操作、日志记录
  • reference.md - 决策框架、插件参考、生产环境检查清单

<philosophy>

Philosophy

设计理念

GraphQL Yoga is a batteries-included, Fetch API-compatible GraphQL server. Its core is built on the WHATWG Fetch API (
Request
/
Response
), making it runtime-agnostic -- the same server code deploys to Node.js, Bun, Deno, and edge runtimes. The Envelop plugin system provides composable middleware at both the HTTP and GraphQL execution layers.
Schema approach: Yoga is schema-library agnostic. Use
createSchema
(schema-first SDL), Pothos (code-first), or vanilla
graphql-js
-- anything that produces a
GraphQLSchema
works.
Plugin priority: When both an Envelop plugin and a Yoga-specific plugin exist for the same feature (caching, persisted operations, defer/stream), always choose the Yoga variant. Yoga plugins hook into the HTTP layer and can short-circuit before GraphQL execution begins, skipping parsing and validation entirely for cached or persisted results.
Error philosophy: All unexpected errors are masked by default in production. Intentional errors are thrown as
GraphQLError
from the
graphql
package -- these bypass masking and reach clients with their message and extensions intact.
</philosophy>
<patterns>
GraphQL Yoga是一款开箱即用、兼容Fetch API的GraphQL服务器。其核心基于WHATWG Fetch API(
Request
/
Response
),实现了运行时无关性——同一服务器代码可部署至Node.js、Bun、Deno及边缘运行时。Envelop插件系统提供了HTTP和GraphQL执行层的可组合中间件。
Schema方案:Yoga与Schema库无关。可使用
createSchema
(Schema优先SDL)、Pothos(代码优先)或原生
graphql-js
——任何能生成
GraphQLSchema
的方案均可。
插件优先级:当同一功能(缓存、持久化操作、延迟/流)同时存在Envelop插件和Yoga专属插件时,始终选择Yoga版本。Yoga插件挂钩HTTP层,可在GraphQL执行开始前直接短路,跳过解析和验证流程,直接返回缓存或持久化结果。
错误处理理念:生产环境中所有意外错误默认会被屏蔽。如需向客户端暴露指定错误,请从
graphql
包抛出
GraphQLError
——这类错误会绕过屏蔽机制,完整将消息和扩展信息传递给客户端。
</philosophy>
<patterns>

Core Patterns

核心模式

Pattern 1: Server Setup with createYoga

模式1:使用createYoga搭建服务器

Create a Yoga instance with
createSchema
for SDL-based schemas. The yoga instance IS a Fetch API handler -- pass it directly to any runtime's HTTP server.
typescript
import { createYoga, createSchema } from "graphql-yoga";
import { createServer } from "node:http";

const PORT = 4000;

const yoga = createYoga({
  schema: createSchema({
    typeDefs: /* GraphQL */ `
      type Query {
        greeting(name: String!): String!
      }
    `,
    resolvers: {
      Query: {
        greeting: (_, { name }) => `Hello, ${name}!`,
      },
    },
  }),
});

const server = createServer(yoga);
server.listen(PORT, () => {
  console.info(`Server running on http://localhost:${PORT}/graphql`);
});
Why good:
createSchema
wraps
makeExecutableSchema
, yoga instance is a standard Fetch handler, works on any runtime
See examples/core.md for complete setup, cross-runtime deployment, and type-safe context.

通过
createSchema
创建基于SDL的Schema,进而创建Yoga实例。Yoga实例本身就是一个Fetch API处理器——可直接传入任意运行时的HTTP服务器。
typescript
import { createYoga, createSchema } from "graphql-yoga";
import { createServer } from "node:http";

const PORT = 4000;

const yoga = createYoga({
  schema: createSchema({
    typeDefs: /* GraphQL */ `
      type Query {
        greeting(name: String!): String!
      }
    `,
    resolvers: {
      Query: {
        greeting: (_, { name }) => `Hello, ${name}!`,
      },
    },
  }),
});

const server = createServer(yoga);
server.listen(PORT, () => {
  console.info(`Server running on http://localhost:${PORT}/graphql`);
});
优势:
createSchema
封装了
makeExecutableSchema
,Yoga实例是标准Fetch处理器,可在任意运行时工作
完整搭建、跨运行时部署及类型安全上下文示例请查看examples/core.md。

Pattern 2: Type-Safe Context

模式2:类型安全上下文

Pass a generic to
createYoga
for server-specific context typing. The
context
factory receives
YogaInitialContext
(containing
request
and
params
) and returns your custom context.
typescript
import { createYoga, type YogaInitialContext } from "graphql-yoga";

interface ServerContext {
  req: IncomingMessage;
  res: ServerResponse;
}

const yoga = createYoga<ServerContext>({
  schema,
  context: async ({ request }: YogaInitialContext) => {
    const token = request.headers.get("authorization");
    return { user: token ? await verifyToken(token) : null };
  },
});
Why good: generic types flow to resolver context parameter,
request
uses standard Fetch API (not framework-specific
req
/
res
)
See examples/core.md for full context patterns.

通过向
createYoga
传递泛型,实现服务器特定上下文的类型定义。
context
工厂函数接收
YogaInitialContext
(包含
request
和
params
)并返回自定义上下文。
typescript
import { createYoga, type YogaInitialContext } from "graphql-yoga";

interface ServerContext {
  req: IncomingMessage;
  res: ServerResponse;
}

const yoga = createYoga<ServerContext>({
  schema,
  context: async ({ request }: YogaInitialContext) => {
    const token = request.headers.get("authorization");
    return { user: token ? await verifyToken(token) : null };
  },
});
优势:泛型类型会传递到解析器的上下文参数,
request
使用标准Fetch API(而非框架特定的
req
/
res
)
完整上下文模式请查看examples/core.md。

Pattern 3: Envelop Plugin System

模式3:Envelop插件系统

Plugins are passed in the
plugins
array. Use Yoga-specific plugins when available -- they operate at the HTTP layer and can skip GraphQL execution entirely.
typescript
import { createYoga } from "graphql-yoga";
import { useResponseCache } from "@graphql-yoga/plugin-response-cache";

const CACHE_TTL_MS = 2_000;

const yoga = createYoga({
  schema,
  plugins: [
    useResponseCache({
      session: () => null,
      ttl: CACHE_TTL_MS,
    }),
  ],
});
Why good: Yoga response cache skips parsing/validation for cached results (Envelop equivalent cannot), plugins compose without conflicts
See examples/plugins.md for custom plugins, lifecycle hooks, and all Yoga-specific plugins.

插件通过
plugins
数组传入。优先使用Yoga专属插件——它们在HTTP层运作,可直接跳过GraphQL执行流程。
typescript
import { createYoga } from "graphql-yoga";
import { useResponseCache } from "@graphql-yoga/plugin-response-cache";

const CACHE_TTL_MS = 2_000;

const yoga = createYoga({
  schema,
  plugins: [
    useResponseCache({
      session: () => null,
      ttl: CACHE_TTL_MS,
    }),
  ],
});
优势:Yoga响应缓存会跳过缓存结果的解析/验证(Envelop等效插件无法实现),插件组合无冲突
自定义插件、生命周期钩子及所有Yoga专属插件示例请查看examples/plugins.md。

Pattern 4: Subscriptions with SSE (Default)

模式4:基于SSE的订阅功能(默认)

Yoga uses Server-Sent Events by default for subscriptions -- no WebSocket setup needed. Use
AsyncGenerator
syntax in subscription resolvers.
typescript
const schema = createSchema({
  typeDefs: /* GraphQL */ `
    type Subscription {
      countdown(from: Int!): Int!
    }
  `,
  resolvers: {
    Subscription: {
      countdown: {
        subscribe: async function* (_, { from }) {
          for (let i = from; i >= 0; i--) {
            await new Promise((resolve) => setTimeout(resolve, 1_000));
            yield { countdown: i };
          }
        },
      },
    },
  },
});
Why good: no WebSocket infrastructure needed, works through HTTP proxies and load balancers,
graphql-sse
library for clients
See examples/subscriptions.md for PubSub, WebSocket setup, and filtering.

Yoga默认使用Server-Sent Events实现订阅功能——无需WebSocket配置。在订阅解析器中使用
AsyncGenerator
语法。
typescript
const schema = createSchema({
  typeDefs: /* GraphQL */ `
    type Subscription {
      countdown(from: Int!): Int!
    }
  `,
  resolvers: {
    Subscription: {
      countdown: {
        subscribe: async function* (_, { from }) {
          for (let i = from; i >= 0; i--) {
            await new Promise((resolve) => setTimeout(resolve, 1_000));
            yield { countdown: i };
          }
        },
      },
    },
  },
});
优势:无需WebSocket基础设施,可通过HTTP代理和负载均衡器工作,客户端使用
graphql-sse
库
PubSub、WebSocket配置及过滤功能示例请查看examples/subscriptions.md。

Pattern 5: Error Masking and GraphQLError

模式5:错误屏蔽与GraphQLError

Yoga masks all unexpected errors by default. Throw
GraphQLError
(from
graphql
) for intentional client-facing errors -- these bypass masking.
typescript
import { GraphQLError } from "graphql";

const NOT_FOUND_CODE = "USER_NOT_FOUND";

throw new GraphQLError("User not found", {
  extensions: { code: NOT_FOUND_CODE },
});
Why good: unexpected errors never leak internals (database details, stack traces), intentional errors pass through with message + extensions
See examples/error-handling.md for custom masking, disabling masking, and development mode.

Yoga默认屏蔽所有意外错误。如需向客户端暴露指定错误,请抛出
GraphQLError
(来自
graphql
包)——这类错误会绕过屏蔽机制。
typescript
import { GraphQLError } from "graphql";

const NOT_FOUND_CODE = "USER_NOT_FOUND";

throw new GraphQLError("User not found", {
  extensions: { code: NOT_FOUND_CODE },
});
优势:意外错误绝不会泄露内部细节(数据库信息、堆栈跟踪),指定错误可完整传递消息和扩展信息
自定义屏蔽规则、禁用屏蔽及开发模式示例请查看examples/error-handling.md。

Pattern 6: File Uploads

模式6:文件上传

Yoga supports the GraphQL Multipart Request spec. Add a
File
scalar and receive WHATWG
File
objects in resolvers.
typescript
const schema = createSchema({
  typeDefs: /* GraphQL */ `
    scalar File
    type Mutation {
      uploadFile(file: File!): Boolean!
    }
  `,
  resolvers: {
    Mutation: {
      uploadFile: async (_, { file }: { file: File }) => {
        const content = await file.arrayBuffer();
        // Process file content
        return true;
      },
    },
  },
});
Why good: uses standard WHATWG File API (same as browser), no extra packages needed, disable with
multipart: false
See examples/core.md for complete file upload patterns.
</patterns>
<decision_framework>
Yoga支持GraphQL Multipart Request规范。添加
File
标量后,可在解析器中接收WHATWG
File
对象。
typescript
const schema = createSchema({
  typeDefs: /* GraphQL */ `
    scalar File
    type Mutation {
      uploadFile(file: File!): Boolean!
    }
  `,
  resolvers: {
    Mutation: {
      uploadFile: async (_, { file }: { file: File }) => {
        const content = await file.arrayBuffer();
        // 处理文件内容
        return true;
      },
    },
  },
});
优势:使用标准WHATWG File API(与浏览器一致),无需额外包,可通过
multipart: false
禁用
完整文件上传模式请查看examples/core.md。
</patterns>
<decision_framework>

Decision Framework

决策框架

Schema Approach

Schema方案选择

Need auto-generated types from SDL?
+-- YES --> createSchema (schema-first with typeDefs + resolvers)
+-- NO  --> Want full TypeScript inference in schema definition?
    +-- YES --> Code-first library (e.g. Pothos) -- pass resulting GraphQLSchema to Yoga
    +-- NO  --> Vanilla graphql-js GraphQLSchema
是否需要从SDL自动生成类型?
+-- 是 --> 使用createSchema(Schema优先,基于typeDefs + resolvers)
+-- 否 --> 是否需要在Schema定义中实现完整TypeScript类型推断?
    +-- 是 --> 使用代码优先库(如Pothos)——将生成的GraphQLSchema传入Yoga
    +-- 否 --> 使用原生graphql-js GraphQLSchema

Subscription Transport

订阅传输方式选择

Need subscriptions?
+-- YES --> Do clients need bidirectional communication?
|   +-- YES --> WebSocket via graphql-ws (add ws + graphql-ws packages)
|   +-- NO  --> SSE (default, zero config, works through proxies)
+-- NO  --> No subscription setup needed
是否需要订阅功能?
+-- 是 --> 客户端是否需要双向通信?
|   +-- 是 --> 使用基于graphql-ws的WebSocket(需安装ws + graphql-ws包)
|   +-- 否 --> 使用SSE(默认,零配置,可通过代理工作)
+-- 否 --> 无需配置订阅功能

Plugin Selection

插件选择

Feature available as Yoga-specific plugin?
+-- YES --> Use Yoga plugin (HTTP-level hooks, can skip execution)
+-- NO  --> Use Envelop plugin (GraphQL execution-level hooks)
该功能是否有Yoga专属插件?
+-- 是 --> 使用Yoga插件(HTTP层钩子,可跳过执行流程)
+-- 否 --> 使用Envelop插件(GraphQL执行层钩子)

Yoga-Specific Plugins (Prefer Over Envelop)

Yoga专属插件(优先于Envelop)

PluginPackageWhy Yoga-specific
Response Cache
@graphql-yoga/plugin-response-cache
Skips execution for cached queries
Persisted Operations
@graphql-yoga/plugin-persisted-operations
Rejects unknown operations at HTTP layer
Defer/Stream
@graphql-yoga/plugin-defer-stream
Streams via HTTP chunked encoding
CSRF Prevention
@graphql-yoga/plugin-csrf-prevention
Requires custom header before parsing
GraphQL SSE
@graphql-yoga/plugin-graphql-sse
Single-connection SSE mode
</decision_framework>

<red_flags>
插件名称包名选择Yoga专属的原因
Response Cache
@graphql-yoga/plugin-response-cache
缓存查询可跳过执行流程
Persisted Operations
@graphql-yoga/plugin-persisted-operations
在HTTP层拒绝未知操作
Defer/Stream
@graphql-yoga/plugin-defer-stream
通过HTTP分块编码实现流传输
CSRF Prevention
@graphql-yoga/plugin-csrf-prevention
解析前需验证自定义标头
GraphQL SSE
@graphql-yoga/plugin-graphql-sse
单连接SSE模式
</decision_framework>

<red_flags>

RED FLAGS

注意事项

High Priority:
  • Importing
    GraphQLError
    from
    graphql-yoga
    instead of
    graphql
    -- wrong package, will fail
  • Passing
    typeDefs
    /
    resolvers
    object directly to
    createYoga
    without
    createSchema
    -- not supported in v5
  • Using an Envelop plugin when a Yoga-specific equivalent exists -- misses HTTP-level optimizations (the Yoga response cache skips parsing entirely; the Envelop equivalent cannot)
  • Throwing plain
    Error
    in resolvers expecting clients to see the message -- masked to "Unexpected error." in production
Medium Priority:
  • Not configuring CORS origins for production -- default is
    *
    , which should be locked down
  • Using in-memory PubSub across multiple server instances -- events won't propagate (use Redis-backed
    createRedisEventTarget
    )
  • Missing
    graphql
    peer dependency --
    graphql-yoga
    requires
    graphql
    as a peer, install both
  • Calling
    createSchema
    with no schema at all -- Yoga requires a schema; it does not infer one
Gotchas & Edge Cases:
  • YogaInitialContext.request
    is a Fetch API
    Request
    , not a Node.js
    IncomingMessage
    -- use
    request.headers.get()
    , not
    req.headers
  • Plugin execution order changed in v5 -- plugins added via
    addPlugin
    in
    onPluginInit
    now execute immediately after the adding plugin, not last
  • useResponseCache
    session
    callback must return a string (user ID) for PRIVATE scope or
    null
    for public -- returning
    undefined
    breaks caching
  • SSE subscriptions go through HTTP (text/event-stream) -- some proxies may buffer events; set
    X-Accel-Buffering: no
    for Nginx
  • File
    scalar in uploads gives you a WHATWG
    File
    object -- use
    .text()
    ,
    .arrayBuffer()
    , or
    .stream()
    methods (not Node.js
    Buffer
    directly)
  • Yoga's built-in GraphiQL is enabled by default -- disable with
    graphiql: false
    in production
  • maskedErrors
    set to
    false
    disables ALL masking including stack traces -- use custom
    maskError
    function instead for selective exposure
  • CORS
    credentials: true
    with
    origin: '*'
    is rejected by browsers per the Fetch spec -- specify exact origins
</red_flags>

<critical_reminders>
高优先级问题:
  • 从
    graphql-yoga
    而非
    graphql
    导入
    GraphQLError
    ——包错误,会导致运行失败
  • 未使用
    createSchema
    ,直接将
    typeDefs
    /
    resolvers
    对象传入
    createYoga
    ——v5不支持该方式
  • 存在Yoga专属插件时仍使用Envelop等效插件——错失HTTP层面优化(Yoga响应缓存可完全跳过解析;Envelop等效插件无法实现)
  • 在解析器中抛出普通
    Error
    并期望客户端看到错误消息——生产环境中会被屏蔽为"Unexpected error."
中优先级问题:
  • 生产环境未配置CORS源——默认值为
    *
    ,需锁定为指定源
  • 在多服务器实例中使用内存PubSub——事件无法跨实例传播(使用基于Redis的
    createRedisEventTarget
    )
  • 缺少
    graphql
    peer依赖——
    graphql-yoga
    需要
    graphql
    作为peer依赖,请同时安装两者
  • 调用
    createSchema
    时未传入任何Schema——Yoga必须指定Schema,无法自动推断
易踩坑点与边缘情况:
  • YogaInitialContext.request
    是Fetch API
    Request
    ,而非Node.js
    IncomingMessage
    ——使用
    request.headers.get()
    ,而非
    req.headers
  • v5中插件执行顺序已变更——通过
    onPluginInit
    中的
    addPlugin
    添加的插件现在会紧跟添加它的插件执行,而非最后执行
  • useResponseCache
    的
    session
    回调必须返回字符串(用户ID)以实现私有作用域,或返回
    null
    以实现公共作用域——返回
    undefined
    会导致缓存失效
  • SSE订阅通过HTTP(text/event-stream)传输——部分代理可能会缓冲事件;对于Nginx需设置
    X-Accel-Buffering: no
  • 文件上传中的
    File
    标量返回WHATWG
    File
    对象——使用
    .text()
    、
    .arrayBuffer()
    或
    .stream()
    方法(而非直接使用Node.js
    Buffer
    )
  • Yoga内置的GraphiQL默认启用——生产环境需通过
    graphiql: false
    禁用
  • 将
    maskedErrors
    设为
    false
    会禁用所有屏蔽,包括堆栈跟踪——如需选择性暴露,请使用自定义
    maskError
    函数
  • CORS设置
    credentials: true
    同时
    origin: '*'
    会被浏览器根据Fetch规范拒绝——请指定精确的源
</red_flags>

<critical_reminders>

CRITICAL REMINDERS

重要提醒

All code must follow project conventions in CLAUDE.md
(You MUST import
GraphQLError
from
'graphql'
, NOT from
'graphql-yoga'
-- it is the standard graphql-js export)
(You MUST prefer Yoga-specific plugins over Envelop equivalents -- Yoga plugins operate at the HTTP layer and can skip GraphQL execution entirely for cached/persisted results)
(You MUST use
createSchema
from
'graphql-yoga'
for schema-first -- passing raw
typeDefs
/
resolvers
objects directly to
createYoga
is not supported in v5)
(You MUST use named constants for all numeric values -- timeouts, TTLs, port numbers, limits)
Failure to follow these rules will cause import errors, missed performance optimizations, and information leakage through unmasked errors.
</critical_reminders>
所有代码必须遵循CLAUDE.md中的项目规范
(必须从
'graphql'
而非
'graphql-yoga'
导入
GraphQLError
——这是标准graphql-js导出)
(必须优先选择Yoga专属插件而非Envelop等效插件——Yoga插件在HTTP层运作,对于缓存/持久化结果可直接跳过GraphQL执行流程)
(对于Schema优先开发方式,必须使用
'graphql-yoga'
中的
createSchema
——在v5中不支持直接将原始
typeDefs
/
resolvers
对象传入
createYoga
)
(所有数值类型的值必须使用命名常量——超时时间、TTL、端口号、限制值等)
不遵循这些规则会导致导入错误、错失性能优化机会,以及通过未屏蔽的错误泄露信息。
</critical_reminders>