Skip to content

NestJS GraphQL

NestJS has first-class GraphQL support via @nestjs/graphql. This lesson introduces GraphQL in Nest, the Apollo driver, and how resolvers replace REST controllers.

Enabling GraphQL in Nest

Install @nestjs/graphql, @nestjs/apollo, @apollo/server, and graphql. Register GraphQLModule.forRoot with a driver and choose code-first or schema-first. Queries and mutations live in resolver classes instead of REST controllers.

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
})

With code-first, Nest generates schema.gql from TypeScript resolver and model decorators automatically.

A Minimal Query Resolver

@Resolver(() => Cat)
export class CatsResolver {
  constructor(private catsService: CatsService) {}

  @Query(() => [Cat])
  cats() {
    return this.catsService.findAll();
  }
}
  • Resolvers are providers registered in a module like controllers.
  • @Query, @Mutation, and @Subscription map to GraphQL operations.
  • GraphQL still uses Nest pipes, guards, and interceptors.
  • Playground/Explorer is useful in development; disable in production if exposed publicly.

GraphQL Nest Cheatsheet

Core GraphQL wiring in Nest.

Piece Role
GraphQLModule Boots the GraphQL HTTP endpoint
ApolloDriver Apollo server integration
@Resolver Groups queries/mutations for a type
@Query / @Mutation Operation handlers
Code-first / schema-first How the schema is authored

When to Prefer GraphQL

GraphQL shines when clients need flexible field selection and fewer round-trips. REST remains excellent for simple resource APIs and caching at the HTTP layer. Many Nest apps expose both.

Guards Still Apply

Use @UseGuards(JwtAuthGuard) on resolvers or methods the same way you would on controllers. Extract the user from the GraphQL context.

Common Mistakes

  • Leaving GraphQL Playground enabled on public production APIs.
  • Putting business logic in resolvers instead of services.
  • Ignoring N+1 query problems when resolving nested fields.
  • Exposing internal entity fields without an explicit GraphQL object type.

Key Takeaways

  • Nest GraphQL uses modules, resolvers, and the same DI/guards/pipes ecosystem.
  • Apollo driver is the common HTTP GraphQL host.
  • Code-first generates schema from TypeScript; schema-first starts from .graphql files.
  • Keep resolvers thin and services thick, just like REST controllers.

Pro Tip

Add a complexity/depth limit early if clients can craft expensive nested queries—GraphQL APIs need deliberate abuse protection.