Apollo-server: Using apollo server to forward header ?

Created on 24 Oct 2017  路  5Comments  路  Source: apollographql/apollo-server

I run into this issue when stitching two schema, but apollo server looks can't forward the header, so I switch to express-graphql. It did fix the problem https://github.com/AEB-labs/graphql-weaver/issues/6. But I don't want the 500 status code when something failed https://github.com/AEB-labs/graphql-weaver/issues/14. Apollo-server give me the status code I wanted in my test. So how do I use apollo server to forward header like auth? Thanks.

Most helpful comment

If I understand you correctly, you're looking for the ability to access a request header from your resolver. While express-graphql passes the request as context by default, that is often not what you want because it prevents you from setting the context yourself and putting additional properties on it.

In Apollo Server, you can add per-request information to your context by passing a function to graphqlExpress. In your case, something like this should work:

graphqlExpress(request => ({
  schema,
  context: { auth: request.header('Authentication') }
}))

All 5 comments

If I understand you correctly, you're looking for the ability to access a request header from your resolver. While express-graphql passes the request as context by default, that is often not what you want because it prevents you from setting the context yourself and putting additional properties on it.

In Apollo Server, you can add per-request information to your context by passing a function to graphqlExpress. In your case, something like this should work:

graphqlExpress(request => ({
  schema,
  context: { auth: request.header('Authentication') }
}))

Yeap, it's working, just pass req as context. Thanks.

graphqlExpress(req => {
  return ({
    schema: schema,
    context: req
  });
})

I am not seeing the request authorization header forwarded when using graphiqlExpress, it is forcing me to pass in passHeader, any idea why this is?

This issue is still relevant for Subscriptions.

I am trying to do something similar.. (i think). just want to add the authorization header from client call to be passed onto the graphql endpoints. not having much luck

const server = new ApolloServer({ 
    gateway, 
    subscriptions: false, 
    engine: {sendHeaders: {all: true}},
    context: (ctx:ExpressContext) => {
        console.log('ApolloServer ExpressContext', ctx.req.header('authorization'));  // header is there. 
        return {'authorization': ctx.req.header('authorization')}  // attempting to pass the header on to the graphql endpoint 
    }
 });

does this look right? adding that context element seems to break my request.

Was this page helpful?
0 / 5 - 0 ratings