"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000.

Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header

However, when checking the storage > cookies tab in Chrome, no cookies are found. chrome: application > storage > cookies

Below is my server.ts file. (I believe I have configured my cors settings correctly)

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true,
  playground: true,
  dataSources: () => ({
    projectAPI: new ProjectAPI(),
  }),
  context: ({ req, res }: { req: Request; res: Response }) => ({ req, res }),
})

const app = express()

/* Parse cookie header and populate req.cookies */
app.use(cookieParser())

app.use(
  cors({
    origin: '*',
    credentials: true, // <-- REQUIRED backend setting
  })
)

app.use((req: any, res: any, next: any) => {
    console.log(req.cookies)
    next()
})

server.applyMiddleware({ app, path: '/' })

if (process.env.NODE_ENV !== 'test') {
  app.listen({ port: 4000 }, () =>
    console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
  )
}

export { server }

Furthermore, here is my resolvers.ts:

export default {
  Query: {
    session: async (_: null | undefined, __: null | undefined, { res }: any) => {
      const response = await fetch(`http://localhost:3000/api/v1/sessions/current_user`, {
        headers: {
          'content-type': 'application/json',
        },
      })

      /** Obtain session cookie from the response header */
      const sessionCookie = setCookie
        .parse(response.headers.get('set-cookie') as string)
        .find((el: any) => el.name === '_session')

      /** If session cookie exists, store the cookie */
      if (sessionCookie && res) {
        const { name, value, ...rest } = sessionCookie
        res.cookie(name, value, rest)
      }

      const data = await response.json()
      return data.user
    },

Answer â„–1

Do you have apollo-client integrated on the client side?

If you do, make sure to include the credentials option when setting up the terminating http link (or batch link). If you are not using apollo-client, adjust the options accordingly.

const SETTINGS = {
  uri: GQL_BASE,
  credentials: 'include', // or 'same-origin' etc.
  includeExtensions: true,
}

const httpLink = new BatchHttpLink(SETTINGS)

Remember to also include credentials: true in the CORS settings for proper functionality.

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

The continuity of service value across parent and child components is not guaranteed

My goal is to update a value in a service from one component and retrieve it in another. The structure of my components is as follows: parent => child => grandchild When I modify the service value in the first child component, the parent receives the cor ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

Hey there world! I seem to be stuck at the Loading screen while trying to use Angular

A discrepancy in the browsers log indicates node_modules/angular2/platform/browser.d.ts(78,90): error TS2314: Generic type 'Promise' is missing 2 type arguments. ...

What is the process of determining if two tuples are equal in Typescript?

When comparing two tuples with equal values, it may be surprising to find that the result is false. Here's an example: ➜ algo-ts git:(master) ✗ ts-node > const expected: [number, number] = [4, 4]; undefined > const actual: [number, number] ...

The Perplexing Problem with Angular 15's Routing Module

After upgrading to Angular 15, I encountered an issue with the redirect functionality. The error message points out a double slash "//" in my code, but upon inspection, I couldn't find any such occurrence. * * PagesRoutingModule: const routes: Routes ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

What is the TypeScript definition for the return type of a Reselect function in Redux?

Has anyone been able to specify the return type of the createSelector function in Redux's Reselect library? I didn't find any information on this in the official documentation: https://github.com/reduxjs/reselect#q-are-there-typescript-typings ...

The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly: declare const EventBus: any; @Injectable({ providedIn: 'root' }) export cl ...

Filtering an array in Angular based on two specific property values

I am facing a challenge with deleting items from an array based on two property values. If we were to compare it to the classic Sql delete command, the equivalent would look something like this: DELETE oImages WHERE idOffertRow = 1 and idProductImage = 2 ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

What is the best way to retrieve a nested data type?

I am working with an interface named IFoo interface IFoo { name: string; version: number; init: (arg1: string, arg2: number) => Promise<string[]>; } I am interested in the type of init. Is there a way to extract it so that I can use this i ...

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

What is the best way to define types for an array of objects with interconnected properties?

I need to define a type for an object called root, which holds a nested array of objects called values. Each object in the array has properties named one (of any type) and all (an array of the same type as one). Below is my attempt at creating this type d ...

Adding an object with a composite key to an IndexedDB object store is not permitted as the key already exists within the store. This limitation occurs when attempting to add an entry

I am facing an issue with my objectStore where adding an object with the same productId but a different shopName triggers an error in the transaction showing: ConstraintError: Key already exists in the object store.. This is how I initialized the objectSto ...

Is there a clever method to transform the property names of child objects into an array of strings?

I have a similar object that looks like this: { "name":"sdfsd", "id":1, "groups":[ { "name":"name1", "id":1, "subGroups":[..] }, { "name":"name2", "id":21, ...

Switching from a TypeOrm custom repository to Injectable NestJs providers can be a smooth transition with the

After updating TypeORM to version 0.3.12 and @nestjs/typeorm to version 9.0.1, I followed the recommended approach outlined here. I adjusted all my custom repositories accordingly, but simply moving dependencies into the providers metadata of the createTe ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...