question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

passport.js + apollo-server-express drop session

See original GitHub issue

if you use passport.js

const app = express();
app.use(session({
    secret: 'test',
}));
app.use(passport.initialize());
app.use(passport.session());
const server = new ApolloServer({
    typeDefs,
    resolvers,
    context: ({ req }) => {
        const user = req.user;

        console.log({ user, 'req.session': req.session });

        return {
            user,
            orm,
            dataloader: compose(orm),
        };
    },
});

app.use('/graphql', (req, res, next) => {
    console.log({
        url: req.protocol + '://' + req.get('host') + req.originalUrl,
        user: req.user,
        sessionID: req.sessionID,
        session: req.session,
        cookie: JSON.stringify(req.cookie),
    });

    return next();
});
server.applyMiddleware({ app, path: '/graphql' });

if i comment out server.applyMiddleware({ app, path: ‘/graphql’ });, passport js session is present, otherwise not

if session would be present, it would able to restore user

full PR: https://github.com/eugene-matvejev/node-explorer/pull/73

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

18reactions
arvicommented, Oct 9, 2019

@jonesmac I was so close to implementing your workaround since it’s been 3 days that I’ve been trying to figure out what the heck is wrong with my code why session cookies are not appearing on front-end but being saved in a store e.g in my case Redis. So the issue in my case is I need to also set the credentials: include in Apollo Client

I have posted my answer here for the front-end: https://github.com/apollographql/apollo-client/issues/4190#issuecomment-540023803

As for my back-end, it’s like this:

const corsOptions = {
  origin: ['http://localhost:5000', /\.myproject\.com$/],
  credentials: true,
};

app.use(cors(corsOptions));

// setup session handling options
const sessionOptions = {
  name: config.sessionStore.name,
  secret: config.sessionStore.secret,
  store: new RedisStore({ client: redisDB, prefix: config.sessionStore.redisSessionIdPrefix }),
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: config.sessionStore.lifetime,
    sameSite: true,
    secure: process.env.NODE_ENV === 'production',
  },
};
app.use(session(sessionOptions));


const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req, res }) => ({
    session: req.session,
    redis: redisDB,
  }),
  playground:
    process.env.NODE_ENV === 'production'
      ? false
      : {
        settings: {
          'request.credentials': 'include',
        },
      },
});

apolloServer.applyMiddleware({ app, path: '/graphql', cors: false });
3reactions
jkettmanncommented, Oct 17, 2019

If anyone is looking for a working example using Apollo server and Passport.js here are one without and one with graphql-passport. There is also a couple of blog posts linked there if you want a more detailed explanation.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Apollo express don't have express passport session
For our portal, i integrated my express server with passport to authenticate user. Once user authenticated need to fetch details for user from ......
Read more >
Subscriptions in Apollo Server - Apollo GraphQL Docs
To run both an Express app and a separate WebSocket server for subscriptions, we'll create an http.Server instance that effectively wraps the two...
Read more >
Authentication with GraphQL and Passport.js: The frontend
In this situation, the express server used in the GraphQL API implementation will reject requests from the frontend with a CORS error by...
Read more >
Jwt or Passport.js (sessions) ? : r/graphql - Reddit
Sessions are very easy to set up on passport, and require virtually nothing on the front end to manage. But they can be...
Read more >
GraphQL Server Tutorial with Apollo Server and Express
In the end, you should have a fully working GraphQL server boilerplate project that implements authentication, authorization, a data access ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found