NestJS + GraphQL + Authentication
NestJS + GraphQL Example
$ npm install
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
The first step to setup GraphQL in NestJS is to import the GraphQLModule
from @nestjs/graphql
into the AppModule
in app.module.ts
.
In order for GraphQL requests to access request headers (needed later for authentication), we need to use the GraphQLModule context
option.
// Location: src/app.module.ts
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { PostsModule } from './posts/posts.module';
@Module({
imports: [
AuthModule,
UsersModule,
PostsModule,
GraphQLModule.forRoot({
installSubscriptionHandlers: true,
autoSchemaFile: 'schema.gql',
context: ({ req }) => ({ req }),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
The GraqhQL schema is generated automatically using decorators from @nestjs/graphql
and TypeGraphQL.
@Resolver()
and @Args()
decorators used come from @nestjs/graphql
instead of type-graphql
.The GraphQL specification doesn't cover authentication, but we can create an AuthModule
in NestJS that handles: