Search code examples
headerresponseapollo-server

Apollo Server Set Response Headers


I am currently using Apollo Server. I am trying to set an attribute in response headers. And this attribute is retrieved from client graphQL request headers.

I looked it up a bit online. And saw answers like using plugins or extensions. I tried below:

class FormatErrorWithContextExtension extends GraphQLExtension {
    willSendResponse(o) {
        const { context, graphqlResponse } = o;
        const { headers } = context;
        const myVar = headers['variable']
        o.graphqlResponse.http.headers.set("variable", myVar);
    }
}

function createApolloServer() {
    return new ApolloServer({
        typeDefs,
        resolvers,
        extensions: [() => new FormatErrorWithContextExtension()],
        ...
    });
}

From the client, it seems that it failed to set it to response headers. Any idea?


Solution

  • For "apollo-server": "^2.9.11", You can set the custom response headers in formatResponse method of ApolloServer class.

    E.g.

    server.ts:

    import { ApolloServer, gql } from 'apollo-server';
    import { GraphQLResponse, GraphQLRequestContext } from 'apollo-server-express/node_modules/apollo-server-core';
    
    const typeDefs = gql`
      type Query {
        _root: String
      }
    `;
    const resolvers = {
      Query: {
        _root: () => '_root',
      },
    };
    
    const server = new ApolloServer({
      typeDefs,
      resolvers,
      formatResponse: (response: GraphQLResponse | null, requestContext: GraphQLRequestContext<any>) => {
        if (requestContext.response && requestContext.response.http) {
          requestContext.response.http.headers.set('custom-key', 'custom-value');
        }
        return response as GraphQLResponse;
      },
    });
    
    server.listen().then(({ url }) => {
      console.log(`Apollo server is listening on ${url}`);
    });
    

    Now, you can get the custom-key response header from your client-side.

    Response Headers in the browser

    HTTP/1.1 200 OK
    X-Powered-By: Express
    Access-Control-Allow-Origin: *
    Content-Type: application/json; charset=utf-8
    custom-key: custom-value
    Content-Length: 27
    ETag: W/"1b-AQpb9d3mRlH09xAPu3kjw6hdh0M"
    Date: Wed, 08 Jan 2020 05:37:05 GMT
    Connection: keep-alive