mongodbmongoosegraphqlexpress-sessionconnect-mongo

Can't use express session in my mutations


Hello everybody I have problem with express session. I have created my session with express-session and used it in my apollo-server-express but inside my login mutation when i want to use the session to store my user id and again use that session in my query, it will change to undefined. what is the problem?

This is my index.js where i created my session using mongo-connect:

const MongoStore = mongoconnect(session);    
const SERVER = new ApolloServer({
    typeDefs,
    resolvers,
    cors: {
        origin: '*',
        credentials: true
    },
    playground: {
        endpoint: `http://localhost:3600/graphql`,
        settings: {
            'editor.theme': 'dark'
        }
    },
    context: ({ req }) => {
        return {
            req,
            session: req.session
        }
    }
});

app.use(
    session({
        store: new MongoStore({
            mongooseConnection: mongoose.connection
        }),
        secret: "mysecret-ssss",
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 1000 * 60 * 60 * 2,
            sameSite: true,
            secure: true
        }
    })
);

This is my Query:

Query: {
   circularLetters: async (parent, args, context, info) => {
            const options = {
                page: args.page,
                limit: args.limit
            };
            const circularLetter = await CircularLetters.paginate({}, options, (err, result) => {
                return result.docs;
            });
            console.log(context.session.userId)

            return circularLetter;
        },
}

And my mutation where i want to store my user id inside session:

Mutation: {
     login: async (parent, args, context, info) => {
            const user = await Users.findOne({
                personelNumber: args.data.personelNumber
            }, function (err, myUser) {
                console.log(err);
            });

            if (!user) {
                throw new Error("User not found");
            }

            const isMatch = await bcrypt.compare(args.data.password, user.password);

            if (!isMatch) {
                throw new Error("Wrong password");
            }

            context.session.userId = user.id;
            console.log(context.session);

            return {
                user,
                token: generateToken(user.id)
            }
        },
}

Solution

  • Ok found the solution. it's about Apollo and you have to block Cors inside Apollo and import Cors like this:

    import cors from 'cors';
    
    const SERVER = new ApolloServer({
        typeDefs,
        resolvers,
        engine: {
            debugPrintReports: true
        },
        playground: {
            endpoint,
            settings: {
                'editor.theme': 'dark'
            }
        },
        context: ({ req, res }) =>
            ({
                req,
                res,
                session: req.session
            })
    });
    
    app.use(cors({
        credentials: true,
        origin: true
    }));
    
    app.use(cookieParser());
    
    SERVER.applyMiddleware({
        app,
        cors: false
    });