Javascript-Graphql yoga @graphql-yoga/[email protected]: Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience

icon
Latest Release: @graphql-yoga/[email protected]

Patch Changes

  • 3d54829: enhance: move W3C changes
  • Updated dependencies [3d54829]
Source code(tar.gz)
Source code(zip)

graphql-yoga

CircleCI npm version

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

Overview

  • 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:

Features

  • 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.

Install

yarn add graphql-yoga

Usage

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.

API

GraphQLServer

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 }) =>
  console.log(
    `Server started, listening on port ${port} for incoming requests.`,
  ),
)

PubSub

See the original documentation in graphql-subscriptions.

mocking

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 })

Endpoints

Examples

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.

Workflow

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.)

Deployment

now

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

Heroku

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 ? )

FAQ

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:

server.express.use(myMiddleware())

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

server.express.post(server.options.endpoint, 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!

Prisma

Comments

  • undefined headers in yoga server's context
    undefined headers in yoga server's context

    Jan 17, 2022

    When I try to access headers I get undefined. Here is the CodeSandbox.

    The issue is mentioned as well in this issue.

    Reply
  • fix(common): Fix missing mimetype issue in uploaded files via Fastify
    fix(common): Fix missing mimetype issue in uploaded files via Fastify

    Jan 18, 2022

    null

                                                                                                                                                                                                           
    Reply
  • fix(deps): update dependency framer-motion to v6
    fix(deps): update dependency framer-motion to v6

    Jan 19, 2022

    WhiteSource Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | framer-motion | ^5.3.3 -> ^6.0.0 | age | adoption | passing | confidence |


    Release Notes

    framer/motion

    v6.2.1

    Compare Source

    Added
    • Ensure useReducedMotion detects reduced motion on load.

    v6.2.0

    Compare Source

    Added
    • reducedMotion option to MotionConfig.

    v6.1.0

    Compare Source

    Added
    • Added viewport.fallback option to disable IntersectionObserver polyfill.

    v6.0.0

    Compare Source

    Changed
    • framer-motion/three is now framer-motion-3d.

    Configuration

    ? Schedule: At any time (no schedule defined).

    ? Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    ? Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by WhiteSource Renovate. View repository job log here.

    dependencies 
    Reply
  • chore(deps): update babel monorepo
    chore(deps): update babel monorepo

    Jan 19, 2022

    WhiteSource Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | @babel/core (source) | 7.16.7 -> 7.16.10 | age | adoption | passing | confidence | | @babel/preset-env (source) | 7.16.8 -> 7.16.11 | age | adoption | passing | confidence |


    Release Notes

    babel/babel (@​babel/core)

    v7.16.10

    Compare Source

    :bug: Bug Fix
    :house: Internal
    :microscope: Output optimization
    • babel-helper-create-class-features-plugin, babel-preset-env
    babel/babel (@​babel/preset-env)

    v7.16.11

    Compare Source

    v7.16.11 (2022-01-20)

    This empty releases force-publishes a new version of @babel/plugin-proposal-private-methods (which was not published in v7.16.10 because it didn't have any actual change) and of @babel/preset-env.

    This solves an incompatibility between @babel/[email protected] and @babel/[email protected], by making sure that @babel/preset-env transitively depends on @babel/[email protected]^7.16.10.

    v7.16.10

    Compare Source

    :bug: Bug Fix
    :house: Internal
    :microscope: Output optimization
    • babel-helper-create-class-features-plugin, babel-preset-env

    Configuration

    ? Schedule: At any time (no schedule defined).

    ? Automerge: Disabled due to failing status checks.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    ? Immortal: This PR will be recreated if closed unmerged. Get config help if that's undesired.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by WhiteSource Renovate. View repository job log here.

    dependencies 
    Reply
  • use pnpm instead of yarn
    use pnpm instead of yarn

    Jan 20, 2022

    we often have super weird dependency issues and cryptic errors with yarn. Let's try if pnpm is the better alternative.

    dependencies 
    Reply
  • Update: yoga apha6 & sveltekit next.234
    Update: yoga apha6 & sveltekit next.234

    Jan 21, 2022

    null

                                                                                                                                                                                                           
    Reply
  • Update to graphql 0.13.0 crashes subscriptions
    Update to graphql 0.13.0 crashes subscriptions

    Feb 11, 2018

    Update:

    Add the following to your package.json and run yarn install. This should fix the problem:

      "resolutions": {
        "graphql": "0.13.1"
      }
    

    After updating to graphql-yoga to 1.2.5 subscriptions are not working anymore because of duplicated graphql version. And a lot of warnings are throwing on yarn installation -> i think that the deps are not compatible with 0.13.0

    warning "graphql-yoga > [email protected]" has incorrect peer dependency "[email protected] - 0.12".
    warning "graphql-yoga > [email protected]" has incorrect peer dependency "[email protected]^0.10.5 || ^0.11.3 || ^0.12.0".
    warning "graphql-yoga > [email protected]" has incorrect peer dependency "[email protected]^0.11.0 || ^0.12.0".
    warning "graphql-yoga > [email protected]" has incorrect peer dependency "[email protected]^0.10.0 || ^0.11.0 || ^0.12.0".
    warning "graphql-yoga > apollo-server-express > [email protected]" has incorrect peer dependency "[email protected]^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0".
    warning "graphql-yoga > apollo-server-express > apollo-server-core > [email protected]" has incorrect peer dependency "[email protected]^0.10.0 || ^0.11.0 || ^0.12.0".
    warning "graphql-yoga > apollo-server-express > apollo-server-core > [email protected]" has incorrect peer dependency "[email protected]^0.10.0 || ^0.11.0 || ^0.12.0".
    warning "graphql-yoga > apollo-server-express > apollo-server-core > [email protected]" has incorrect peer dependency "[email protected]^0.10.0 || ^0.11.0 || ^0.12.0".
    

    Cannot use GraphQLSchema “[object Object]” from another module or realm.↵↵Ensure that there is only one instance of “graphql” in the node_modules↵directory. If different versions of “graphql” are the dependencies of other↵relied on modules, use “resolutions” to ensure only one version is installed.↵↵https://yarnpkg.com/en/docs/selective-version-resolutions↵↵Duplicate “graphql” modules cannot be used at the same time since different↵versions may have different capabilities and behavior. The data from one↵version used in the function from another could produce confusing and↵spurious results.

    Reply
  • Subscriptions fire multiple times
    Subscriptions fire multiple times

    Jan 10, 2018

    I have an issue where the subscriptions are firing multiple times per event when they should only fire once. The number of times the subscriptions fire increases the more requests the server receives.

    The issue can be reproduced with this project: https://github.com/howtographql/react-apollo/tree/gc-1.0

    status/pr-welcome 
    Reply
  • Integrate graphql-crunch
    Integrate graphql-crunch

    May 3, 2018

    Just came across this tweet and could not resist from sharing:

    screen shot 2018-05-03 at 07 29 45

    I haven't tested graphql-crunch myself, but it appears to be a great tool doing a similar job to graphql-deduplicator, which is a part of graphql-yoga already.

    Adding graphql-crunch to Apollo Server and Apollo Client is very similar to how this is done for graphql-deduplicator, according to the README. It can also become graphql-yoga's built-in feature that gets triggered by a flag and thus save gigabytes of bandwidth worldwide ?

    WDYT of graphql-crunch? I'll be happy to submit a PR that adds it if there is interest ?

    Reply
  • Ability / documentation to add Apollo Engine
    Ability / documentation to add Apollo Engine

    Nov 21, 2017

    There is a rather lengthy list of steps to add Apollo Engine to an Apollo Express server. I think this is a great opportunity to abstract those steps into something much easier to implement.

    area/readme 
    Reply
  • The future of GraphQL Yoga
    The future of GraphQL Yoga

    Sep 23, 2018

    It's been almost 4 weeks since release of graphql-js v14. There's plenty of PRs with deps update but the last commit on this repo was 26 days ago.

    I've tried to update the deps in my project but graphql-yoga is still in 0.13.x ecosystem which results in plenty of errors like this:

    npm WARN [email protected] requires a peer of [email protected] - 0.13.x but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected] || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.9.0 || ^0.10.0 || ^0.11.0
    || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected] - 0.13.x but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.13.1 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.11.0 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.11.0 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected] - 0.13.x but none is
    installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.11.0 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.13.2 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.13.2 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.10.5 || ^0.11.3 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN [email protected] requires a peer of [email protected]^0.13.0 but none is installed. You must install peer dependencies yourself.
    

    I also get famous Cannot use GraphQLSchema "[object GraphQLSchema]" from another module or realm. error while trying to use the subscriptions. And it also rejects to compile new GraphQLServer({ schema }) in TypeScript as there's a conflict of GraphQLSchema typings between 0.13 and 14.0 ?

    I would like to create a PR to fix that and upgrade the deps but someone has to merge it then ?

    kind/discussion status/stale 
    Reply
  • Upgrade apollo-engine to 1.0.1
    Upgrade apollo-engine to 1.0.1

    Mar 13, 2018

    Related: #206

    Just for sharing and discussing.

    TODO:

    • [x] Split start in two functions to avoid this server.start({autoStart: false}) pattern
    • [x] Understand and fix why the subscriptions are not working with apollo-engine

    BTW, it can be nice to add a prettier in this project, my VSCode reformat everything without my permission…

    Please note that you need to npm link or yarn link with the local version of graphql-yoga to try ? (it can be obvious, but just in case ^^)

    Reply