nestjs-graphql-example

NestJS + GraphQL + Authentication

Stars
1

Description

NestJS + GraphQL Example

Installation

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Implementation Details

1. Setup the GraphQL Server with HTTP Context

The first step to setup GraphQL in NestJS is to import the GraphQLModule from @nestjs/graphql into the AppModule in app.module.ts.

HTTP Context

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 {}

Example: ./src/app.module.ts

2. Auto-Generated GraphQL Schema

The GraqhQL schema is generated automatically using decorators from @nestjs/graphql and TypeGraphQL.

  1. Types and Fields Example
  2. Resolver Example
    • Reference
    • Note: The @Resolver() and @Args() decorators used come from @nestjs/graphql instead of type-graphql.

3. Authentication

The GraphQL specification doesn't cover authentication, but we can create an AuthModule in NestJS that handles:

  1. User Login
    1. Using an AuthService
  2. JWT Signing
    1. Import and Setup the JwtModule
    2. Consume JwtService
  3. JWT Auth Guard
    1. Create JwtStrategy
    2. Create GraphQLAuthGuard
    3. Provide JwtStrategy and GraphQLAuthGuard to AuthModule
  4. Current User Context
    1. Create a @CurrentUser decorator
    2. Provide CurrentUser to AuthModule