graphql-yoga 正在参加 2021 年度 OSC 中国开源项目评选,请投票支持!
graphql-yoga 在 2021 年度 OSC 中国开源项目评选 中已获得 {{ projectVoteCount }} 票,请投票支持!
2021 年度 OSC 中国开源项目评选 正在火热进行中,快来投票支持你喜欢的开源项目!
2021 年度 OSC 中国开源项目评选 >>> 中场回顾
graphql-yoga 获得 2021 年度 OSC 中国开源项目评选「最佳人气项目」 !
授权协议 MIT License
开发语言 Java
操作系统 跨平台
软件类型 开源软件
所属分类 大数据数据查询
地区 不详
投 递 者 首席测试
适用人群 未知
收录时间 2021-11-23



CircleCI npm version

Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience


  • Easiest way to run a GraphQL server: Sensible defaults & includes everything you need with minimal setup.
  • Includes Subscriptions: Built-in support for GraphQL subscriptions using WebSockets.
  • Compatible: Works with all GraphQL clients (Apollo, Relay...) and fits seamless in your GraphQL workflow.

graphql-yoga is based on the following libraries & tools:


  • GraphQL spec-compliant
  • File upload
  • GraphQL Subscriptions
  • TypeScript typings
  • GraphQL Playground
  • Extensible via Express middleware
  • Schema directives
  • Apollo Tracing
  • Accepts both application/json and application/graphql content-types
  • Runs everywhere: Can be deployed via now, up, AWS Lambda, Heroku etc.
  • Supports middleware out of the box.


yarn add graphql-yoga


Quickstart (Hosted demo)

import { GraphQLServer } from 'graphql-yoga'
// ... or using `require()`
// const { GraphQLServer } = require('graphql-yoga')

const typeDefs = `
  type Query {
    hello(name: String): String!

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}`,

const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))

To get started with graphql-yoga, follow the instructions in the READMEs of the examples.



constructor(props: Props): GraphQLServer

The props argument accepts the following fields:

Key Type Default Note
typeDefs String or Function or DocumentNode or array of previous null Contains GraphQL type definitions in SDL or file path to type definitions (required if schema is not provided *)
resolvers Object null Contains resolvers for the fields specified in typeDefs (required if schema is not provided *)
resolverValidationOptions Object null Object which controls the resolver validation behaviour (see "Generating a schema") for more information
schema Object null An instance of GraphQLSchema (required if typeDefs and resolvers are not provided *)
mocks Object or Boolean null Applies mocks to schema. Setting this to true will apply a default mock, however you can pass an object to customize the mocks similar to the resolvers map.
context Object or Function {} Contains custom data being passed through your resolver chain. This can be passed in as an object, or as a Function with the signature (req: ContextParameters) => any **
schemaDirectives Object null Apollo Server schema directives that allow for transforming schema types, fields, and arguments
middlewares array of Middleware [] A list of GraphQLMiddleware middleware.

(*) There are two major ways of providing the schema information to the constructor:

  1. Provide typeDefs and resolvers and omit the schema, in this case graphql-yoga will construct the GraphQLSchema instance using makeExecutableSchema from graphql-tools.
  2. Provide the schema directly and omit typeDefs and resolvers.

