Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Getting Started

Setting Up a Server: Express, Apollo Server and Yoga

Set up a GraphQL server in Node.js step by step: install, write typeDefs and resolvers, start Apollo Server or GraphQL Yoga, mount on Express, and test the endpoint with curl.

You have written queries and read the schema language. Now it is time to see what a GraphQL server is made of in practice. The good news: there is very little to it. A server needs three ingredients, a schema (the types, usually as SDL text), resolvers (functions that produce the data) and an HTTP endpoint that accepts GraphQL requests and hands them to an execution engine. Libraries such as Apollo Server and GraphQL Yoga package the last two, so your job is to supply the first two and decide how to mount them.

This lesson shows three setups (Apollo Server standalone, Apollo Server mounted on Express, and GraphQL Yoga), explains what each line does, and then makes the whole pipeline visible with a runnable stand-in. Nothing on this site can install npm packages, so the real library code is read-only and the stand-ins use a miniature engine written in plain JavaScript. The stand-in engine is not graphql-js; it supports only a small query subset, but the structure around it (schema, resolvers, endpoint, tests) is the same one you will write for real.

A server is three ingredients

Schema typeDefs written in SDL.
Resolvers Functions that fetch the data.
Endpoint One HTTP route, usually /graphql.

Libraries supply the engine and the endpoint.

1 / 2

The schema and resolvers

These two objects are the heart of every setup, and they do not change between libraries. Here is a small catalogue:

