Search code examples
graphqlapollo-serverkoaapollo-server-koa

How to access Koa context (and koa-session) from Apollo resolvers?


Given the following Koa application initialization :

const apolloServer = new ApolloServer({
  ...processSchema(schemas),
  ...graphqlConfig,
  cors: false,   // already present with Koa
  context: ctx => {
    console.log( "*** 2", ctx.session );
    // -> *** 2 undefined
  }
});

const app = new Koa();

const serverHttp = app
  .use(cors(CORS_CONFIG))
  .use(session(SESSION_CONFIG, app))
  .use(async (ctx, next) => {
    console.log( "*** 1", ctx.session );
    // *** 1 Session { ...session object }

    await next();

    if (!ctx.body) {
      ctx.throw(404);
    }
  })
  .use(koaBody())
  .use(apolloServer.getMiddleware())
  .listen(port)
;

As you can see, making any GraphQL query will output

*** 1 Session { ...session object }
*** 2 undefined

Showing that Apollo does not receive the context, neither the session.

  1. Is it possible to have access to the session from context function?
  2. Is it possible to have access to the session from a resolver?

Solution

  • Yes, it is possible to access session from the context function, and here's the way to do it:

    const server = new ApolloServer({
      typeDefs,
      resolvers,
      context: (req) => {
        const { session } = req.ctx;
    
        // return an object with whatever properties you 
        // need to be accessible inside resolvers as `context`
        return {
          userSession: session
        }
      }
    })
    

    Then, inside your resolver, you can access it the following way:

    const resolvers = {
      Query: {
        books: (parent, args, context) {
          const { userSession } = context;
          const books = [...];
    
          return books;
        }
      }
    }
    

    Hope this helps.