#1 Create Your First GraphQL NestJs Project: A Step-by-Step Guide

Bhavy Shekhaliya
3 min readJun 18, 2024

--

GraphQL has revolutionized how we build APIs, offering a flexible and efficient way to fetch data. NestJS, a progressive Node.js framework, leverages TypeScript to provide a robust and scalable platform for server-side applications. Combining GraphQL with NestJS can create powerful, maintainable APIs. In this article, we’ll walk through creating your first GraphQL NestJS project.

Step 1: Setting Up the Project

Create a New NestJS Project :

First, install the NestJS CLI if you haven’t already:

npm install -g @nestjs/cli

Now, create a new project:

nest new my-graphql-app
cd my-graphql-app

Step 2: Install GraphQL Dependencies

Install the necessary GraphQL packages:

npm install @nestjs/graphql @nestjs/apollo graphql @apollo/server

Step 3: Configure GraphQL

Configure GraphQL in your NestJS application. Open src/app.module.ts and update it as follows:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { AppService } from './app.service';
import { AppController } from './app.controller';

@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

This configuration sets up the Apollo driver for GraphQL and enables automatic schema generation.

Step 4: Define Your First GraphQL Schema

GraphQL schemas define the structure of your API. In NestJS, you define the schema using TypeScript classes and decorators.

Create a user.model.ts file :

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

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

@Field()
name: string;

@Field()
email: string;
}

Step 5: Create a User Service

Create a user.service.ts file:

import { Injectable } from '@nestjs/common';
import { User } from './user.model';

@Injectable()
export class UserService {
private users: User[] = [
{ id: '1', name: 'John Doe', email: 'john@example.com' },
{ id: '2', name: 'Jane Doe', email: 'jane@example.com' },
];

findAll(): User[] {
return this.users;
}

findOneById(id: string): User {
return this.users.find(user => user.id === id);
}
}

Step 6: Create a User Resolver

Resolvers handle the logic for fetching and manipulating data. Create a user.resolver.ts file

import { Resolver, Query, Args } from '@nestjs/graphql';
import { User } from './user.model';
import { UserService } from './user.service';

@Resolver(() => User)
export class UserResolver {
constructor(private userService: UserService) {}

@Query(() => [User])
users(): User[] {
return this.userService.findAll();
}

@Query(() => User)
user(@Args('id') id: string): User {
return this.userService.findOneById(id);
}
}

Step:7 Create a User Module

Finally, create a user.module.ts file to bundle everything together:

import { Module } from '@nestjs/common';
import { UserResolver } from './user.resolver';
import { UserService } from './user.service';

@Module({
providers: [UserResolver, UserService],
})
export class UserModule {}

Step 8: Register the User Module

Register the UserModule in your application.

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { UserModule } from './user/user.module';

@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
UserModule,
],
})
export class AppModule {}

Step 9: Run your NestJs Graphql application

npm run start:dev

Navigate to http://localhost:3000/graphql to access the GraphQL playground. You can now run queries like:

query {
users {
id
name
email
}

user(id: "1") {
id
name
email
}
}

Conclusion

Congratulations! You’ve successfully created your first GraphQL project with NestJS. We’ve covered setting up the project, configuring GraphQL, defining your schema, creating services and resolvers, and running your application. With these basics, you’re now equipped to build more complex GraphQL APIs with NestJS.

NestJS and GraphQL together provide a powerful, type-safe, and scalable way to build modern APIs. Dive deeper into NestJS’s capabilities and GraphQL’s flexibility to create robust and efficient applications.

Next Steps

  • Explore Mutations: Learn how to create, update, and delete data using GraphQL mutations.
  • Implement Authentication: Secure your GraphQL API with authentication and authorization mechanisms.
  • Add Custom Scalars: Handle complex data types like dates and custom objects with custom scalars.

🔗CheckOut :NestJs GraphQL articles

🔗CheckOut : NestJs GraphQL + MongoDB articles

🔗CheckOut : Dockerarticles

🔗Follow me on LinkedIn

#nestjs #graphql #apiDevelopment #backendDevelopment

--

--