"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

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

I keep receiving the following error message: "Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers after they have been sent to the client."

I encountered an issue while implementing a middleware in my blog website for multi-role admins. The problem arises when I try to prevent an admin from accessing the login page while logged in, or any other protected admin page before logging in. Here is t ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Encryption module is malfunctioning when used in an asynchronous environment

Currently, I am faced with an issue related to implementing a user login and sign up page. The bcrypt module is working perfectly during the signup process to hash the password asynchronously. However, when attempting to use it in the login code, the await ...

the behavior subject remains static and does not update

Working on setting my language in the BehaviorSubject with a default value using a LanguageService. The service structure is as follows import {Injectable} from '@angular/core'; import * as globals from '../../../environments/globals'; ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

Creating GraphQL from a Mongoose model: A step-by-step guide

I'm currently utilizing graphql and mongodb to add a specific object to the database. While using the same method to add an object, this particular one has a nested structure. package.json { "name": "workplaces", "versi ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

The magical form component in React using TypeScript with the powerful react-final-form

My goal is to develop a 3-step form using react-final-form with TypeScript in React.js. I found inspiration from codesandbox, but I am encountering an issue with the const static Page. I am struggling to convert it to TypeScript and honestly, I don't ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Retrieve the URL with a GET request and remove a specific object

Currently, I am working on developing a CRUD (Create, Read, Update, Delete) App using Express and LowDB. So far, I have successfully implemented the create and read functions, but I am facing issues with the delete function. This is an example of what th ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Updating from Angular version 12.0.4 to 12.1.0 results in a runtime error. As a temporary solution, we are reverting back to version 12.0

There is a related issue discussed here: Angular: TypeError: Cannot read property 'firstCreatePass' of null However, the problem in that case pertains to different Angular versions and the solution provided did not resolve my issue. The recurring ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

Having trouble getting the jQuery slider to function properly within an AngularJS environment

Every time I navigate to my page, the slider doesn't appear. However, if I refresh the page or replace the <div ng-view></div> code with the content from the front.html page, the slider works fine. It seems like there might be a basic mist ...

Node.js for Error Handling: Showing Errors

I'm currently facing an issue where I need to send a user-friendly error message when my MongoDB server cannot be connected from within node.js. Right now, node.js is not handling this situation well. I've realized that accessing the response va ...

What is the method to obtain Express's JSON response using a promise handler?

I currently have an express router set up as follows: app.get('/is-unique-email', function(req, res){ // check if email address is unique if(unique){ res.json({ unique: true }) return } // if not unique, return 403 ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...