Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 42 ยท Building Real APIs

GraphQL with NestJS

Build a GraphQL API in NestJS with @nestjs/graphql: code-first versus schema-first, @ObjectType and @Field, resolvers, @Args, @ResolveField and guards on resolvers.

Everything so far in this tutorial exposed data over REST: controllers, routes and HTTP verbs. Nest can expose the same services through GraphQL instead (or as well). In GraphQL the client sends one query that names the fields it wants, and the server returns exactly that shape. If GraphQL is new to you, read What Is GraphQL? first; this lesson assumes you know what a schema, a query and a resolver are, and focuses on how Nest maps those ideas onto classes and decorators.

The package is @nestjs/graphql, and it runs on top of a GraphQL server driver, usually Apollo (@nestjs/apollo) or Mercurius on Fastify. You will see the two ways to define a schema, how types, queries, arguments and field resolvers look as decorated classes, and how the pipeline you already know (guards, pipes, interceptors) still applies. Real Nest code is read-only here, since it needs npm and a server. The stand-ins build a small piece of the machinery in plain JavaScript so you can see what the decorators generate.

GraphQL in Nest

Types @ObjectType classes become schema types.
Resolvers @Query and @Mutation methods answer requests.
Field resolvers @ResolveField fills nested data.
Same pipeline Guards, pipes and filters still apply.

Services and modules stay exactly as before.

1 / 2

Code-first or schema-first

Nest supports two styles, and you pick one per project:

  • Code-first: you write TypeScript classes with decorators (@ObjectType, @Field), and Nest generates the schema (SDL) from them. One source of truth, strong typing, but the schema is a by-product.
  • Schema-first: you write the schema in .graphql files, and Nest (via a generator) creates TypeScript definitions for it. The schema is the contract that front-end and back-end teams review, and the classes follow it.

Most new Nest projects choose code-first, because decorators and TypeScript types sit next to each other and refactoring tools work. Schema-first suits teams that design the API contract before coding or share a schema across languages. The rest of this lesson shows code-first.

Setting up

Install @nestjs/graphql, @nestjs/apollo, @apollo/server and graphql. Register the module once:

TypeScript
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: true,        // keep the generated schema in memory
      sortSchema: true,
      playground: false,
    }),
    BooksModule,
  ],
})
export class AppModule {}

autoSchemaFile: true generates the schema in memory; pass a path such as join(process.cwd(), 'src/schema.gql') to write it to a file, which is handy for code review and for client code generators. The server listens at /graphql on the same HTTP server as your REST controllers. Check the current @nestjs/graphql guide for the exact driver options of your version, since they change between major releases.

Object types

An object type describes something clients can ask for. You write a class and decorate it:

TypeScript
import { Field, ID, Int, ObjectType } from '@nestjs/graphql';

@ObjectType({ description: 'A book in the catalog' })
export class Book {
  @Field(() => ID)
  id: string;

  @Field()
  title: string;

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

  @Field(() => [String])
  tags: string[];

  @Field(() => Author)
  author: Author;
}

Nest reads TypeScript's metadata for simple types, so title: string becomes String!. Where metadata is not enough (a number that should be Int, arrays, optional values), you pass a type function such as () => Int or () => [String]. The generated SDL is:

GRAPHQL
"""A book in the catalog"""
type Book {
  id: ID!
  title: String!
  pages: Int
  tags: [String!]!
  author: Author!
}

Fields are non-null by default, which is the opposite of GraphQL's own default. Mark optional fields with { nullable: true }. This is the same advice as in Lists and Nullability: promise only what you can always deliver.

Resolvers

A resolver class is the GraphQL counterpart of a controller. It is a provider, so it uses dependency injection to receive your existing services:

TypeScript
import { Args, ID, Int, Mutation, Query, Resolver } from '@nestjs/graphql';

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

  @Query(() => [Book], { name: 'books' })
  findAll(@Args('limit', { type: () => Int, defaultValue: 10 }) limit: number) {
    return this.books.findAll(limit);
  }

  @Query(() => Book, { name: 'book', nullable: true })
  findOne(@Args('id', { type: () => ID }) id: string) {
    return this.books.findOne(id);
  }

  @Mutation(() => Book)
  addBook(@Args('input') input: NewBookInput) {
    return this.books.create(input);
  }
}

@Query and @Mutation register fields on the root Query and Mutation types. The method name is the field name unless you set name. @Args('id') declares an argument, and the method receives its value. For several arguments that belong together, use an input type: a class decorated with @InputType() and @Field, which also works with class-validator decorators because Nest's ValidationPipe runs on resolver arguments too:

