Can't pass session data into Apollo Server Context

I tried to add Passport.JS for social login services that store confidential data (user_id) in session (express-session) and share to the client via cookie.

I can retrieve user_id from session from general route (like ‘/’, ‘/api’).

app.get('/api/current_user', (req, res,next)=>{
        res.send('Guess Login')
        res.send(`current user id ${}`)

The output of the console log from the above code as follow.

**Session {**
**  cookie: {**
**    path: '/',**
**    _expires: 2022-11-07T13:28:48.585Z,**
**    originalMaxAge: 86400000,**
**    httpOnly: true,**
**    secure: false**
**  },**
**  passport: { user: '102012197665909713239' }**

So, I thought the session part look fine. Then, I tried to pass into the Apollo Server via context. 

expressMiddleware(graphQLServer, {
context: async ({req, res}) => ({ req, res, session: req.session })

Unfortunately, it didn't pass user(passport) to Apollo as I tried to access in resolver. Please see the result below. 


**Session {**
**  cookie: {**
**    path: '/',**
**    _expires: 2022-11-07T13:28:52.830Z,**
**    originalMaxAge: 86400000,**
**    httpOnly: true,**
**    secure: false**
**  }**


Did I do something wrong?

Can you share how req.session is being set (where’s your passport js code)?
Is it in an app.get call maybe? Should it be in an app.use instead? (your graphql requests are probably post and wouldn’t hit middleware using app.get)

Do you have separate code blocks for adding cookie and adding passport to the session object? Most likely, your passport block isn’t running for graphql requests.

1 Like

Thanks for you reply Trevor. I could figure it out the solution yesterday. Which was I need to tweak a setting when initiating the Apollo Server after I read in and out of Apollo documentation.

const graphQLServer = new ApolloServer({
plugins: [ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginLandingPageLocalDefault({ includeCookies: true })],

Currently, I am building the api so I only tests the functionality with Apollo Studio. I hope I will not face the same issue when the api is accessed by React.JS even by omitting that setting.

1 Like