Having trouble with GraphQL Explorer and Express Sessions compatibility?

Struggling to implement a login system using GraphQL and Express, but facing issues with session persistence. Despite logging in, req.session.userId remains undefined.

Code snippet:

(async () => {
    await connect(process.env.MONGO_URI!, { dbName: "example" });

    const app = express();

    app.use(
        cors({
            origin: [__clientUrl__, "https://studio.apollographql.com"],
            credentials: true
        })
    );

    app.use(
        session({
            name: "qid",
            secret: process.env.SESSION_SECRET!,
            store: MongoStore.create({
                mongoUrl: process.env.MONGO_URI,
                dbName: "example"
            }),
            saveUninitialized: false,
            resave: false,
            cookie: {
                maxAge: 6.048e8,
                httpOnly: __prod__,
                sameSite: "lax",
                secure: __prod__
            }
        })
    );

    const server = new ApolloServer({
        schema: await buildSchema({
            resolvers: [HelloResolver, UserResolver],
            validate: false
        }),
        context: ({ req, res }) => ({ req, res })
    });

    await server.start();

    server.applyMiddleware({
        app,
        cors: {
            origin: [__clientUrl__, "https://studio.apollographql.com"],
            credentials: true
        }
    });

    app.listen(__port__, () =>
        console.log(
            `🚀 Server started at http://localhost:${__port__}${server.graphqlPath}`
        )
    );
})();

Login Mutation using TypeGraphQL:

    @Mutation(() => User, { nullable: true })
    public async login(
        @Arg("username") username: string,
        @Arg("password") password: string,
        @Ctx() { req }: Context
    ) {
        const user = await UserModel.findOne(
            username.includes("@") ? { email: username } : { username }
        );
        if (!user) return;

        if (!(await verify(user.password, password))) return;

        req.session.userId = user._id;

        return user;
    }

Additionally, cookies were enabled in the GraphQL Explorer and specified headers were set: https://i.sstatic.net/npvAt.png

Answer â„–1

Have you managed to find a resolution? One possible solution could be using the "classic" playground by integrating the ApolloServerPluginLandingPageGraphQLPlayground plugin during server creation.

plugins: [ ApolloServerPluginLandingPageGraphQLPlayground(), ],

If the issue is resolved with the "classic" playground, then it indicates a problem with graphqlstudio.

In my experience, I have encountered CORS problems with graphql studio regardless of the specified CORS value for the server. As a result, I have switched back to using the playground.

Answer â„–2

After conducting some research, I discovered that it is necessary to include the following code when setting up the ApolloServer instance:

    const server = new ApolloServer({
        schema: await buildSchema({
            resolvers: [HelloResolver, UserResolver],
            validate: false
        }),
        context: ({ req, res }) => {
>           res.header(
>               "Access-Control-Allow-Origin",
>               "https://studio.apollographql.com"
>           );
>           res.header("Access-Control-Allow-Credentials", "true");

            return { req, res };
        }
    });

By including this code snippet, you will be able to set cookies in the GQL Explorer. Please let me know if this solution works for you!

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

Encountering Challenges When Trying to Upload File onto Azure Blob Storage

My current project involves integrating file uploads to Azure Blob Storage. The backend setup using Node.js with Express and @azure/storage-blob is already done, but I'm facing challenges with the frontend implementation. I need guidance to ensure pro ...

Retrieving latitude and longitude from place id in an Angular Google Maps component

Currently utilizing the google-maps component to extract latitude and longitude from Google Maps prediction data. Additionally, I have integrated a search bar using google-maps component. I have successfully implemented a search bar with ngx-google-places ...

Uploading Files using Node.js and Ajax

Utilizing an ajax file upload plugin (file uploader plugin) to send a file to a node.js server is the current challenge I'm facing. Below is my client-side code for initializing the plugin: $(function() { /* dom ready */ var uploader = new qq. ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this: { "id": "some type of user id", "name": "The name of the user", "permiss ...

Creating a regular expression variable in Mongoose: A step-by-step guide

I am looking for a solution to incorporate a variable pattern in mongoose: router.get('/search/:name', async(req, res) => { name = req.params.name; const products = await Product.find({ name: /.*name*/i }).limit(10); res.send(prod ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Having trouble locating a character's name in the Marvel API with NodeJS

I have integrated the Marvel API to fetch character data using axios. Here is a snippet of the code I am using: const axios = require('axios'); const md5 = require('blueimp-md5'); const publickey = '73f5271b4d972dc0f4eba'; co ...

Yes, indeed - Entering the schema of a retrieved field from an Object schema

After deciding to upgrade from Yup version 0.29 to 1.2, I encountered some challenges with its types. Seeking assistance in finding the best solution for typing yup schemas. In version 0.29, the universal type Schema fit everywhere, but now it no longer d ...

I am struggling to pinpoint the issue within my GraphQL request

Every time I attempt to send a data query in GraphQL, I receive a bad request code. I am unsure whether the problem lies with the resolver or the input itself. https://i.stack.imgur.com/6WKMD.png Here is the resolver function: const addTranslationTableAd ...

Encountering a EJS variable referencing issue while submitting a form

I am currently working on a form within my "welcome.ejs" page. I am trying to display the text that the user enters on the "welcome.ejs" page onto a new page, "submitform.ejs". However, when I attempt to output the text from the form, I encounter an error ...

jade scripts not appearing correctly on expressjs

Currently, I am working with expressjs version 3.0+ and jade in my project. The issue I am facing is related to the placement of script tags in my layout.jade file. When I view the HTML page, the scripts are not functioning correctly due to the closing scr ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Server Sent Events not being received by client from Express.js server

My Next.js (React) client is set up to receive Server-Sent Events from my Node.js/Express.js server, but it seems like it's not receiving any messages for some unknown reason. While the open and error events of EventSource are functioning correctly, ...

"Encountering a problem with the client-session middleware: the value of req.session_state is becoming undefined

I'm facing an issue with client-session middleware in Express. After setting the session_state, it doesn't seem to be accessible when redirecting to a new route. I followed a tutorial on YouTube (client-session part starts at around 36:00) and do ...

Encountered an issue while trying to install npm package express-generator globally

Encountering an error when trying to run npm install express? Looking for the correct solution? Read on. -bash-3.2$ npm install express-generator -g npm WARN engine <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a2bfb7b5a2 ...

Encountering the error message "Received 1 argument, when expecting 4" while attempting to utilize a vuex getter in TypeScript

I encountered an issue while unit testing a getter function. The error message Expected 4 arguments, but got 1. appeared when I attempted to use the getter. My application was built using Quasar and utilizes TypeScript. The value of HttpMocks.mockToken is ...