TypeScript
@InputType()
export class NewBookInput {
  @Field()
  @MaxLength(120)
  title: string;

  @Field(() => ID)
  authorId: string;
}

Your service did not change. BooksService is the same class a REST controller would call, so you can offer both APIs over one business layer.

Field resolvers

The Book.author field in the schema above does not need to be loaded unless a client asks for it. A field resolver computes one field of a type on demand, using the parent object:

TypeScript
import { Parent, ResolveField } from '@nestjs/graphql';

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

  @ResolveField(() => Author)
  author(@Parent() book: Book) {
    return this.authors.findById(book.authorId);
  }
}

Nest calls author() only for queries that select author, once per book. That is exactly the N+1 problem explained in N+1 and DataLoader: fifty books means fifty author lookups. The cure is a DataLoader, a per-request batching cache. In Nest, create the loader in a provider with request scope (see Dynamic Modules and Provider Scopes) or in the GraphQL context factory, so each request gets its own instance.

Guards, pipes and errors

The request pipeline you learned still works, with one difference. A resolver does not receive an HTTP request in the same shape, so guards and decorators that read request.user must get the request from the GraphQL context:

TypeScript
import { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { createParamDecorator } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data: unknown, context: ExecutionContext) =>
    GqlExecutionContext.create(context).getContext().req.user,
);

An authentication guard calls GqlExecutionContext.create(context).getContext().req in the same way (see Guards and Authorization and Custom Decorators). You then write @UseGuards(GqlAuthGuard) on a resolver or method.

Errors also differ. A GraphQL response is normally 200 OK even when a field fails; errors travel in an errors array in the body. If a resolver throws a Nest NotFoundException, the driver turns it into a GraphQL error whose extensions carry the code. See Execution and Errors for how clients should read them.

Security and cost

A public GraphQL endpoint lets clients write expensive queries. Disable introspection and the playground in production unless you intend them to be public, add depth and complexity limits, and rate-limit as described in Query Limits and Security. Authorization belongs in resolvers or services, per field where it matters, not only on the endpoint.

Stand-in: from decorated classes to SDL

The real @nestjs/graphql reads decorator metadata with TypeScript's reflect-metadata. This stand-in uses plain JavaScript objects to show the same pipeline: type definitions are collected, then a printer produces the SDL you would see in schema.gql. It is not Nest's implementation, only the idea.

Node.js Generating SDL from type metadata

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.

Notice that fields are non-null unless you opt out, matching Nest's default. That is why pages is the only field printed without !.

Stand-in: resolvers and a field resolver

Now the runtime part: a resolver class with injected services, a root query, and a ResolveField for author. A tiny executor calls them. As in the lesson on resolvers, the engine here is hand-written; real servers parse GraphQL text. The call counter makes the N+1 effect visible, and a per-request cache (a stand-in for DataLoader) removes it.

Node.js Field resolvers and the N+1 effect

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.

Four books cost four author lookups with a plain field resolver, but only two with the cache, because there are two distinct authors. A real DataLoader goes further and batches the distinct ids into one query, as shown in the GraphQL track.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a code-first NestJS GraphQL project, where does the schema come from?

    Code-first generates the schema from decorated classes. Schema-first starts from .graphql files instead.
  2. 2. In @nestjs/graphql, what is the default nullability of a @Field()?

    Nest makes fields non-null by default, so mark optional ones with nullable: true.
  3. 3. What does @ResolveField() with @Parent() do?

    A field resolver receives the parent and returns the value of one field, for example the author of a book.
  4. 4. Why might a custom decorator like @CurrentUser need GqlExecutionContext?

    Use GqlExecutionContext.create(context).getContext().req to reach the underlying request in a resolver.
  5. 5. A query lists 50 books and selects the author of each. A plain @ResolveField('author') runs how many times?

    Field resolvers run per parent object. Batching with a request-scoped DataLoader turns many lookups into one.

Summary

  • @nestjs/graphql runs a GraphQL server (Apollo or Mercurius) inside your Nest app; REST controllers and resolvers can share the same services.
  • Code-first generates the schema from @ObjectType, @InputType and @Field classes; schema-first starts from .graphql files. Fields are non-null by default in Nest.
  • Resolver classes use @Query, @Mutation and @Args; @ResolveField with @Parent computes nested fields lazily.
  • Guards, pipes and filters still work, but read the request from GqlExecutionContext.
  • Field resolvers cause N+1 queries; batch with a request-scoped DataLoader, and limit query depth and cost in production.

Next, split reads from writes in larger systems with CQRS Basics.