graphql-yoga
🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.
Top Related Projects
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
A reference implementation of GraphQL for JavaScript
Awesome list of GraphQL
Code-First, Type-Safe, GraphQL Schema Construction
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
Create a GraphQL HTTP server with Express.
Quick Overview
GraphQL Yoga is a fully-featured GraphQL server with focus on easy setup, performance, and great developer experience. It's built on top of popular libraries like Express, Apollo Server, and GraphQL Tools, providing a batteries-included solution for creating GraphQL servers.
Pros
- Easy to set up and use, with minimal configuration required
- Highly extensible with a plugin system
- Built-in support for subscriptions and file uploads
- Excellent TypeScript support and type safety
Cons
- May be overkill for very simple GraphQL server needs
- Learning curve for advanced features and customizations
- Dependency on multiple underlying libraries may lead to potential conflicts
- Performance might be slightly lower compared to bare-bones GraphQL implementations
Code Examples
- Creating a simple GraphQL server:
import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'
const yoga = createYoga({
schema: {
typeDefs: `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello from Yoga!'
}
}
}
})
const server = createServer(yoga)
server.listen(4000, () => {
console.log('Server is running on http://localhost:4000/graphql')
})
- Adding a subscription:
import { createPubSub } from 'graphql-yoga'
const pubSub = createPubSub()
const yoga = createYoga({
schema: {
typeDefs: `
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, 1000))
yield { countdown: i }
}
}
}
}
}
}
})
- Using plugins:
import { useResponseCache } from '@graphql-yoga/plugin-response-cache'
const yoga = createYoga({
plugins: [
useResponseCache({
// cache for 1 hour
ttl: 60 * 60 * 1000,
}),
],
// ... rest of your configuration
})
Getting Started
To get started with GraphQL Yoga, follow these steps:
-
Install the package:
npm install graphql-yoga
-
Create a new file (e.g.,
server.js
) and add the following code:import { createServer } from 'node:http' import { createYoga } from 'graphql-yoga' const yoga = createYoga({ schema: { typeDefs: ` type Query { hello: String } `, resolvers: { Query: { hello: () => 'Hello World!' } } } }) const server = createServer(yoga) server.listen(4000, () => { console.log('Server is running on http://localhost:4000/graphql') })
-
Run the server:
node server.js
-
Open your browser and navigate to
http://localhost:4000/graphql
to access the GraphQL playground.
Competitor Comparisons
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
Pros of Apollo Server
- More extensive documentation and community support
- Robust integration with Apollo ecosystem tools (Apollo Client, Apollo Studio)
- Advanced features like subscriptions and federation out-of-the-box
Cons of Apollo Server
- Heavier and more opinionated, which may lead to vendor lock-in
- Steeper learning curve for beginners
- Less flexibility in terms of server framework integration
Code Comparison
Apollo Server:
const { ApolloServer } = require('apollo-server');
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
GraphQL Yoga:
const { createServer } = require('graphql-yoga');
const server = createServer({ schema });
server.start(() => {
console.log('Server is running on http://localhost:4000');
});
Key Differences
- GraphQL Yoga is more lightweight and flexible, allowing easier integration with various server frameworks
- Apollo Server provides a more comprehensive ecosystem with additional tools and services
- GraphQL Yoga focuses on simplicity and ease of use, while Apollo Server offers more advanced features out-of-the-box
Use Cases
- Choose Apollo Server for large-scale applications requiring advanced features and tight integration with the Apollo ecosystem
- Opt for GraphQL Yoga in projects prioritizing simplicity, flexibility, and lightweight implementation
A reference implementation of GraphQL for JavaScript
Pros of graphql-js
- Reference implementation of GraphQL, ensuring high compatibility and adherence to specifications
- Extensive documentation and community support
- Flexible and can be integrated with various server frameworks
Cons of graphql-js
- Requires more setup and configuration for a complete GraphQL server
- Less opinionated, which may lead to more decision-making for developers
- Steeper learning curve for beginners
Code Comparison
graphql-js:
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'Hello, World!';
}
}
}
})
});
GraphQL Yoga:
import { createServer } from '@graphql-yoga/node'
const server = createServer({
schema: {
typeDefs: `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello, World!'
}
}
}
})
GraphQL Yoga provides a more streamlined setup process with sensible defaults, making it easier for developers to get started quickly. However, graphql-js offers more granular control and is ideal for complex, custom implementations. Both libraries are actively maintained and have their strengths depending on the project requirements and developer preferences.
Awesome list of GraphQL
Pros of awesome-graphql
- Comprehensive resource collection for GraphQL, covering various aspects and tools
- Community-driven project with contributions from many developers
- Regularly updated with new resources and tools
Cons of awesome-graphql
- Not a functional library or tool, but rather a curated list of resources
- May require additional effort to evaluate and choose appropriate tools for specific needs
- Can become overwhelming due to the large number of resources listed
Code comparison
Not applicable, as awesome-graphql is a curated list of resources and does not contain code examples.
graphql-yoga, on the other hand, is a functional GraphQL server library. Here's a basic example of setting up a GraphQL server with graphql-yoga:
import { createServer } from 'graphql-yoga'
const server = createServer({
schema: {
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello from Yoga!'
}
}
}
})
server.start()
While awesome-graphql serves as a valuable resource for learning about and discovering GraphQL tools, graphql-yoga provides a practical implementation of a GraphQL server with additional features and optimizations.
Code-First, Type-Safe, GraphQL Schema Construction
Pros of Nexus
- Strong TypeScript integration with auto-generated types
- Declarative schema definition with code-first approach
- Powerful plugin system for extending functionality
Cons of Nexus
- Steeper learning curve for developers new to code-first GraphQL
- Less flexibility in schema customization compared to SDL-first approaches
- Potentially more verbose schema definitions for simple use cases
Code Comparison
Nexus schema definition:
import { objectType, queryType, makeSchema } from '@nexus/schema'
const User = objectType({
name: 'User',
definition(t) {
t.string('id')
t.string('name')
},
})
const Query = queryType({
definition(t) {
t.list.field('users', {
type: 'User',
resolve: () => [{ id: '1', name: 'Alice' }],
})
},
})
const schema = makeSchema({
types: [Query, User],
})
GraphQL Yoga schema definition:
import { createSchema } from 'graphql-yoga'
const schema = createSchema({
typeDefs: `
type User {
id: ID!
name: String!
}
type Query {
users: [User!]!
}
`,
resolvers: {
Query: {
users: () => [{ id: '1', name: 'Alice' }],
},
},
})
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
Pros of Graffle
- Lightweight and minimalistic approach to GraphQL server implementation
- Focuses on simplicity and ease of use for basic GraphQL setups
- Potentially faster setup time for simple projects
Cons of Graffle
- Less feature-rich compared to GraphQL Yoga
- Smaller community and ecosystem support
- May require additional libraries or custom code for advanced use cases
Code Comparison
GraphQL Yoga:
import { createServer } from 'graphql-yoga'
const server = createServer({
schema: mySchema,
context: myContext
})
server.start()
Graffle:
import { createServer } from 'graffle'
const server = createServer({
schema: mySchema,
context: myContext
})
server.listen(4000)
Summary
Graffle offers a more streamlined approach to setting up a GraphQL server, which can be beneficial for smaller projects or those requiring a quick setup. However, GraphQL Yoga provides a more comprehensive set of features and broader community support, making it potentially more suitable for larger or more complex applications. The code comparison shows that both libraries have similar basic usage patterns, but GraphQL Yoga's ecosystem and additional features may offer more flexibility for advanced use cases.
Create a GraphQL HTTP server with Express.
Pros of express-graphql
- Lightweight and simple to set up
- Directly integrates with Express.js
- Well-established and maintained by the GraphQL Foundation
Cons of express-graphql
- Limited built-in features compared to GraphQL Yoga
- Requires more manual configuration for advanced use cases
- Less flexibility in terms of server frameworks and plugins
Code Comparison
express-graphql:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const app = express();
app.use('/graphql', graphqlHTTP({
schema: MyGraphQLSchema,
graphiql: true,
}));
GraphQL Yoga:
import { createServer } from '@graphql-yoga/node'
const server = createServer({
schema: MyGraphQLSchema,
graphiql: true,
})
server.start()
GraphQL Yoga offers a more modern and flexible approach, with built-in support for various features like file uploads, subscriptions, and CORS. It also provides a plugin system for easy extensibility. express-graphql, on the other hand, is more focused on providing a simple integration with Express.js and relies on additional libraries for advanced features.
While express-graphql is a solid choice for basic GraphQL setups, GraphQL Yoga offers more out-of-the-box functionality and easier configuration for complex use cases. The choice between the two depends on project requirements and developer preferences.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
GraphQL Yoga
Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience
Go to documenation
Quick start
Install
pnpm add graphql-yoga graphql
Start
Make a schema, create Yoga and start a Node server:
import { createServer } from 'node:http'
import { createSchema, createYoga } from 'graphql-yoga'
const yoga = createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello from Yoga!'
}
}
})
})
const server = createServer(yoga)
server.listen(4000, () => {
console.info('Server is running on http://localhost:4000/graphql')
})
Overview
- Easiest way to run a GraphQL server: Sensible defaults & includes everything you need with minimal setup (we also export a platform/env-agnostic handler so you can build your own wrappers easily).
- Includes Subscriptions: Built-in support for GraphQL subscriptions using Server-Sent Events.
- Compatible: Works with all GraphQL clients (Apollo, Relay, Urql...) and fits seamless in your GraphQL workflow.
- WHATWG Fetch API: the core package depends on WHATWG Fetch API so it can run and deploy on any environment (Serverless, Workers, Deno, Node).
- Easily Extendable: New GraphQL-Yoga support all
envelop
plugins.
Features
- Fully typed with TypeScript
- GraphQL over HTTP spec compliant
- GraphiQL included
- File uploads with GraphQL Multipart Request spec
- Subscriptions and realtime capabilities
- Automatic persisted queries
- Built-in parsing and validation caching
- Testing utilities
- Supports ESM
- Runs everywhere, including environments like:
- And more...
Documentation
Our documentation website will help you get started.
Examples
We've made sure developers can quickly start with GraphQL Yoga by providing a comprehensive set of
examples.
See all of them in the examples/
folder.
Comparison
Read more about how GraphQL Yoga compares to other servers in the ecosystem here.
Contributing
If this is your first time contributing to this project, please do read our Contributor Workflow Guide before you get started off.
For this project in particular, to get started on stage/2-failing-test
:
- Install Node.js
- Run in your terminal:
npm i -g pnpm@8 && pnpm install && pnpm build
- Add tests to
packages/graphql-yoga/__tests__
using Jest APIs - Run the tests with
pnpm test
Feel free to open issues and pull requests. We're always welcome support from the community.
Code of Conduct
Help us keep Yoga open and inclusive. Please read and follow our Code of Conduct as adopted from Contributor Covenant.
License
MIT
Top Related Projects
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
A reference implementation of GraphQL for JavaScript
Awesome list of GraphQL
Code-First, Type-Safe, GraphQL Schema Construction
Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
Create a GraphQL HTTP server with Express.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot