Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Clients and Transport

GraphQL with NestJS

See how NestJS turns the GraphQL ideas you know into classes: code-first and schema-first schemas, resolver classes, field resolvers, context, and where to read more.

Until now, our servers were small functions: a schema string, a resolver map, a few lines to start listening. That is perfect for learning and for small services. Larger teams often want a framework around it: dependency injection, modules, validation, guards for authentication, testing helpers and a standard project layout. NestJS is the most common such framework in the Node.js world, and its @nestjs/graphql package connects it to a GraphQL server (Apollo or Mercurius under the hood).

This lesson is the GraphQL side of that story. It shows how the concepts from this tutorial (schema, types, resolvers, field resolvers, context) map onto Nest's classes and decorators, and compares Nest's two ways of defining a schema. The full Nest walk-through, with modules, decorators and the request pipeline, lives in the NestJS tutorial: GraphQL with NestJS. Everything here is read-only framework code plus runnable stand-ins, because the site cannot install npm packages.

GraphQL concepts in Nest

Schema Generated from classes, or written as SDL.
Resolver class Methods marked with @Query and @Mutation.
Field resolver @ResolveField with @Parent.
Context Per-request values for guards and loaders.

Same GraphQL, different packaging.

1 / 2

What changes, and what does not

Nothing about GraphQL itself changes. Queries, variables, fragments, errors, nullability and the execution model all work as in earlier lessons. What Nest changes is how you organize the server code:

  • Resolvers become classes that receive services through dependency injection, instead of functions in one big object.
  • The schema can be generated from decorated TypeScript classes.
  • Authentication and validation reuse Nest's guards and pipes, which also run for REST controllers, so one authentication system serves both.
  • The GraphQL server becomes one module in the app, so you can offer REST, GraphQL and WebSockets from a single codebase.

Code-first

In the code-first approach you describe your types as TypeScript classes, and Nest produces the SDL:

TypeScript
@ObjectType()
export class Book {
  @Field(() => ID)
  id: string;

  @Field()
  title: string;

  @Field(() => Int, { nullable: true })
  pages?: number;
}

@Resolver(() => Book)
export class BooksResolver {
  constructor(private readonly books: BooksService) {}

  @Query(() => [Book])
  books() {
    return this.books.findAll();
  }
}

The advantages are one source of truth (the class is both the TypeScript type and the schema type), refactoring support in your editor, and no drift between SDL and code. The trade-off: the schema is a by-product, so reviewing API changes means reading a generated file. Many teams therefore commit the generated schema.gql and review its diff in pull requests, in the spirit of Schema Evolution, Federation and Tooling.

Schema-first

In schema-first you write the SDL yourself, in .graphql files, and write resolver classes that fill in the fields. Nest can generate TypeScript definitions from the SDL so your resolver signatures stay type-checked:

GRAPHQL
# schema/book.graphql
type Book {
  id: ID!
  title: String!
  pages: Int
}

type Query {
  books: [Book!]!
}
TypeScript
@Resolver('Book')
export class BooksResolver {
  constructor(private readonly books: BooksService) {}

  @Query('books')
  findAll() {
    return this.books.findAll();
  }
}

The advantage is that the schema is the contract: front-end and back-end teams can design it together, review it as a plain file and mock it before any server code exists. The trade-off is keeping the TypeScript definitions in sync (a generator step) and slightly more files.

Which to pick? Code-first is the common default for TypeScript-only teams. Schema-first suits contract-first workflows, polyglot organizations that share a schema across languages, and teams adopting federation, where the SDL is an artifact in its own right. Either way the running server is the same.

Field resolvers and context

Field resolvers keep their meaning. In Nest they are methods with a decorator:

TypeScript
@Resolver(() => Book)
export class BooksResolver {
  @ResolveField(() => Author)
  author(@Parent() book: Book, @Context() ctx: GqlContext) {
    return ctx.loaders.author.load(book.authorId);
  }
}

@Parent() is the first resolver argument you know from Resolvers, and @Context() is the third. Because the field resolver runs once per book, the N+1 problem is exactly as real here as anywhere else, and the cure is the same: create a DataLoader per request and put it in the context.

Authentication also maps cleanly. A guard reads the request from the GraphQL context and decides whether the resolver may run (see Authentication and Authorization). Because an HTTP request in a resolver lives in the GraphQL context rather than in the usual HTTP execution context, Nest provides GqlExecutionContext to reach it. The NestJS lesson shows the code.

Stand-in: a resolver class and a schema check

Frameworks catch mistakes that plain resolver maps silently allow: a resolver for a field that does not exist in the schema, or a field that is never implemented. This stand-in has a small schema (as a type map), resolver classes with injected services, and a checker that compares them. It is not Nest, but it shows the idea a framework's startup validation enforces.

Node.js Resolver classes and schema-resolver validation

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.

The checker finds the typo Book.autor, which a plain resolver map would simply never call (the client would get an author that works and an autor resolver that is dead code). Real frameworks report this kind of mismatch at startup, or generate the schema from the classes so it cannot happen at all.

Stand-in: class metadata and the SDL it implies

For code-first, the idea is that the same description serves as both runtime metadata and schema. This stand-in describes a type once, as plain data (what @ObjectType and @Field record), prints SDL from it, and checks that the result equals a hand-written schema-first SDL. The two styles give the same API.

Node.js Code-first and schema-first produce the same SDL

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.

The last line shows the drift risk of schema-first: if code and SDL are maintained separately, they can diverge. Teams guard against it with generated types and CI checks that compare the committed schema with the running server (see Testing GraphQL APIs).

When Nest is a good fit

  • You want dependency injection, modules and a conventional structure for a growing team.
  • You already run Nest for REST, WebSockets or microservices and want GraphQL in the same app, sharing services and authentication.
  • You value TypeScript end to end, including generated schema types.

A lighter setup (Apollo Server or Yoga with plain functions, see Setting Up a Server) is perfectly fine for small services. The framework adds structure, not capabilities: everything you learned about resolvers, execution, security and performance applies unchanged.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In NestJS code-first GraphQL, how does the schema come into existence?

    Code-first treats TypeScript classes as the source of truth and prints the SDL from them.
  2. 2. Which advantage belongs mainly to the schema-first approach?

    Schema-first makes the SDL the primary artifact, which suits contract-first workflows, shared schemas and federation.
  3. 3. A @ResolveField method for Book.author runs once per book in a list. What problem does this create, and what is the cure?

    Field resolvers are called per parent object. Batching with DataLoader fixes the N+1 effect.
  4. 4. What does a framework like Nest NOT change about GraphQL?

    Nest changes the packaging of the server, not GraphQL itself.
  5. 5. Why is a startup check that compares resolvers with the schema useful?

    A misspelled field name in a resolver map simply never runs, which is a quiet bug. Validation turns it into a clear error.

Summary

  • NestJS wraps a GraphQL server in modules, dependency injection, guards and pipes; the GraphQL language and execution rules stay the same.
  • Code-first generates the SDL from decorated TypeScript classes; schema-first starts from .graphql files and generates types.
  • Resolvers become classes; @Query, @Mutation, @ResolveField, @Parent and @Context map directly to the concepts you know.
  • Field resolvers still cause N+1 problems, solved with a per-request DataLoader in the context.
  • Commit and review the schema file, and validate resolvers against it so drift and typos are caught early.
  • For the Nest-specific details, read GraphQL with NestJS in the NestJS tutorial.

Next, put everything together in a project or deepen the architecture side with GraphQL Server Architectures.