DEV Community

Cover image for Building NestJS app boilerplate - Authentication, Validation, GraphQL and Prisma

Building NestJS app boilerplate - Authentication, Validation, GraphQL and Prisma

Nikita Kot on October 22, 2019

The boilerplate app created by this tutorial is here. ⚠️⚠️⚠️ Update - 06 April 2020 NestJS version 7 was recently released. Many thanks...
Collapse
 
johnbiundo profile image
John Biundo

Nikita, thanks for the great tutorial. I am running this 1.5 years after you wrote it 😄 and with Nest v7. So there were a couple of issues I had to fix:

Installing graphql@latest (15.0) caused some sort of problem for me. I haven't quite sorted it out, so I fell back to ^14.6.0 to avoid that problem.

With Nest 7, there's a breaking change to createParamDecorator. Here's the change I made to src/shared/decorators/decorators.ts to make it work:

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

import { Response } from 'express';
import { User } from '../../../generated/prisma-client';

export const ResGql = createParamDecorator(
  (data: unknown, context: ExecutionContext): Response =>
    GqlExecutionContext.create(context).getContext().res,
);

export const GqlUser = createParamDecorator(
  (data: unknown, context: ExecutionContext): User => {
    const ctx = GqlExecutionContext.create(context).getContext();
    return ctx.req && ctx.req.user;
  },
);
Collapse
 
nikitakot profile image
Nikita Kot • Edited

Hi John! Thanks for sharing this! I'll update the article and the repo in near future. By the way, there is prisma 2 beta release out, haven't checked it yet, but I'm pretty sure some bigger changes have to be done for the upgrade too.

Collapse
 
johnbiundo profile image
John Biundo

Sounds good. Figured I'd post the code that worked for me as a stop gap in case others run into it.

Collapse
 
valerebron profile image
Valère BRON

Hi Nikita Gr8 Article ... but Express can't write token'cookie !

this line of code seems ok : "res.cookie('token', jwt, { httpOnly: true });" in auth.resolver.ts,
and the token is correctly generated but no cookie is created in client side...

Collapse
 
nikitakot profile image
Nikita Kot

Please check your graphql playground settings in the browser. You should have "request.credentials": "same-origin" set there to allow CORS.

Collapse
 
valerebron profile image
Valère BRON • Edited

Indeed, that works

Collapse
 
nikitakot profile image
Nikita Kot

P.S. If you are not using graphql playground and calling the server from a front-end application served from another server (different domain/port/etc.) you need to enable cors on the nestjs server (not described in the article). To do it simply add these lines to your main.ts file to the bootstrap function.

app.enableCors({
    credentials: true,
    origin: true,
  });
Collapse
 
valerebron profile image
Valère BRON

Cors was the problem yes, thanks again for these speed responses !

Collapse
 
abumalick profile image
abumalick

Thank you very much for your tutorial, it was very helpful.

In Nest v7 you don't really need to create custom Decorators, you can use the @Context decorator from graphql package:

import {Args, Context, Mutation, Resolver} from '@nestjs/graphql'

// and in your mutation:
@Mutation()
  async login(
    @Args('loginInput') { email, password }: LoginInput,
    @Context('res') res: Response,
  ) {
Enter fullscreen mode Exit fullscreen mode

Thank you again

Collapse
 
otarbes profile image
otarbes

Hi Nikita! Thanks for sharing this. We would love to have your input on our last opensource project leveraging Prisma to add generative capabilities to Nest!

Traxion 🎉 a 100% open-source Generative Toolkit for NestJS Developers ! It helps you accelerate your NestJS projects with generative capabilities while maintaining total control over your code. Features 🌟: Data management with Prisma, Instant GraphQL API, Role-Based Access Control, Official Packages including Dev-Kit, Nest-Authentication, Nest-Authorization, and Nest-Utilities.

Check it out at github.com/tractr/traxion
We'd love to hear your feedback!

Cheers

Collapse
 
edertxodw profile image
Edertxo

That help me a lot, thanks! :D

Collapse
 
elie222 profile image
Elie

Is this the best approach for log out?

  @Mutation(() => Boolean)
  async logOut(@ResGql() res: Response) {
    res.cookie('token', '', { httpOnly: true })
    return true
  }
Collapse
 
nikitakot profile image
Nikita Kot

Hi Elie,

This looks like as the easiest solution. Or you can implement something like token blacklist. More here.

Collapse
 
valeronlol profile image
Valerii Kuzivanov • Edited

Great article Nikita, but authorization doesnt work properly due to problems with cookiest. I can see Set-Cookie header, but it does not add cookie to your browser storage.
github.com/apollographql/apollo-cl...

Collapse
 
nikitakot profile image
Nikita Kot

Thanks! About authorisation - take a look at src/main.ts. I'm using external cookieParser library to parse cookies. You sure you also installed it?

Collapse
 
arrrrny profile image
Arrrrny

Nice post. It would be great if you have the same article using Apollo since it is the default graphql server for the nest.

Collapse
 
paulcuixan profile image
Paul Cuichan • Edited

I have this problem. how can I solve that
dev-to-uploads.s3.amazonaws.com/i/...

Collapse
 
nikitakot profile image
Nikita Kot

looks like you didn't generate typescript types from the gql schema, re-check the GraphQL part of the article

Collapse
 
paulcuixan profile image
Paul Cuichan

thanks

Collapse
 
sgarza profile image
Sergio de la Garza

Seems that the Prisma's client generation API changed and it no longer generates the GraphQL schemas. I have the same issue. Any ideas?