JavaScript
const typeDefs = `#graphql
  type Query {
    hello: String!
    book(id: ID!): Book
    books: [Book!]!
  }
  type Book {
    id: ID!
    title: String!
    author: Author!
  }
  type Author {
    name: String!
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello, GraphQL',
    book: (_parent, { id }) => books.find((b) => b.id === id),
    books: () => books,
  },
  Book: {
    author: (book) => authors[book.authorId],
  },
};

The #graphql comment after the opening backtick is a hint that editors use to highlight the string as SDL. The resolver map mirrors the schema: a key per type, a function per field, each receiving (parent, args, context, info), as explained in Resolvers. Fields without a resolver (Book.title) use the default, which reads the property of the parent object.

Apollo Server, standalone

The quickest start has no web framework at all. Install @apollo/server and graphql, and make sure your package.json has "type": "module" so import works:

Terminal
npm init -y
npm pkg set type=module
npm install @apollo/server graphql
JavaScript
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

const server = new ApolloServer({ typeDefs, resolvers });

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
  context: async ({ req }) => ({ token: req.headers.authorization ?? null }),
});

console.log(`Ready at ${url}`);

Run it with node server.js, open http://localhost:4000 in a browser and, in development, you land on an explorer (see GraphiQL, Playground and Sandbox Tools). The server answers POST / with GraphQL requests. The context function runs for every request; whatever it returns is the third argument of every resolver, which is the place to put the current user, database handles and DataLoaders.

Apollo Server on Express

Real applications usually have more than GraphQL: a health check, webhooks, maybe REST routes. Mount the GraphQL endpoint on an Express app so they share one process and one port. Install express, cors and the Express integration, then:

JavaScript
import express from 'express';
import http from 'node:http';
import cors from 'cors';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';

const app = express();
const httpServer = http.createServer(app);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();

app.get('/health', (_req, res) => res.send('ok'));

app.use(
  '/graphql',
  cors({ origin: ['https://app.example'] }),
  express.json(),
  expressMiddleware(server, {
    context: async ({ req }) => ({ token: req.headers.authorization ?? null }),
  }),
);

httpServer.listen(4000, () => console.log('http://localhost:4000/graphql'));

Four details matter:

  • await server.start() comes before mounting. The middleware refuses to work on a server that has not started.
  • Order of middleware matters. CORS first (so preflight requests are answered), then express.json() (so req.body exists), then the GraphQL middleware. If the body parser comes after the GraphQL handler, the handler sees no body.
  • The drain plugin lets the server finish in-flight requests when you shut down, instead of cutting them off.
  • The import path depends on the version. Apollo Server 4 shipped its Express integration as @apollo/server/express4; Apollo Server 5 moved it into the separate @as-integrations/express5 package used above. Check the current Apollo documentation for the pair that matches your Express version.

GraphQL Yoga

GraphQL Yoga (from The Guild) is built on the standard Fetch API (Request and Response), so it runs on Node, Bun, Deno, Cloudflare Workers and more. The Node setup is shorter than the others:

JavaScript
import { createServer } from 'node:http';
import { createYoga, createSchema } from 'graphql-yoga';

const yoga = createYoga({
  schema: createSchema({ typeDefs, resolvers }),
  context: ({ request }) => ({ token: request.headers.get('authorization') }),
});

createServer(yoga).listen(4000, () => {
  console.info('http://localhost:4000/graphql');
});

yoga is itself a request handler, so you can also mount it on Express with app.use(yoga.graphqlEndpoint, yoga). Yoga serves GraphiQL in development at the same URL. Options differ (for example how to switch the IDE off), so use its documentation rather than assuming they match Apollo's.

Which one should you pick? Apollo Server is the most widely used and pairs with Apollo's federation and client tooling. Yoga is lighter, standards-based and plugin-friendly. The schema and resolvers are portable between them, so the choice is rarely permanent.

Stand-in: schema, resolvers and an endpoint

The stand-in below puts all three ingredients in one file. The first part is a miniature engine (parse the SDL into a type map, parse a query subset, execute it against resolvers). In real life the graphql package does this job. The second part is exactly what you would give a real library: typeDefs and resolvers. The third part is the HTTP endpoint on the loopback address, followed by fetch calls that play the role of curl.

Node.js A complete server in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the status codes. A query the engine can run returns 200. An unknown field is a validation failure, so the whole request gets 400 and no data. Broken JSON never reaches the engine. In real servers these checks are done by the library before your resolvers run; see GraphQL over HTTP for the exact rules.

Stand-in: mounting and middleware order

The second stand-in focuses on the Express part: why the order of app.use arguments matters. It builds a miniature Express (path-matched middleware run in registration order) and a stand-in for expressMiddleware that needs req.body and builds context from a header. It runs the correct order and the wrong one against a real loopback server.

Node.js Middleware order on the /graphql route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With the right order, the CORS header is present, the JSON body is parsed, and the token in the Authorization header reaches the "resolver" through the context function. With the body parser mounted after the handler, the handler receives no body, which is the classic "Missing query" symptom when GraphQL is set up on Express.

Testing the endpoint

Once a real server runs, test it with the tools from the previous lesson or with curl:

Terminal
curl -X POST http://localhost:4000/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ hello }"}'

Expected response: {"data":{"hello":"Hello, GraphQL"}}. Add -H "Authorization: Bearer ..." to see the context at work, and send a deliberately wrong query to see the error format. Later, Testing GraphQL APIs shows how to test without any network at all, by calling the server's execute function directly.

A short checklist for a first server

  • Keep typeDefs and resolvers in their own modules, so the server file only wires things together.
  • Build the context per request; never share per-user state in a module-level variable.
  • Mount GraphQL under a single path and keep health checks and REST routes outside it.
  • Parse JSON before GraphQL, set CORS deliberately, and add graceful shutdown.
  • Before production: disable the IDE, decide about introspection, and add query limits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which three ingredients does every GraphQL server need?

    The schema describes the API, resolvers produce data, and the endpoint accepts requests and runs them through an engine such as graphql-js.
  2. 2. When mounting Apollo Server on Express, what must happen before app.use('/graphql', expressMiddleware(server))?

    The middleware needs a started server. Forgetting the await is a common startup error.
  3. 3. Why should express.json() come before the GraphQL middleware?

    Middleware runs in the order you list it. A body parser placed after the handler is too late.
  4. 4. What is the context function for?

    It runs once per request, so each request gets its own user and its own caches.
  5. 5. What does an unknown field in a query usually cause at the HTTP level in these servers?

    Validation happens before execution. The request is rejected as a whole, unlike a resolver error, which can still return partial data.

Summary

  • A GraphQL server is a schema (SDL typeDefs), a resolver map and an HTTP endpoint run by an execution engine; libraries provide the engine and the endpoint.
  • Apollo Server standalone is the quickest start; for sharing a process with REST routes, mount expressMiddleware on Express after await server.start().
  • On Express the order is CORS, then express.json(), then GraphQL; the context function builds per-request values from the request.
  • GraphQL Yoga is a small Fetch API based alternative that takes the same schema and resolvers and can also mount on Express.
  • Test the running endpoint with curl or an IDE, and keep schema, resolvers and server wiring in separate modules.

Next, learn a naming and identity convention that clients and caches love in Global Object Identification and the Node Interface.