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 !!!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay