What is the most effective way to add cookies to the response object in a NestJS GraphQL application?

How can I save cookies in the response object of a NestJS GraphQL application? Here is the relevant code snippet:

app.module.ts:

GraphQLModule.forRoot<ApolloDriverConfig>({
      autoSchemaFile: true,
      driver: ApolloDriver,
      cors: {
        origin: process.env.ADDRESS,
        credentials: true,
      },
      context: ({ req, res }) => ({ req, res }),
    }),

resolver:

 @Mutation(() => token)
  async login(
    @Args("input") input: LoginI,
    @Context() context: GraphQLExecutionContext
  ) {
    const result = await this.authnService.login(input);
    context.res.cookie("authorization", "Bearer " + result.userToken);
    return result;
  }

However, it seems like it's not working as expected.

console.log(context.res.cookies)

Returns undefined. Additionally, I do not see any cookies in the browser devtools for my client.

Answer №1

If you're facing issues with receiving cookies in the GraphQL playground, it's essential to ensure that your playground is configured correctly. By default, the request.credentials setting is set to omit. By changing it to include, the playground will start including credentials.

Make sure to configure your GraphQL Module like this:
const GraphQL = GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  playground: {
    settings: {
      "request.credentials": "include", // Make sure to include credentials for cookies to be sent
    }
  },
  // ...
});

Answer №2

In the world of NestJS, we use the @Res() decorator which is from the @nestjs/common package, as opposed to the Response object from the express package.

@Post('some-route')
     someHandler(@Res({ passthrough: true }) response: Response) {
     # obtain and store the refreshToken
     response.cookie('refreshToken', refreshToken);
   }
 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining Axios response header in a Typescript environment

I am currently working on a rest call that may return a header that I need to store. In order to do this, I have to first check if the header is present before storing it. Here is how I approached it: private getHeader(response: AxiosResponse) { if (r ...

Can SystemJS, JetBrains IntelliJ, and modules be combined effectively?

Looking for some clarification on the functionality of module includes and systemJS within an Angular2 app structure. I have set up a basic Angular2 app with the following layout: -app |-lib (contains shims and node libraries) |-components |-app |-app. ...

The Firebase database is experiencing difficulties fetching the data

Having an issue with my component. Struggling to retrieve data from Firebase. Can someone spot the error in the code below? import { Component, OnInit, Input, ViewChild } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

Error: To execute NPX command locally from Google Maps API documentation, make sure to call npm.load(callback) as required

Attempting to execute the Google Maps API example locally using this command: npx @googlemaps/js-samples init directions-waypoints googlemapssample However, every time I try to run the npx command locally, it fails after a short period and I encounter the ...

Using Firebase Database, Angular2 employs UID (User ID) as the primary key

Creating a signup component in my app using Firebase as the authentication method and database. After registering a new user, a key is generated and all user information, including the UID from authentication, is saved in the database. I want to use the UI ...

Preventing data binding for a specific variable in Angular 2: Tips and tricks

How can I prevent data binding for a specific variable? Here's my current approach: // In my case, data is mostly an object. // I would prefer a global solution function(data) { d = data; // This variable changes based on user input oldD = da ...

Retrieve component information from the service

Incorporated within my component is a form that I'm utilizing with reactive form and my intention is to reach this form through my service. For example: const id = MyComponent.id and inside my component: @Output: public id: number = 7; ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

Encountering an issue with undefined ID when utilizing a radio input field in Vue JS

I'm facing an issue and I hope you can assist me with it. My webpage contains Vue scripts and a list of radio selections rendered via Liquid tag and GraphQL results. The problem arises when I click the submit button or select a radio option, resultin ...

The data type of the element is implicitly set to 'any' due to the fact that a 'string' expression cannot be used to reference the type '(controlName: string) => boolean'

checkError(typeofValidator: string, controlName: string): boolean { return this.CustomerModel.formCustomerGroup.contains[controlName].hasError(typeofValidator); } I am currently learning Angular. I came across the same code in a course video, but it i ...

Dealing with missing image sources in Angular 6 by catching errors and attempting to reset the source

When a user adds a blob to my list, sometimes the newly added image is still uploading when the list is refreshed. In this case, I catch the error and see the function starting at the right time: <img src="https://MyUrl/thumbnails/{{ blob.name }}" widt ...

Ways to incorporate NPM packages into your browser projects using TypeScript

This is the current setup: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <script src="../node_modules/systemjs/dist/system.js"></script> <script src="../node_modules/lodash/in ...

When using Angular, the Zone can be accessed through VSCode intelligence, but it appears as undefined when running in

Upon attempting to utilize Zone within the ngOnInit function in my Angular application, I placed a breakpoint on line 11. However, when inspecting the function Zone(parent, zoneSpec){....}, it returns undefined upon launching in Chrome browser. Here is the ...

What causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...

Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array. Below is the code for the RoomlistService that helps me fetch the correct JSON file: @Injectable() export class RoomlistService { constructor( ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

Initial 16 characters of the deciphered message are nonsensical

In a specific scenario, I encounter data encryption from the API followed by decryption in TypeScript. I have utilized CryptoJS for decryption in TypeScript. Below is the decryption code snippet: decrypt(source: string, iv: string): string { var key = envi ...