mongodbexpressmongooseapollo-serverconnect-mongo

Apollo-server-express Session undefined problem


Hello I want to make session with ApolloServer and Express but when i get console log from req.session, it gives me undefined. Whats the problem?? When i get console log from req.session inside app.get, i get my results. Inside Mongodb compass i can find a sessions sections but i dont know how to use it or import data inside it. Anyone can solve this problem?

import '@babel/polyfill/noConflict';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import mongoose, { mongo } from 'mongoose';
import { existsSync, mkdirSync } from 'fs';
import path from 'path';
import { resolvers } from './resolvers';
import { typeDefs } from './typeDefs';
import session from 'express-session';
import mongoconnect from 'connect-mongo';

const MongoStore = mongoconnect(session);

const app = express();

let dbUrl = 'mongodb://localhost:27017/test';
mongoose.connect(dbUrl);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, "DB connection error"));

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

SERVER.applyMiddleware({
    app
});

existsSync(path.join(__dirname, "../images")) || mkdirSync(path.join(__dirname, "../images"));

app.use("/images", express.static(path.join(__dirname, "../images")));

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

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

app.get('/', function (req, res, next) {

});

app.post('/', function (req, res, next) {
    // Handle the post for this route
});

app.listen(3600, () => {
    console.log(`Server ready at port 3600`);
});

Solution

  • From the Express docs:

    The order of middleware loading is important: middleware functions that are loaded first are also executed first.

    Your session middleware needs to be applied before you apply the ApolloServer middleware.