Sending httponly cookies with Apollo GraphQL server

Objective: I want my API gateway to retrieve the HTTPOnly cookies returned by my REST endpoints and forward them to the frontend. Additionally, the frontend should have the capability to transmit these cookies as well.

httpO=httponly

   SPA(react)              apiGateway(apolloQL)            restEndpoint
httpO-cookies---->     <-----(httpO)cookies----->      <-----(httpO)cookies

Currently, the resolvers can detect the "set-cookies" in the response from the endpoints, but the headers are not maintained throughout the response lifecycle.

const apolloServer: ApolloServer = new ApolloServer({
    context: ({ res }) => {
        
        // console.log(res,"res");
        return ({
            res
        });

    },
    formatError,
    resolvers,
    typeDefs,
    formatResponse: (response: GraphQLResponse) => {
        console.log(response.http?.headers, "header?");
        return {
            headers: {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Credentials': 'true',
            },
            data: response.data,
            errors: response.errors,
        };
    }
});

An example of a resolver:

const signupUser = async (parent: any, args: any, context: any, info: any) => {
    try {
        const response = await UserService.createUser(args);
        console.log(response , "response");
        return response;
    } catch (error) {
        console.log(error
    }
};

In this scenario, let's assume that UserService.createUser returns the entire response object, not just response.data.

Answer №1

async function registerUser(parent: any, args: any, context: any, info: any) {
    try {
        // Access the Express response from the context
        const expressResponse = context.res;
        
        // Alternatively, you can destructure the response object
        const { res } = context;

        // Create a new user using UserService
        const newUserResponse = await UserService.createUser(args);
        
        // Set cookies in the response headers
        expressResponse.header('set-cookie', newUserResponse?.headers['set-cookie']);

        // Return the response data from creating the new user
        return newUserResponse?.data;
    } catch (error) {
        console.log(error);
    }
}

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

Avoiding the installation of dependencies within npm packages, particularly in projects utilizing Next.js, Node

I've encountered a puzzling issue that seems to have no solution online. When I install npm packages, their dependencies are not automatically installed. This situation is resulting in numerous warnings appearing in the console, such as: Module not ...

express not resolving async callback

Exploring the concept of promises further, I decided to create a simple async delay function that incorporates a timeout feature: const app = express(); function timeout(duration) { return new Promise((resolve, reject) => setTimeout(() => { ...

Sanitizing form fields in node.js: Best practices and techniques

I recently installed the express-validator package to help me sanitize form fields. However, when I tried using it, I encountered an error: TypeError: req.sanitize is not a function. var express = require('express'); var router = express.Router() ...

Encountering a NextJS Error while trying to render a page, following a recent post

Recently, I encountered an issue with my Next.js application that is connected to my NodeJS API. I have a form on one of the pages that sends POST requests to the backend API. However, upon submitting the form and being redirected to another page, pressin ...

Encountering permission issues while trying to run yo @superset-ui/superset

Exploring ways to customize Apache Superset, I came across this page: With the command 'yo @superset-ui/superset', I encountered the following error: /usr/lib/node_modules/yo/node_modules/write-file-atomic/index.js:236 throw err ^ Error ...

Learn the technique of invoking a sub component's method from the parent component in Vue.js

I am looking to trigger a method in a sub component from the parent component in Vue.js in order to refresh certain parts of the sub component. Below is an example showcasing what I aim to achieve. Home.vue <template> <componentp></compo ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Easy steps to handle web service requests in Expressjs

app.get('/', function(req, res){ var options = { host: 'www.google.com' }; http.get(options, function(http_res) { http_res.on('data', function (chunk) { res.send('BODY: ' + chunk); }); res.end ...

expressjs templates

I am looking to implement two different layouts for the main page and admin page. What steps should I take to configure my code to achieve this? Here is my current configuration: app.configure(function(){ app.set('views', __dirname + ...

Combining input streams using node.js and ffmpeg

Currently, I'm in the process of developing a basic and straightforward Video-Web-Chat platform. My approach involves utilizing the getUserMedia API call on the client side to capture webcam data and transmit it as data-blob to my server. My plan is ...

Should Node.js utilize a framework?

I am embarking on the journey of creating the server component for a client app. My tools of choice are nodejs and a nosql db, with the requirement that it should be deployable on AWS Lambda. As I venture into this new territory, I kindly ask for assista ...

Error: The function semrush.backlinks_refdomains does not exist as a valid function

Hey there! So I've been working with the SEMRUSH API and encountered an issue when trying to retrieve data using backlinks_refdomains and backlinks_refips. However, when I called the domain_rank function, it responded in JSON format without any proble ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

Having trouble with the POST method in my Node.js application, and I'm unsure of the cause

This is the main index.js file that serves as the entry point for my Node.js application. const express = require('express'); const app = express(); const path = require('path'); const port = process.env.PORT || 2000; require('./db ...

Is it possible to retrieve the parent object?

My code snippet is as follows, and I'm struggling to access the data object from within the innerFn function. Is there a way to accomplish this? export default { data: { a: "a", b: "b" }, fn: { innerFn: () => co ...

Experience the power of Google Cloud PubSub emulator by testing it with a push subscription

In my attempt to configure a GCP PubSub service to work with a subscription that uses the push method, I encountered an obstacle during the development stage due to the unavailability of accessible endpoints. I initially believed that utilizing the emulat ...

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

What is the process of invoking a node module in an express-rendered view?

Struggling to comprehend how to pass data to my view. Currently integrating the Mozscape node module into an application and unsure of how to send the information to the view. My assumption is that I should create the object in the router, call the functio ...

Is ExpressJs used as a server in web development?

I am currently learning about Node.js. Can you explain the role of Express in NodeJs? Is it primarily utilized as a server for NodeJs applications? If yes, how can we deploy our code using Express? Thank you! ...

The retrieved information can be seen in the Network tab, however, there seems to be an issue in the console

I am successfully fetching data from the server, but I can't seem to display it in console.log. The error message I'm encountering is shown below. I have confirmed that the data is being returned as an array. What steps should I take to ensure th ...