Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Erick Wang Avatar asked Dec 17 '25 16:12

Erick Wang


2 Answers

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
like image 114
slideshowp2 Avatar answered Dec 20 '25 05:12

slideshowp2


The answer by @slideshowp2 is probably correct, but I couldn't get it working. Perhaps due to older version of Apollo Server.

Anyway, I solved this by settings a middleware to Express to add the required headers. Something like

const server = express();
const graphqlServer = new ApolloServer({...})
// ...

server.use('/graphql', (req, res, next) => {
  res.set({'custom-key': 'custom-value'});
  next();
});
graphqlServer.applyMiddleware({ app: server });
like image 36
kaskelotti Avatar answered Dec 20 '25 04:12

kaskelotti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!