A server with GraphQL Yoga
Stand up a GraphQL server with graphql-yoga on Node: schema, resolvers, context, built-in GraphiQL, and a Fetch handler you can test offline.
A server with GraphQL Yoga
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- GraphQL Yoga is a GraphQL server built on the Fetch API: `createYoga({ schema })` returns a request handler that you can pass to Node's `http.createServer`, or call directly with `yoga.fetch`.
- `createSchema({ typeDefs, resolvers })` builds an executable schema from SDL and a resolver map, and fails at startup if the two disagree.
- One endpoint, `/graphql` by default, serves POST and GET operations, and a browser visiting it with an HTML `Accept` header gets the GraphiQL explorer.
- The `context` option builds per-request state, so a database handle and the current user reach every resolver.
- Yoga masks unexpected errors as `Unexpected error.` by default; throw a `GraphQLError` when you want the client to see the message.
The problem: a schema is not a server
You have SDL and resolvers. A GraphQL server also has to parse HTTP requests, validate documents against the schema, run the executor, serialise errors, speak the GraphQL over HTTP conventions, stream subscriptions, and ideally give you an explorer for development. graphql-js is the engine; it does not include any of that.
Yoga is the layer that does. It is built by The Guild on the web-standard Fetch API (Request in, Response out), which is why the same server runs on Node, Bun, Deno or a Workers runtime, and why testing it needs no port.
The whole server
Versions used: Node 26, graphql 17.1.0, graphql-yoga 6.1.0, better-sqlite3 13.2.0. Install, then save this as server.mjs. makeDb is a small helper that creates and seeds the SQLite database; it is written out in the next lesson.
import { createServer } from 'node:http';
import { createYoga, createSchema } from 'graphql-yoga';
import { makeDb } from './db.mjs';
const db = makeDb(); // an in-memory SQLite database with authors and posts, seeded
const typeDefs = /* GraphQL */ `
type Author { id: ID! name: String! }
type Post { id: ID! title: String! author: Author! }
type Query {
hello: String!
posts: [Post!]!
}
`;
const resolvers = {
Query: {
hello: () => 'Hello from Yoga',
posts: (_parent, _args, { db }) =>
db.prepare('SELECT * FROM posts ORDER BY id').all(),
},
Post: {
author: (post, _args, { db }) =>
db.prepare('SELECT * FROM authors WHERE id = ?').get(post.author_id),
},
};
const yoga = createYoga({
schema: createSchema({ typeDefs, resolvers }),
context: () => ({ db }),
});
createServer(yoga).listen(4000, () => {
console.log('Server is running on http://localhost:4000/graphql');
});
Run node server.mjs. Four ideas are in it:
createSchemajoins SDL and resolvers and checks them against each other, as in schema-first and code-first.createYogawraps the schema in an HTTP handler.createServer(yoga)works because the Yoga instance is a function that Node’shttpcan call with its own request and response objects.contextruns per request and putsdbwhere every resolver can read it, per context and resolver arguments.
Talking to it
With the server running on a seeded database, I sent a POST:
$ curl -s localhost:4000/graphql -H 'content-type: application/json' \
-d '{"query":"{ hello posts { title author { name } } }"}'
{"data":{"hello":"Hello from Yoga","posts":[{"title":"Post 1","author":{"name":"Grace"}}, ...
A GET with the query in the URL also works for queries:
$ curl -s 'localhost:4000/graphql?query=%7Bhello%7D'
{"data":{"hello":"Hello from Yoga"}}
Open http://localhost:4000/graphql in a browser and you get the GraphiQL explorer. I checked that a request with Accept: text/html returns a page titled Yoga GraphiQL; the same URL with a JSON content type runs an operation. If you followed your first query in GraphiQL, this is the same tool, served by your own process. Turn it off in production; the hardening lesson covers that.
Testing without a port
Because Yoga is a Fetch handler, you can call it as a function. Every example in this group of lessons was run this way, with no server listening:
const response = await yoga.fetch('http://localhost/graphql', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query: '{ hello }' }),
});
console.log(await response.json()); // { data: { hello: 'Hello from Yoga' } }
That is fast and needs no free port, which makes it a good basis for testing a GraphQL API.
Errors are masked by default
Throw a plain Error in a resolver and the client does not see its message:
{ "errors": [{ "message": "Unexpected error.", "path": ["throwsPlain"],
"extensions": { "code": "INTERNAL_SERVER_ERROR" } }] }
A message like connect ECONNREFUSED 10.0.0.5:5432 would tell an outsider your database address, so Yoga hides it and keeps the real error in the server logs. When you do want the client to read a message, throw a GraphQLError, optionally with an extensions.code:
import { GraphQLError } from 'graphql';
throw new GraphQLError('Upstream unavailable', { extensions: { code: 'UPSTREAM_DOWN' } });
I saw the same masking on a Cannot return null for non-nullable field violation, which Yoga also reported as Unexpected error.. Reading the server logs when a client sees that message is the first debugging step. The errors and partial responses lesson goes into more depth.
Where the plugins go
Yoga’s plugins array is how features attach: response caching, persisted operations, introspection control, defer and stream, rate limiting. The defer and stream lesson used useDeferStream() from it. Subscriptions over SSE worked in Yoga without any plugin at all.
What the video covers
The clip is a six-minute stretch of notJust.dev’s 3 hour 40 minute “Build and Deploy a GraphQL API using NodeJS” course, starting at the chapter “Setting up the basic Graphql-yoga server” (1:20:45) and ending where “Setting up the project file strucutre” begins (1:26:48). The video is from February 2024 and is sponsored by IBM StepZen. From its chapter titles, it sets up a Yoga server inside the course’s project; its code will differ in detail from the plain-Node server above, and I could not read a transcript. The same course continues into mutations and a MongoDB database, which is a different store from this lesson’s SQLite.
Where this fits
You have a running server with a context and a throwaway in-memory database. The next lesson designs the data access properly. Next: connecting a database.
Check yourself
What does `createYoga` return, and what can you do with it?
A request handler that works with the Fetch API. Pass it to `http.createServer`, or call `yoga.fetch(url, init)` in a test to run an operation with no network.
How do you get a database connection into every resolver?
Return it from the `context` function passed to `createYoga`; every resolver receives it as its third argument.
What does a browser see when it opens the GraphQL URL?
When the request asks for HTML, Yoga serves its GraphiQL page, titled Yoga GraphiQL, where you can write and run operations. Programmatic clients get JSON.
A resolver throws `new Error('connection refused')`. What does the client receive?
The message `Unexpected error.` with code `INTERNAL_SERVER_ERROR`. Yoga masks plain errors so internals do not leak; a `GraphQLError` passes its message through.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.