Building a GraphQL API in Node.js
GraphQL lets clients request exactly the data they need in a single query. It's popular for frontends that combine data from many sources — and headless CMSs like Contentstack and Sitecore use it for delivery.
Schema First
type Ticket {
id: ID!
summary: String!
status: String!
assignee: User
}
type User {
id: ID!
name: String!
}
type Query {
tickets(status: String): [Ticket!]!
}
Server With GraphQL Yoga
import { createSchema, createYoga } from 'graphql-yoga';
import { createServer } from 'node:http';
const yoga = createYoga({
schema: createSchema({
typeDefs,
resolvers: {
Query: { tickets: (_, { status }) => db.tickets.find({ status }) },
Ticket: { assignee: (t, _, ctx) => ctx.loaders.user.load(t.assigneeId) },
},
}),
context: () => ({ loaders: createLoaders() }),
});
createServer(yoga).listen(4000);
Apollo Server is the other popular choice.
The N+1 Problem
Fetching 100 tickets then one user per ticket = 101 queries. DataLoader batches them into one:
import DataLoader from 'dataloader';
const createLoaders = () => ({
user: new DataLoader(async (ids) => {
const users = await db.users.findByIds(ids);
return ids.map((id) => users.find((u) => u.id === id));
}),
});
Security and Performance
- Limit query depth and complexity
- Authenticate in context; authorise in resolvers
- Use persisted queries in production
- Disable introspection publicly if appropriate
REST or GraphQL?
GraphQL shines for complex, client-driven data needs. REST is simpler for straightforward resources and caching. Many systems use both.
GraphQL moves complexity from the client to the server. Make sure your server is ready for it.