DEV Community

lukadriel7
lukadriel7

Posted on • Edited on

[NestJS] Access Express request and response in GraphQL resolver.

If you are like me and ever wanted to add cookies to your NestJS GraphQL responses, you may not have found a lot of documentation about how to do it. Here is how :

First of all, add a context to your GraphqlModule initialization

GraphQLModule.forRoot({
    ...
    context: (context) => context,
}
Enter fullscreen mode Exit fullscreen mode

Then use the @Context decorator from nestjs/graphql to specify what you need to access. Request and Response are imported from express.

async login(
        @Args() params: LoginArgs,
        @Context('req') request: Request,
        @Context('res') response: Response,
) {
    console.log('request: ', request.cookies);
    response.cookie('whoami', 'DIO', {
        httpOnly: true,
    });
}
Enter fullscreen mode Exit fullscreen mode

The 'req' and 'res' arguments are used to specify that we want to access the request and response from the Context. Not using any argument will give you access to the full context. Personally, I prefer to specify them to make use of typing.

That is all, enjoy coding !!!

Top comments (0)