(**) Notice that the req argument is an object of the shape { request, response, connection } which either carries a request: Request property (when it's a Query/Mutation resolver), response: Response property (when it's a Query/Mutation resolver), or a connection: SubscriptionOptions property (when it's a Subscription resolver). Request is imported from Express.js. Response is imported from Express.js aswell. SubscriptionOptions is from the graphql-subscriptions package. SubscriptionOptions are getting the connectionParams automatically injected under SubscriptionOptions.context.[CONNECTION_PARAMETER_NAME]

Here is example of creating a new server:

const typeDefs = `
  type Query {
    hello(name: String): String!

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}`,

const server = new GraphQLServer({ typeDefs, resolvers })

start(options: Options, callback: ((options: Options) => void) = (() => null)): Promise<void>

Once your GraphQLServer is instantiated, you can call the start method on it. It takes two arguments: options, the options object defined above, and callback, a function that's invoked right before the server is started. As an example, the callback can be used to print information that the server has started.

The options object has the following fields:

Key Type Default Note
cors Object null Contains configuration options for cors
tracing Boolean or TracingOptions 'http-header' Indicates whether Apollo Tracing should be enabled or disabled for your server (if a string is provided, accepted values are: 'enabled', 'disabled', 'http-header')
port Number or String 4000 Determines the port your server will be listening on (note that you can also specify the port by setting the PORT environment variable)
endpoint String '/' Defines the HTTP endpoint of your server
subscriptions Object or String or false '/' Defines the subscriptions (websocket) endpoint for your server; accepts an object with subscription server options path, keepAlive, onConnect and onDisconnect; setting to false disables subscriptions completely
playground String or false '/' Defines the endpoint where you can invoke the Playground; setting to false disables the playground endpoint
defaultPlaygroundQuery String undefined Defines default query displayed in Playground.
uploads UploadOptions or false or undefined null Provides information about upload limits; the object can have any combination of the following three keys: maxFieldSize, maxFileSize, maxFiles; each of these have values of type Number; setting to false disables file uploading
https HttpsOptions or undefined undefined Enables HTTPS support with a key/cert
getEndpoint String or Boolean false Adds a graphql HTTP GET endpoint to your server (defaults to endpoint if true). Used for leveraging CDN level caching.
deduplicator Boolean true Enables graphql-deduplicator. Once enabled sending the header X-GraphQL-Deduplicate will deduplicate the data.
bodyParserOptions BodyParserJSONOptions BodyParserJSONOptions Defaults Allows pass through of body-parser options

Additionally, the options object exposes these apollo-server options:

Key Type Note
cacheControl Boolean Enable extension that returns Cache Control data in the response
formatError Number A function to apply to every error before sending the response to clients. Defaults to defaultErrorFormatter. Please beware, that if you override this, requestId and code on errors won't automatically be propagated to your yoga server
logFunction LogFunction A function called for logging events such as execution times
rootValue any RootValue passed to GraphQL execution
validationRules Array of functions Additional GraphQL validation rules to be applied to client-specified queries
fieldResolver GraphQLFieldResolver Specify a custom default field resolver function
formatParams Function A function applied to each query in a batch to format parameters before execution
formatResponse Function A function applied to each response after execution
debug boolean Print additional debug logging if execution errors occur
const options = {
  port: 8000,
  endpoint: '/graphql',
  subscriptions: '/subscriptions',
  playground: '/playground',

server.start(options, ({ port }) =>
    `Server started, listening on port ${port} for incoming requests.`,


See the original documentation in graphql-subscriptions.


Mocking the schema is straight forward, along wit

import { GraphqlServer, MockList } from 'graphql-yoga'

const typeDefs = `
  type Query {
    hello(name: String): String!
    listOfStrings: [String]

const mocks = {
  Query: () => ({
    hello: () => 'Hello World',
    listOfStrings: () => new MockList([2, 6]),

const server = new GraphQLServer({ typeDefs, mocks })



There are three examples demonstrating how to quickly get started with graphql-yoga:

  • hello-world: Basic setup for building a schema and allowing for a hello query.
  • subscriptions: Basic setup for using subscriptions with a counter that increments every 2 seconds and triggers a subscription.
  • fullstack: Fullstack example based on create-react-app demonstrating how to query data from graphql-yoga with Apollo Client 2.0.


Once your graphql-yoga server is running, you can use GraphQL Playground out of the box – typically running on localhost:4000. (Read here for more information.)



To deploy your graphql-yoga server with now, follow these instructions:

  1. Download Now Desktop
  2. Navigate to the root directory of your graphql-yoga server
  3. Run now in your terminal


To deploy your graphql-yoga server with Heroku, follow these instructions:

  1. Download and install the Heroku Command Line Interface (previously Heroku Toolbelt)
  2. Log in to the Heroku CLI with heroku login
  3. Navigate to the root directory of your graphql-yoga server
  4. Create the Heroku instance by executing heroku create
  5. Deploy your GraphQL server by executing git push heroku master

up (Coming soon 🔜 )

AWS Lambda (Coming soon 🔜 )


How does graphql-yoga compare to apollo-server and other tools?

As mentioned above, graphql-yoga is built on top of a variety of other packages, such as graphql.js, express and apollo-server. Each of these provides a certain piece of functionality required for building a GraphQL server.

Using these packages individually incurs overhead in the setup process and requires you to write a lot of boilerplate. graphql-yoga abstracts away the initial complexity and required boilerplate and lets you get started quickly with a set of sensible defaults for your server configuration.

graphql-yoga is like create-react-app for building GraphQL servers.

Can't I just setup my own GraphQL server using express and graphql.js?

graphql-yoga is all about convenience and a great "Getting Started" experience by abstracting away the complexity that comes when you're building your own GraphQL server from scratch. It's a pragmatic approach to bootstrap a GraphQL server, much like how create-react-app removes friction when first starting out with React.

Whenever the defaults of graphql-yoga are too tight a corset for you, you can simply eject from it and use the tooling it's built upon - there's no lock-in or any other kind of magic going on preventing you from doing this.

How to eject from the standard express setup?

The core value of graphql-yoga is that you don't have to write the boilerplate required to configure your express.js application. However, once you need to add more customized behaviour to your server, the default configuration provided by graphql-yoga might not suit your use case any more. For example, it might be the case that you want to add more custom middleware to your server, like for logging or error reporting.

For these cases, GraphQLServer exposes the express.Application directly via its express property:

Middleware can also be added specifically to the GraphQL endpoint route, by using:, myMiddleware())

Any middleware you add to that route, will be added right before the apollo-server-express middleware.

Help & Community Slack Status

Join our Slack community if you run into issues or have questions. We love talking to you!





{{o.pubDate | formatDate}}


{{parseInt(o.replyCount) | bigNumberTransform}}
{{parseInt(o.viewCount) | bigNumberTransform}}
{{o.pubDate | formatDate}}


{{parseInt(o.replyCount) | bigNumberTransform}}
{{parseInt(o.viewCount) | bigNumberTransform}}
undici < 5.7.1 存在CRLF序列注入漏洞
undici是一个HTTP/1.1客户端。在小于5.7.1的undici版本中,可以将 CRLF序列注入到 undici 中的请求标头中,从而引起http请求拆分漏洞。
CVE-2022-31150 MPS-2022-11180
2022-08-08 19:10
needle 存在Authorization请求头泄露漏洞
needle 是 一款流式传输的HTTP客户端 needle 没有对重定向后的请求头做过滤处理,会把第一次请求的 Authorization 请求头也传递到重定向后的服务,导致 Authorization 请求头泄露。 攻击者可利用该漏洞被动窃取用户的 Authorization 数据。
2022-08-08 19:10
Async 安全漏洞
Async是英国Caolan McMahon个人开发者的一个实用模块。用于使用异步 JavaScript。 Async 3.2.1 及之前版本存在安全漏洞,该漏洞源于 mapValues() 方法。攻击者可通过 mapValues() 方法获取权限。
CVE-2021-43138 MPS-2021-34434
2022-08-08 19:10
Mermaid 输入验证错误漏洞
Mermaid是一个应用软件。使用文本和代码创建图表和可视化。 Mermaid 8.13.8之前版本存在输入验证错误漏洞,攻击者可利用该漏洞通过恶意图表在阅读图表的机器上运行javascript代码。
CVE-2021-43861 MPS-2021-36986
2022-08-08 19:10
0 评论
0 收藏